diff --git a/CODEOWNERS b/CODEOWNERS index 9b63d1bbd03930ed56c660264086ffc1266a52f8..81d411b4860e6baaff515d258356e6c6e84b2a56 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -129,8 +129,10 @@ zh-cn/device-dev/subsystems/subsys-toolchain-hdc-guide.md @Austin23 zh-cn/device-dev/subsystems/subsys-toolchain-hiperf.md @Austin23 zh-cn/device-dev/subsystems/subsys-xts-guide.md @Austin23 -zh-cn/application-dev/ability/ @RayShih -zh-cn/application-dev/ui/ @HelloCrease +zh-cn/application-dev/ability/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/IDL/ @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/device-usage-statistics/ @RayShih @shuaytao @wangzhen107 @inter515 +zh-cn/application-dev/ui/ @HelloCrease @qieqiewl @tomatodevboy @niulihua zh-cn/application-dev/notification/ @RayShih zh-cn/application-dev/windowmanager/ @ge-yafang zh-cn/application-dev/webgl/ @ge-yafang @@ -181,60 +183,22 @@ zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/file-management/ @qinxiaowang zh-cn/application-dev/application-test/ @HelloCrease +zh-cn/application-dev/device-usage-statistics/ @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-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 +266,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 +279,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,56 +328,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/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 @@ -423,20 +376,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 +399,74 @@ 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 @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethod-subtype.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errcode-inputmethod-framework.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errcode-usb.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-datashare.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-colorspace-manager.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-display.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-distributed-data_object.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-distributedKVStore.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-pasteboard.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-preferences.md @ge-yafang +zh-cn/application-dev/reference/errorcodes/errorcode-window.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-missionManager.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-permissionrequestresult.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-processrunninginfo.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-service-extension-context.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen +zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @RayShih @littlejerry1 @gwang2008 @ccllee @chengxingzhen + diff --git a/README_zh.md b/README_zh.md index ebf1bc8d7557d35f99eaacf8fd1427972d61d3b0..386fa1d7449553f92f399839d947a0dacd4e18b8 100644 --- a/README_zh.md +++ b/README_zh.md @@ -18,15 +18,15 @@ - master:最新开发版本。 - - OpenHarmony 3.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta2.md)了解版本详情。 + - OpenHarmony 3.2 Beta3版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.2-beta3.md)了解版本详情。 - OpenHarmony 3.1 Release版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.1-release.md)了解版本详情。 - 该已更新至OpenHarmony 3.1.1 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.1-release.md)了解版本详情。 + 该版本已更新至OpenHarmony 3.1.3 Release,点击[此处](zh-cn/release-notes/OpenHarmony-v3.1.3-release.md)了解版本详情。 - OpenHarmony 3.0 LTS版本:点击[此处](zh-cn/release-notes/OpenHarmony-v3.0-LTS.md)了解版本详情。 - 该版本已更新至OpenHarmony 3.0.5 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.5-LTS.md)了解版本详情。 + 该版本已更新至OpenHarmony 3.0.6 LTS,点击[此处](zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md)了解版本详情。 - OpenHarmony 2.2 Beta2版本:点击[此处](zh-cn/release-notes/OpenHarmony-v2.2-beta2.md)了解版本详情。 @@ -34,7 +34,7 @@ ### 历史稳定版本 -OpenHarmony_v1.x_release:OpenHarmony 1.1.4 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1-1-4-LTS.md)了解版本详情。 +OpenHarmony_v1.x_release:OpenHarmony 1.1.5 LTS稳定版本,点击[此处](zh-cn/release-notes/OpenHarmony-v1.1.5-LTS.md)了解版本详情。 如需了解更多版本详情,点击[此处](zh-cn/release-notes/)。 diff --git a/en/Legal-Notices.md b/en/Legal-Notices.md new file mode 100644 index 0000000000000000000000000000000000000000..80d301770e502de109fbcf861fe456168cd23ab1 --- /dev/null +++ b/en/Legal-Notices.md @@ -0,0 +1,21 @@ +# Legal Notices + +**Copyright (c) 2020-2022 OpenAtom OpenHarmony. All rights reserved.** + +## Copyright + +All copyrights of the OpenHarmony documents are reserved by OpenAtom OpenHarmony. + +The OpenHarmony documents are licensed under Creative Commons Attribution 4.0 International (CC BY 4.0). For easier understanding, you can visit [Creative Commons](https://creativecommons.org/licenses/by/4.0/) to get a human-readable summary of the license. For the complete content, see [Creative Commons Attribution 4.0 International Public License](https://creativecommons.org/licenses/by/4.0/legalcode). + +## Trademarks and Permissions + +No content provided in the OpenHarmony documentation shall be deemed as a grant of the approval or right to use any trademark, name, or logo of the OpenAtom Foundation and OpenAtom OpenHarmony. No third parties shall use any of the aforementioned trademarks, names, or logos in any way without explicit prior written permission of the OpenAtom Foundation. + +## Disclaimer + +The information in the OpenHarmony documents is subject to change without notice. + +The OpenHarmony documents are provided without any express or implied warranty. In any case, the OpenAtom Foundation or the copyright owner is not liable for any direct or indirect loss arising from the use of the OpenHarmony documents, regardless of the cause or legal theory, even if the OpenHarmony documents have stated that there is a possibility of such loss. + + \ No newline at end of file diff --git a/en/application-dev/Readme-EN.md b/en/application-dev/Readme-EN.md index f3fa0e7ac0e9b829f2418e4b1bf96001e66553d2..ca2c2fda1462b991f8ea60f36b5c181783034874 100644 --- a/en/application-dev/Readme-EN.md +++ b/en/application-dev/Readme-EN.md @@ -16,6 +16,7 @@ - [Application Package Structure Configuration File (Stage Model)](quick-start/stage-structure.md) - [SysCap](quick-start/syscap.md) - [HarmonyAppProvision Configuration File](quick-start/app-provision-structure.md) + - Development - [Ability Development](ability/Readme-EN.md) - [UI Development](ui/Readme-EN.md) @@ -26,6 +27,7 @@ - [Security](security/Readme-EN.md) - [Connectivity](connectivity/Readme-EN.md) - [Data Management](database/Readme-EN.md) + - [File Management](file-management/Readme-EN.md) - [Telephony](telephony/Readme-EN.md) - [Task Management](task-management/Readme-EN.md) - [Device Management](device/Readme-EN.md) diff --git a/en/application-dev/connectivity/ipc-rpc-development-guideline.md b/en/application-dev/connectivity/ipc-rpc-development-guideline.md index 1fddf868604e564e4b6a6701f8d3a8088c4d8326..0eeef8040da8abd9710f3996f0b5f2c65ecf71e2 100644 --- a/en/application-dev/connectivity/ipc-rpc-development-guideline.md +++ b/en/application-dev/connectivity/ipc-rpc-development-guideline.md @@ -10,7 +10,7 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat | Class/Interface | Function | Description | | --------------- | -------- | ----------- | -| IRemoteBroker | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | +| [IRemoteBroker](../reference/apis/js-apis-rpc.md#iremotebroker) | sptr AsObject() | Obtains the holder of a remote proxy object. This method must be implemented by the derived classes of **IRemoteBroker**. If you call this method on the stub, the **RemoteObject** is returned; if you call this method on the proxy, the proxy object is returned. | | IRemoteStub | virtual int OnRemoteRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) | Called to process a request from the proxy and return the result. Derived classes need to override this method. | | IRemoteProxy | | Service proxy classes are derived from the **IRemoteProxy** class. | @@ -25,10 +25,10 @@ IPC/RPC enables a proxy and a stub that run on different processes to communicat ``` class ITestAbility : public IRemoteBroker { public: - // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. - DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); - int TRANS_ID_PING_ABILITY = 1; // Define the message code. - virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. + // DECLARE_INTERFACE_DESCRIPTOR is mandatory, and the input parameter is std::u16string. + DECLARE_INTERFACE_DESCRIPTOR(u"test.ITestAbility"); + int TRANS_ID_PING_ABILITY = 1; // Define the message code. + virtual int TestPingAbility(const std::u16string &dummy) = 0; // Define functions. }; ``` diff --git a/en/application-dev/device/device-location-info.md b/en/application-dev/device/device-location-info.md index 4c51f50e9c29c9df846011e80c06a46a59045794..f3572352e718bb77493d7dd2d097d2d7a82058c9 100644 --- a/en/application-dev/device/device-location-info.md +++ b/en/application-dev/device/device-location-info.md @@ -66,25 +66,7 @@ To learn more about the APIs for obtaining device location information, see [Geo If your application needs to access the device location information when running on the background, it must be configured to be able to run on the background and be granted the **ohos.permission.LOCATION_IN_BACKGROUND** permission. In this way, the system continues to report device location information after your application moves to the background. - To allow your application to access device location information, declare the required permissions in the **module.json** file of your application. The sample code is as follows: - - - ``` - { - "module": { - "reqPermissions": [ - "name": "ohos.permission.LOCATION", - "reason": "$string:reason_description", - "usedScene": { - "ability": ["com.myapplication.LocationAbility"], - "when": "inuse" - } - ] - } - } - ``` - - For details about these fields, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). + You can declare the required permission in your application's configuration file. For details, see [Application Package Structure Configuration File](../quick-start/stage-structure.md). 2. Import the **geolocation** module by which you can implement all APIs related to the basic location capabilities. 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/file-management/Readme-EN.md b/en/application-dev/file-management/Readme-EN.md new file mode 100644 index 0000000000000000000000000000000000000000..4bb5fe54817e245807612eaac1a0b6d235101f7a --- /dev/null +++ b/en/application-dev/file-management/Readme-EN.md @@ -0,0 +1,6 @@ +# File Management +- MediaLibrary Management + - [MediaLibrary Overview](medialibrary-overview.md) + - [Media Asset Management](medialibrary-resource-guidelines.md) + - [File Path Management](medialibrary-filepath-guidelines.md) + - [Album Management](medialibrary-album-guidelines.md) \ No newline at end of file diff --git a/en/application-dev/file-management/medialibrary-album-guidelines.md b/en/application-dev/file-management/medialibrary-album-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..322e596ef6a0776291ab36529fb10760c09b4c51 --- /dev/null +++ b/en/application-dev/file-management/medialibrary-album-guidelines.md @@ -0,0 +1,94 @@ +# Album Management + +You can use the APIs provided by the **mediaLibrary** module to create and delete an album and obtain images in the album. + +> **NOTE** +> +> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. + +To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). + +## Obtaining Images and Videos in an Album + +You can obtain images and videos in an album in either of the following ways: + +- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified to obtain the media assets. For details, see [Querying Media Assets with the Specified Album Name](medialibrary-resource-guidelines#querying-media-assets-with-the-specified-album-name). + +- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. For details, see [Obtaining Images and Videos in an Album](medialibrary-resource-guidelines#obtaining-images-and-videos-in-an-album). + +## Creating an Album + +You can use [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1), with the relative path set, to create an album while adding a media asset to the album. The relative path is the album name. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to create an album named **myAlbum**. + +**How to Develop** + +1. Call **getPublicDirectory** to obtain the public directory that stores files of a certain type. + + For details about the operation, see [Obtaining a Public Directory](medialibrary-filepath-guidelines.md#obtaining-a-public-directory). + +2. Call **createAsset** to create an image, with the relative path set to **path + 'myAlbum/'**. + + This operation creates an album and adds an image to it. + +```ts +async function example() { + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_IMAGE) + // myAlbum is the path for storing the new file and the name of the new album. + media.createAsset(mediaType, 'test.jpg', path + 'myAlbum/', (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createAlbum successfully, message = ' + fileAsset); + } else { + console.info('createAlbum failed, message = ' + err); + } + }); +} +``` + +## Renaming an Album + +Renaming modifies the **FileAsset.albumName** attribute of the album, that is, the album name. After the modification, call [Album.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-3) to commit the modification to the database. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to rename the album **newAlbum**. + +**How to Develop** + +1. Create a retrieval condition for obtaining the target album. +2. Call **getAlbums** to obtain the album list. +3. Rename the album **newAlbum**. +4. Call **Album.commitModify** to commit the modification of the attributes to the database. + +```ts +async function example() { + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let albumList = await media.getAlbums(AlbumNoArgsfetchOp); + let album = albumList[0]; + album.albumName = 'newAlbum'; + // Void callback. + album.commitModify().then(function() { + console.info("albumRename successfully"); + }).catch(function(err){ + console.info("albumRename failed with error:"+ err); + }); +} +``` diff --git a/en/application-dev/file-management/medialibrary-filepath-guidelines.md b/en/application-dev/file-management/medialibrary-filepath-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..fc9b327031cfee8ea6de601b3c3d268bbf161c53 --- /dev/null +++ b/en/application-dev/file-management/medialibrary-filepath-guidelines.md @@ -0,0 +1,244 @@ +# File Path Management + +User data on OpenHarmony is managed by the **mediaLibrary** module in a unified manner. You can use the APIs provided by this module to access and operate the user data. + +> **NOTE** +> +> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. + +To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). + +## File Formats Supported by Public Directories + +Before using file paths for development, learn the file formats supported by each public directory. +> **CAUTION** +> +> The following table lists only the file types that can be identified by the system. In your application development, pay attention to the file formats supported by the corresponding interfaces.
For example, only .jpeg and .webp can be used for image encoding, and only .jpg, .png, .gif, .bmp, .webp, and .raw can be used for image decoding. + +| Directory | Directory Type | Media Type | Description | Supported File Format | +| ---------- | ------------- | ------------- | -------------- | ------------------------------------------------------------ | +| Camera/ | DIR_CAMERA | VIDEO and IMAGE | Directory for storing images and videos taken by the camera. Videos and images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif / .mp4 / .3gp / .mpg / .mov / .webm / .mkv | +| Videos/ | DIR_VIDEO | VIDEO | Dedicated video directory. Only videos can be stored in this directory and its subdirectories.| .mp4 / .3gp / .mpg / .mov / .webm / .mkv | +| Pictures/ | DIR_IMAGE | IMAGE | Dedicated image directory. Only images can be stored in this directory and its subdirectories.| .bmp / .bm / .gif / .jpg /. jpeg / .jpe / .png / .webp / .raw / .svg / .heif | +| Audios/ | DIR_AUDIO | AUDIO |Dedicated audio directory. Only audio files can be stored in this directory and its subdirectories.| .aac/.mp3/.flac/.wav/.ogg | +| Documents/ | DIR_DOCUMENTS | FILE |Dedicated file directory. Only files except audios, images, and videos can be stored in this directory and its subdirectories.| - | +| Download/ | DIR_DOWNLOAD | ALLTYPE |Directory for storing downloaded files. The types of files in this directory and its subdirectories are not restricted.| - | + +## Obtaining a Public Directory + +Different types of files are stored in different public directories. You can call [getPublicDirectory](../reference/apis/js-apis-medialibrary.md#getpublicdirectory8-1) to obtain the public directory that stores files of a certain type. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +The following describes how to obtain the public directory that stores camera files. + +```ts +async function example(){ + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let DIR_CAMERA = mediaLibrary.DirectoryType.DIR_CAMERA; + const dicResult = await media.getPublicDirectory(DIR_CAMERA); + if (dicResult == 'Camera/') { + console.info('mediaLibraryTest : getPublicDirectory passed'); + } else { + console.info('mediaLibraryTest : getPublicDirectory failed'); + } +} +``` + +## Copying Files Between the Application Sandbox and the Public Directory + +OpenHarmony provides the application sandbox to minimize the leakage of application data and user privacy information. + +Users can access files stored in the public directories through the system applications **Files** and **Gallery**. However, files in the application sandbox can be accessed only by the application itself. + +### Copying a File + +You can call [mediaLibrary.FileAsset.open](../reference/apis/js-apis-medialibrary.md#open8-1) to open a file in a public directory. + +You can call [fileio.open](../reference/apis/js-apis-fileio.md#fileioopen7) to open a file in the application sandbox. The sandbox directory can be accessed only through the application context. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. +- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. + +**How to Develop** + +1. Call [Context.getFilesDir](../reference/apis/js-apis-Context.md#contextgetfilesdir) to obtain the directory of the application sandbox. +2. Call **MediaLibrary.getFileAssets** and **FetchFileResult.getFirstObject** to obtain the first file in the result set of the public directory. +3. Call **fileio.open** to open the file in the sandbox. +4. Call **fileAsset.open** to open the file in the public directory. +5. Call **fileio.copyfile** to copy the file. +6. Call **fileAsset.close** and **fileio.close** to close the file. + +**Example 1: Copying Files from the Public Directory to the Sandbox** + +```ts +async function copyPublic2Sandbox() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let sandboxDirPath = globalThis.context.filesDir; + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + + let fdPub = await fileAsset.open('rw'); + let fdSand = await fileio.open(sandboxDirPath + '/testFile.txt', 0o2 | 0o100, 0o666); + await fileio.copyFile(fdPub, fdSand); + + await fileAsset.close(fdPub); + await fileio.close(fdSand); + + let content_sand = await fileio.readText(sandboxDirPath + '/testFile.txt'); + console.log('content read from sandbox file: ', content_sand) +} +``` + +**Example 2: Copying a File from the Sandbox to the Public Directory** + +```ts +async function copySandbox2Public() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let sandboxDirPath = globalThis.context.filesDir; + + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const publicDirPath = await media.getPublicDirectory(DIR_DOCUMENTS); + try { + let fileAsset = await media.createAsset(mediaLibrary.MediaType.FILE, 'testFile02.txt', publicDirPath); + console.info('createFile successfully, message = ' + fileAsset); + } catch (err) { + console.info('createFile failed, message = ' + err); + } + try { + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile02.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + var fileAsset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('file asset get failed, message = ', err) + } + var fdPub = await fileAsset.open('rw'); + var fdSand = await fileio.open(sandboxDirPath + 'testFile.txt', 0o2); + await fileio.copyFile(fdSand, fdPub); + await fileio.close(fdPub); + await fileio.close(fdSand); + let fdPubRead = await fileAsset.open('rw'); + try { + var arrayBuffer = new ArrayBuffer(4096); + await fileio.read(fdPubRead, arrayBuffer); + var content_pub = String.fromCharCode(new Uint8Array(arrayBuffer)); + fileAsset.close(fdPubRead); + } catch (err) { + console.log('read text failed, message = ', err); + } + console.log('content read from public file: ', content_pub); +} +``` + +### Reading and Writing a File + +You can use **FileAsset.open** and **FileAsset.close** of [mediaLibrary](../reference/apis/js-apis-medialibrary.md) to open and close a file, and use **fileio.read** and **fileio.write** of [fileio](../reference/apis/js-apis-fileio.md) to read and write a file. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. +- You have imported the module [@ohos.fileio](../reference/apis/js-apis-fileio.md) in addition to @ohos.multimedia.mediaLibrary. + +**How to Develop** + +1. Create a file. + + ```ts + async function example() { + let mediaType = mediaLibrary.MediaType.FILE; + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_DOCUMENTS); + media.createAsset(mediaType, "testFile.text", path).then (function (asset) { + console.info("createAsset successfully:"+ JSON.stringify(asset)); + }).catch(function(err){ + console.info("createAsset failed with error:"+ err); + }); + } + ``` + +2. Call **FileAsset.open** to open the file. + +3. Call **fileio.write** to write a string to the file. + +4. Call **fileio.read** to read the file and save the data read in an array buffer. + +5. Convert the array buffer to a string. + +6. Use **FileAsset.close** to close the file. + +**Example 1: Opening an Existing File and Writing Data to It** + +```ts +async function writeOnlyPromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAssetName: ', fileAsset.displayName); + + try { + let fd = await fileAsset.open('w'); + console.info('file descriptor: ', fd); + await fileio.write(fd, "Write file test content."); + await fileAsset.close(fd); + } catch (err) { + console.info('write file failed, message = ', err); + } +} +``` + +**Example 2: Opening an Existing File and Reading Data from It** + +```ts +async function readOnlyPromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey + let fileAssetFetchOp = { + selections: fileKeyObj.DISPLAY_NAME + '= ?' , + selectionArgs: ['testFile.txt'], + }; + let fetchResult = await media.getFileAssets(fileAssetFetchOp); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAssetName: ', fileAsset.displayName); + + try { + let fd = await fileAsset.open('r'); + let arrayBuffer = new ArrayBuffer(4096); + await fileio.read(fd, arrayBuffer); + let fileContent = String.fromCharCode(...new Uint8Array(arrayBuffer)); + globalThis.fileContent = fileContent + globalThis.fileName = fileAsset.displayName; + console.info('file content: ', fileContent); + await fileAsset.close(fd); + } catch (err) { + console.info('read file failed, message = ', err); + } +} +``` diff --git a/en/application-dev/file-management/medialibrary-overview.md b/en/application-dev/file-management/medialibrary-overview.md new file mode 100644 index 0000000000000000000000000000000000000000..79f13fe066967607ab15f096fe3ce5478aaa9abe --- /dev/null +++ b/en/application-dev/file-management/medialibrary-overview.md @@ -0,0 +1,127 @@ +# MediaLibrary Development Overview + +The **mediaLibrary** module provides APIs for you to access and modify media files. + +- You can manage [media assets (audios, videos, image, and files)](medialibrary-resource-guidelines.md) as follows: + - Query media assets. + - Obtain an image or a video. + - Obtain the thumbnail of an image or a video. + - Create a media asset. + - Rename a media asset. + - Move a media asset to the recycle bin. +- You can manage [file paths](medialibrary-filepath-guidelines.md) as follows: + - Obtain the public directory that stores files of a certain type. + - Copy files between the application sandbox and the public directory. + - Read and write a file. +- You can manage [albums](medialibrary-album-guidelines.md) as follows: + - Obtain images and videos in an album. + - Create an album. + - Rename an album. + +> **NOTE** +> +> This development guide applies only to the stage model (available from API version 9). + +To access and modify personal media data, an application must obtain a **MediaLibrary** instance and request the media asset read and write permissions from the user. + +Before using the **MediaLibrary** APIs to develop features, you must learn how to: + +- [Obtain a MediaLibrary Instance](#obtaining-a-medialibrary-instance) +- [Request Permissions](#requesting-permissions) + +## Obtaining a MediaLibrary Instance + +An application must call [getMediaLibrary](../reference/apis/js-apis-medialibrary.md#medialibrarygetmedialibrary8) to obtain a **MediaLibrary** instance based on the application context. Through this instance, the application can access and modify personal media data (such as audios, videos, images, and files). + +**How to Develop** + +1. Import the **mediaLibrary** module. +2. Call **getContext** to obtain the application context. +3. Obtain a **MediaLibrary** instance. + +```ts +import mediaLibrary from '@ohos.multimedia.mediaLibrary'; + +const context = getContext(this); +var media = mediaLibrary.getMediaLibrary(context); +``` + +## Requesting Permissions + +To read and write a **MediaLibrary** instance, you must have the required permissions, as described in the table below. Before requesting the permissions, ensure that the [basic principles for permission management](../security/accesstoken-overview.md#basic-principles-for-permission-management) are met. + +| Permission | Description | Authorization Mode | +| ------------------------------ | ------------------------------------------ | ---------- | +| ohos.permission.READ_MEDIA | Allows an application to read media files from the user's external storage.| user_grant | +| ohos.permission.WRITE_MEDIA | Allows an application to read media files from and write media files into the user's external storage.| user_grant | +| ohos.permission.MEDIA_LOCATION | Allows an application to access geographical locations in the user's media file.| user_grant | + +After configuring the permissions in the **module.json5** file, the application must call [Context.requestPermissionsFromUser](../reference/apis/js-apis-ability-context.md#abilitycontextrequestpermissionsfromuser) to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. + +> **NOTE**
Even if the user has granted a permission, the application must check for the permission before calling an API protected by the permission. It should not persist the permission granted status, because the user can revoke the permission through the system application **Settings**. + +**How to Develop** + +1. Declare the permissions in the **module.json5** file. Add the **requestPermissions** tag under **module** in the file, and set the tag based on the project requirements. For details about the tag, see [Guide for Requesting Permissions from User](../security/accesstoken-guidelines.md). + + ```json + { + "module": { + "requestPermissions": [ + { + "name": "ohos.permission.MEDIA_LOCATION", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.READ_MEDIA", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "always" + } + }, + { + "name": "ohos.permission.WRITE_MEDIA", + "reason": "$string:reason", + "usedScene": { + "abilities": [ + "MainAbility" + ], + "when": "always" + } + } + ] + } + } + ``` + +2. Call **requestPermissionsFromUser** to check for the required permissions and if they are not granted, request the permissions from the user by displaying a dialog box. + + ```ts + import Ability from '@ohos.application.Ability' + + export default class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + var permissions=['ohos.permission.READ_MEDIA','ohos.permission.WRITE_MEDIA'] + var permissionRequestResult; + this.context.requestPermissionsFromUser(permissions,(err,result) => { + if(err){ + console.log('requestPermissionsFromUserError: ' + JSON.stringify(err)); + }else{ + permissionRequestResult=result; + console.log('permissionRequestResult: ' + JSON.stringify(permissionRequestResult)); + } + }); + } + } + ``` + + diff --git a/en/application-dev/file-management/medialibrary-resource-guidelines.md b/en/application-dev/file-management/medialibrary-resource-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..737ea4e48fa24c38f47fe7595e9df6e1370ab69a --- /dev/null +++ b/en/application-dev/file-management/medialibrary-resource-guidelines.md @@ -0,0 +1,389 @@ +# Media Asset Management + +Your applications can use the APIs provided by the **mediaLibrary** module to perform operations on media assets such as audios, videos, images, and files. + +> **NOTE** +> +> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**. + +To ensure the application running efficiency, most **MediaLibrary** API calls are asynchronous, and both callback and promise modes are provided for these APIs. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md). + +## Querying Media Assets + +You can query media assets by condition such as the media type, date, or album name. + +To do so, call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1), with a **MediaFetchOptions** object passed in to specify the conditions. In this object, **MediaFetchOptions.selections** are the retrieval conditions, and the enumerated values of **FileKey** are used as the column names of the conditions; **MediaFetchOptions.selectionArgs** are the values of the conditions. You can also specify **order** (sorting mode of the search result), **uri** (file URI), and **networkId** (network ID of the registered device) as the conditions. + +To obtain the object at the specified position (for example, the first, the last, or with the specified index) in the result set, call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7). In this section, **getNextObject** is used cyclically to obtain all media assets in the result set. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +### Querying Media Assets with the Specified Media Type + +The following describes how to obtain images. + +**How to Develop** + +To specify the media type as the retrieval condition, set **selections** to **FileKey.MEDIA_TYPE**. + +To specify the image as the media type, set **selectionArgs** to **MediaType.IMAGE**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.IMAGE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +### Querying Media Assets with the Specified Date + +The following describes how to obtain media assets that are added on the specified date. You can also use the modification date and shooting date as the retrieval conditions. + +To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**. + +To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let option = { + selections: fileKeyObj.DATE_ADDED + '= ?', + selectionArgs: ['2022-8-5'], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +### Querying Media Assets and Sorting Them + +The following describes how to query images and sort them in descending order by the date when they are added. You can also sort them in ascending order. + +To sort files in descending order by the date when they are added, set **order** to **FileKey.DATE_ADDED + " DESC"**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.IMAGE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +### Querying Media Assets with the Specified Album Name + +The following describes how to query media assets in **myAlbum**. + +To specify the album name as the retrieval condition, set **selections** to **FileKey.ALBUM_NAME**. + +To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.IMAGE + let option = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs: ['myAlbum'], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + for (let i = 0; i < fetchFileResult.getCount(); i++) { + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName ' + i + ': ' + fileAsset.displayName); + }) + } +} +``` + +## Obtaining Images and Videos in an Album + +You can obtain media assets in an album in either of the following ways: + +- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name). +- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +**How to Develop** + +The following describes how to obtain videos in an album named **New Album 1**. + +1. Create a retrieval condition for obtaining the target **Album** instance. + + ```ts + let fileKeyObj = mediaLibrary.FileKey; + let AlbumNoArgsFetchOp = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'] + } + ``` + +2. Create a retrieval condition for obtaining videos in the target album. + + ```ts + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.VIDEO; + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + } + ``` + +3. Call **Album.getFileAssets** to obtain the videos in the target album. + +Complete sample code: + +```ts +async function getCameraImagePromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + } + let AlbumNoArgsFetchOp = { + selections: fileKeyObj.ALBUM_NAME + '= ?', + selectionArgs:['New Album 1'] + } + + let albumList = await media.getAlbums(AlbumNoArgsFetchOp); + if (albumList.length > 0) { + const album = albumList[0]; + let fetchFileResult = await album.getFileAssets(imagesFetchOp); + let count = fetchFileResult.getCount(); + console.info("get mediaLibrary IMAGE number", count); + } else { + console.info('getAlbum list is: 0'); + } +} +``` + +## Obtaining the Thumbnail of an Image or a Video + +You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#getthumbnail8-2) with the thumbnail size passed in to obtain the thumbnail of an image or a video. Thumbnails are usually displayed on the UI. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.READ_MEDIA**. + +### Obtaining the Thumbnail of an Image + +Your application may need to obtain the thumbnail of an image for preview purposes. + +The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album. + +**How to Develop** + +1. Create a retrieval condition for obtaining images in the target album. +2. Call **getFileAssets** to obtain the images in the target album. +3. Call **getFirstObject** to obtain the first image among all the images obtained. +4. Call **getThumbnail** to obtain the thumbnail of the first image. + +```ts +async function getFirstThumbnailPromise() { + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let imagesFetchOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + } + + let size = { width: 720, height: 720 }; + const fetchFileResult = await media.getFileAssets(imagesFetchOp); + if (fetchFileResult != undefined) { + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail(size).then((pixelMap) => { + pixelMap.getImageInfo().then((info) => { + console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height); + }).catch((err) => { + console.info("getImageInfo failed with error:" + err); + }); + }).catch((err) => { + console.info("getImageInfo failed with error:" + err); + }); + } else { + console.info("get image failed with error"); + } +} +``` + +## Creating a Media Asset + +You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1) to create a media asset. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. +- [Obtain the public directory](medialibrary-filepath-guidelines.md). + +The following describes how to create a file of the **MediaType.FILE** type. + +```ts +async function example() { + let mediaType = mediaLibrary.MediaType.FILE; + let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const path = await media.getPublicDirectory(DIR_DOCUMENTS); + media.createAsset(mediaType, "testFile.text", path).then ((asset) => { + console.info("createAsset successfully:"+ JSON.stringify(asset)); + }).catch((err) => { + console.info("createAsset failed with error:"+ err); + }); +} +``` + +## Moving a Media Asset to the Recycle Bin + +You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin. + +By default, files in the recycle bin will be stored for 30 days. During this period, you can set **isTrash** in **trash** to **false** to recover the files from the recycle bin. Application users can also recover the files through the system applications **Files** or **Gallery**. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to move the first file in the result set to the recycle bin. + +**How to Develop** + +1. Create a retrieval condition for obtaining images in the target album. +2. Call **getFileAssets** to obtain the images in the target album. +3. Call **getFirstObject** to obtain the first image among all the images obtained. +4. Call **trash** to move the first image to the recycle bin. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.FILE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset == undefined) { + console.error('asset not exist') + return + } + // Void callback. + asset.trash(true).then(() => { + console.info("trash successfully"); + }).catch((err) => { + console.info("trash failed with error:"+ err); + }); +} +``` + +## Renaming a Media Asset + +Renaming modifies the **FileAsset.displayName** attribute of a file, that is, the displayed file name, including the file name extension. + +After the modification, call [FileAsset.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-1) to commit the modification to the database. + +Before renaming a file, you must call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7) to obtain the file. + +**Prerequisites** + +- You have obtained a **MediaLibrary** instance. +- You have granted the permission **ohos.permission.WRITE_MEDIA**. + +The following describes how to rename the first file in the result set as **newtitle.text**. + +**How to Develop** + +1. Create a retrieval condition for obtaining images in the target album. +2. Call **getFileAssets** to obtain the images in the target album. +3. Call **getFirstObject** to obtain the first image among all the images obtained. +4. Rename the image as **newImage.jpg**. +5. Call **FileAsset.commitModify** to commit the modification of the attributes to the database. + +```ts +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let fileType = mediaLibrary.MediaType.FILE + let option = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + }; + const context = getContext(this); + var media = mediaLibrary.getMediaLibrary(context); + const fetchFileResult = await media.getFileAssets(option); + let asset = await fetchFileResult.getFirstObject(); + if (asset == undefined) { + console.error('asset not exist') + return + } + asset.displayName = 'newImage.jpg'; + // Void callback. + asset.commitModify((err) => { + if (err) { + console.error('fileRename Failed '); + return; + } + console.log('fileRename successful.'); + }) +} +``` diff --git a/en/application-dev/quick-start/arkts-rendering-control.md b/en/application-dev/quick-start/arkts-rendering-control.md new file mode 100644 index 0000000000000000000000000000000000000000..06862c299448fea4052c690ac45eb29caae1c636 --- /dev/null +++ b/en/application-dev/quick-start/arkts-rendering-control.md @@ -0,0 +1,282 @@ +# Rendering Control + +ArkTS provides conditional rendering and loop rendering. Conditional rendering can render state-specific UI content based on the application status. Loop rendering iteratively obtains data from the data source and creates the corresponding component during each iteration. + +## Conditional Rendering + +Use **if/else** for conditional rendering. + + +> **NOTE** +> +> - State variables can be used in the **if/else** statement. +> +> - The **if/else** statement can be used to implement rendering of child components. +> +> - The **if/else** statement must be used in container components. +> +> - Some container components limit the type or number of subcomponents. When **if/else** is placed in these components, the limitation applies to components created in **if/else** statements. For example, when **if/else** is used in the **\** container component, whose child components can only be **\**, only the **\** component can be used in the **if/else** statement. + + +```ts +Column() { + if (this.count < 0) { + Text('count is negative').fontSize(14) + } else if (this.count % 2 === 0) { + Text('count is even').fontSize(14) + } else { + Text('count is odd').fontSize(14) + } +} +``` + +## Loop Rendering + +You can use **ForEach** to obtain data from arrays and create components for each data item. + +``` +ForEach( + arr: any[], + itemGenerator: (item: any, index?: number) => void, + keyGenerator?: (item: any, index?: number) => string +) +``` + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| arr | any[] | Yes | An array, which can be empty, in which case no child component is created. The functions that return array-type values are also allowed, for example, **arr.slice (1, 3)**. The set functions cannot change any state variables including the array itself, such as **Array.splice**, **Array.sort**, and **Array.reverse**.| +| itemGenerator | (item: any, index?: number) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.| +| keyGenerator | (item: any, index?: number) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **ForEach**.| + +> **NOTE** +> +> - **ForEach** must be used in container components. +> +> - The generated child components should be allowed in the parent container component of **ForEach**. +> +> - The **itemGenerator** function can contain an **if/else** statement, and an **if/else** statement can contain **ForEach**. +> +> - The call sequence of **itemGenerator** functions may be different from that of the data items in the array. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage: +> +> ```ts +> ForEach(anArray.map((item1, index1) => { return { i: index1 + 1, data: item1 }; }), +> item => Text(`${item.i}. item.data.label`), +> item => item.data.id.toString()) +> ``` + +## Example + +```ts +// xxx.ets +@Entry +@Component +struct MyComponent { + @State arr: number[] = [10, 20, 30] + + build() { + Column({ space: 5 }) { + Button('Reverse Array') + .onClick(() => { + this.arr.reverse() + }) + + ForEach(this.arr, (item: number) => { + Text(`item value: ${item}`).fontSize(18) + Divider().strokeWidth(2) + }, (item: number) => item.toString()) + } + } +} +``` + +![forEach1](figures/forEach1.gif) + +## Lazy Loading + +You can use **LazyForEach** to iterate over provided data sources and create corresponding components during each iteration. + +```ts +LazyForEach( + dataSource: IDataSource, + itemGenerator: (item: any) => void, + keyGenerator?: (item: any) => string +): void + +interface IDataSource { + totalCount(): number; + getData(index: number): any; + registerDataChangeListener(listener: DataChangeListener): void; + unregisterDataChangeListener(listener: DataChangeListener): void; +} + +interface DataChangeListener { + onDataReloaded(): void; + onDataAdd(index: number): void; + onDataMove(from: number, to: number): void; + onDataDelete(index: number): void; + onDataChange(index: number): void; +} +``` + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------------------- | ---- | ------------------------------------------------------------ | +| dataSource | IDataSource | Yes | Object used to implement the **IDataSource** API. You need to implement related APIs. | +| itemGenerator | (item: any) => void | Yes | A lambda function used to generate one or more child components for each data item in an array. A single child component or a list of child components must be included in parentheses.| +| keyGenerator | (item: any) => string | No | An anonymous function used to generate a unique and fixed key value for each data item in an array. This key value must remain unchanged for the data item even when the item is relocated in the array. When the item is replaced by a new item, the key value of the new item must be different from that of the existing item. This key-value generator is optional. However, for performance reasons, it is strongly recommended that the key-value generator be provided, so that the development framework can better identify array changes. For example, if no key-value generator is provided, a reverse of an array will result in rebuilding of all nodes in **LazyForEach**.| + +### Description of IDataSource + +| Name | Description | +| ------------------------------------------------------------ | ---------------------- | +| totalCount(): number | Obtains the total number of data records. | +| getData(index: number): any | Obtains the data corresponding to the specified index. | +| registerDataChangeListener(listener:DataChangeListener): void | Registers a listener for data changes.| +| unregisterDataChangeListener(listener:DataChangeListener): void | Deregisters a listener for data changes.| + +### Description of DataChangeListener + +| Name | Description | +| -------------------------------------------------------- | -------------------------------------- | +| onDataReloaded(): void | Invoked when all data is reloaded. | +| onDataAdded(index: number): void (deprecated) | Invoked when data is added to the position indicated by the specified index. | +| onDataMoved(from: number, to: number): void (deprecated) | Invoked when data is moved from the **from** position to the **to** position.| +| onDataDeleted(index: number): void (deprecated) | Invoked when data is deleted from the position indicated by the specified index. | +| onDataChanged(index: number): void (deprecated) | Invoked when data in the position indicated by the specified index is changed. | +| onDataAdd(index: number): void 8+ | Invoked when data is added to the position indicated by the specified index. | +| onDataMove(from: number, to: number): void 8+ | Invoked when data is moved from the **from** position to the **to** position.| +| onDataDelete(index: number): void 8+ | Invoked when data is deleted from the position indicated by the specified index. | +| onDataChange(index: number): void 8+ | Invoked when data in the position indicated by the specified index is changed. | + +## Example + +```ts +// xxx.ets +class BasicDataSource implements IDataSource { + private listeners: DataChangeListener[] = [] + + public totalCount(): number { + return 0 + } + + public getData(index: number): any { + return undefined + } + + registerDataChangeListener(listener: DataChangeListener): void { + if (this.listeners.indexOf(listener) < 0) { + console.info('add listener') + this.listeners.push(listener) + } + } + + unregisterDataChangeListener(listener: DataChangeListener): void { + const pos = this.listeners.indexOf(listener); + if (pos >= 0) { + console.info('remove listener') + this.listeners.splice(pos, 1) + } + } + + notifyDataReload(): void { + this.listeners.forEach(listener => { + listener.onDataReloaded() + }) + } + + notifyDataAdd(index: number): void { + this.listeners.forEach(listener => { + listener.onDataAdd(index) + }) + } + + notifyDataChange(index: number): void { + this.listeners.forEach(listener => { + listener.onDataChange(index) + }) + } + + notifyDataDelete(index: number): void { + this.listeners.forEach(listener => { + listener.onDataDelete(index) + }) + } + + notifyDataMove(from: number, to: number): void { + this.listeners.forEach(listener => { + listener.onDataMove(from, to) + }) + } +} + +class MyDataSource extends BasicDataSource { + // Initialize the data list. + private dataArray: string[] = ['/path/image0.png', '/path/image1.png', '/path/image2.png', '/path/image3.png'] + + public totalCount(): number { + return this.dataArray.length + } + + public getData(index: number): any { + return this.dataArray[index] + } + + public addData(index: number, data: string): void { + this.dataArray.splice(index, 0, data) + this.notifyDataAdd(index) + } + + public pushData(data: string): void { + this.dataArray.push(data) + this.notifyDataAdd(this.dataArray.length - 1) + } +} + +@Entry +@Component +struct MyComponent { + private data: MyDataSource = new MyDataSource() + + build() { + List({ space: 3 }) { + LazyForEach(this.data, (item: string) => { + ListItem() { + Row() { + Image(item).width(50).height(50) + Text(item).fontSize(20).margin({ left: 10 }) + }.margin({ left: 10, right: 10 }) + } + .onClick(() => { + // The count increases by one each time the list is clicked. + this.data.pushData('/path/image' + this.data.totalCount() + '.png') + }) + }, item => item) + } + } +} +``` + +> **NOTE** +> +> - **LazyForEach** must be used in the container component. Currently, only the **\**, **\**, and **\** components support lazy loading (that is, only the visible part and a small amount of data before and after the visible part are loaded for caching). For other components, all data is loaded at a time. +> +> - **LazyForEach** must create and only one child component in each iteration. +> +> - The generated child components must be allowed in the parent container component of **LazyForEach**. +> +> - **LazyForEach** can be included in an **if/else** statement, but cannot contain such a statement. +> +> - For the purpose of high-performance rendering, when the **onDataChange** method of the **DataChangeListener** object is used to update the UI, the component update is triggered only when the state variable is used in the child component created by **itemGenerator**. +> +> - The call sequence of **itemGenerator** functions may be different from that of the data items in the data source. During the development, do not assume whether or when the **itemGenerator** and **keyGenerator** functions are executed. The following is an example of incorrect usage: +> +> ```ts +> LazyForEach(dataSource, +> item => Text(`${item.i}. item.data.label`)), +> item => item.data.id.toString()) +> ``` + +![lazyForEach](figures/lazyForEach.gif) diff --git a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md index 9baaba331069e20f35abb254d9761549b9c6f33e..71cc213f3ba56b31af7c5f1b4dc7bc9bb924b1fd 100644 --- a/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md +++ b/en/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @@ -2,18 +2,15 @@ -HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop, distributed platform developed based on the IntelliJ IDEA Community (Open Source) Edition. It helps you develop versatile all-device, all-scenario applications, offering distributed multi-device development, debugging, and simulation, as well as comprehensive quality and security safeguards. +HUAWEI DevEco Studio For OpenHarmony (DevEco Studio for short) is a one-stop integrated development environment (IDE) powered by the IntelliJ IDEA Community Edition and oriented to OpenHarmony devices in all scenarios. It allows you to create project templates, and develop, build, debug, and release OpenHarmony applications from end to end. -[DevEco Studio 3.0 Beta3](https://developer.harmonyos.com/cn/develop/deveco-studio#download_beta_openharmony) stands out in the following aspects: +[DevEco Studio](https://developer.harmonyos.com/en/develop/deveco-studio/) stands out in the following aspects: -- One-stop information acquisition platform -- A wide range of device project templates -- Efficient code editing -- Visualized UI development -- Bidirectional and instant UI preview -- High-performing compilation tool Hvigor -- Support for application development based on the device System Capability (SysCap) sets -- Automatic application signing mechanism -- A diverse array of code debugging and profiling features +- **Efficient and intelligent code editing**: Code highlighting, intelligent code completion, code error check, automatic code navigation, code formatting, and code search for programming languages such as ArkTS, JavaScript, and C/C++. For details, see [Editor Usage Tips](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-editor-usage-tips-0000001263360493). +- **Low-code development**: A diverse array of features to punch up your UI development productivity, including component drag and drop, visualized data binding, instant previewing, and low-code development for service widgets. For details, see [Using Low-Code Development](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652). +- **Multi-device bidirectional real-time preview**: Bidirectional preview, real-time preview, live preview, component preview, and multi-device preview of UI code to quickly view how your code runs on devices. For details, see [Previewing Your App/Service](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596). +- **High-performance build system**: Hvigor, a compilation and building tool to compile and package applications/services in one-click mode, better supporting ArkTS/JS development. +- **One-stop information acquisition**: A one-stop information acquisition platform that takes into account the developer journey of learning, development, and help seeking, in order to facilitate developer activities. +- **Efficient code debugging**: Various debugging capabilities such as TS, JS, and C/C++ code breakpoint setting, single-step execution, and variable viewing, improving the efficiency of analyzing application/service issues. -For more information, see [HUAWEI DevEco Studio For OpenHarmony User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). +For more information, see [DevEco Studio (OpenHarmony) User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-deveco-studio-overview-0000001263280421). diff --git a/en/application-dev/quick-start/figures/forEach1.gif b/en/application-dev/quick-start/figures/forEach1.gif new file mode 100644 index 0000000000000000000000000000000000000000..8e9e35e98b8c5fec6baf58997ae78992a554e069 Binary files /dev/null and b/en/application-dev/quick-start/figures/forEach1.gif differ diff --git a/en/application-dev/quick-start/figures/lazyForEach.gif b/en/application-dev/quick-start/figures/lazyForEach.gif new file mode 100644 index 0000000000000000000000000000000000000000..e8f92b92fd63c572e22964d8caa6132d318cf5bd Binary files /dev/null and b/en/application-dev/quick-start/figures/lazyForEach.gif differ diff --git a/en/application-dev/quick-start/syscap.md b/en/application-dev/quick-start/syscap.md index 1df5e3c82b4d6e97af1069d65b93336d84788cb4..07570f1359d7a4ead492ea15e02624f35e4e12c1 100644 --- a/en/application-dev/quick-start/syscap.md +++ b/en/application-dev/quick-start/syscap.md @@ -8,6 +8,10 @@ SysCap is short for System Capability. It refers to a standalone feature in the ![image-20220326064841782](figures/image-20220326064841782.png) +For details about the SysCap sets in OpenHarmony, see [SysCap List](../reference/syscap-list.md). + + + ### Supported SysCap Set, Associated SysCap Set, and Required SysCap Set The supported SysCap set, associated SysCap set, and required SysCap set are collections of SysCaps. @@ -60,14 +64,14 @@ You can add APIs to the associated SysCap set in DevEco Studio by adding system Exercise caution when modifying the required SysCap set. Incorrect modifications may result in the application being unable to be distributed to the target device. ```json -/* syscap.json */ +// syscap.json { "devices": { - "general": [ /* General devices. Each general device supports a SysCap set. Multiple general devices can be configured. */ + "general": [ // General devices. Each general device supports a SysCap set. Multiple general devices can be configured. "default", "car" ], - "custom": [ /* Custom devices. */ + "custom": [ // Custom devices. { "Custom device": [ "SystemCapability.Communication.SoftBus.Core" @@ -75,12 +79,12 @@ Exercise caution when modifying the required SysCap set. Incorrect modifications } ] }, - "development": { /* The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. */ + "development": { // The SysCap set in addedSysCaps and the SysCap set supported by each device configured in devices form the associated SysCap set. "addedSysCaps": [ "SystemCapability.Location.Location.Lite" ] }, - "production": { /* Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. */ + "production": { // Used to generate the RPCID. Exercise caution when adding this parameter. Under incorrect settings, applications may fail to be distributed to target devices. "addedSysCaps": [], // Intersection of SysCap sets supported by devices configured in devices. It is the required SysCap set with addedSysCaps set and removedSysCaps set. "removedSysCaps": [] // When the required SysCap set is a capability subset of a device, the application can be distributed to the device. } diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index beab6e2411714274074d3e0cbdfb13cc60ba574b..754d30b06c7dda42dbe16203be2342bf6f70fc2a 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -45,6 +45,7 @@ - [@ohos.application.formInfo](js-apis-formInfo.md) - [@ohos.application.formProvider](js-apis-formprovider.md) - [@ohos.application.missionManager](js-apis-missionManager.md) + - [@ohos.application.quickFixManager](js-apis-application-quickFixManager.md) - [@ohos.application.Want](js-apis-application-Want.md) - [@ohos.continuation.continuationManager](js-apis-continuation-continuationExtraParams.md) - [@ohos.continuation.continuationManager](js-apis-continuation-continuationManager.md) @@ -68,13 +69,13 @@ - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.defaultAppManager](js-apis-bundle-defaultAppManager.md) - [@ohos.bundle.innerBundleManager)](js-apis-Bundle-InnerBundleManager.md) - - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.distributedBundle)](js-apis-Bundle-distributedBundle.md) - [@ohos.zlib](js-apis-zlib.md) - bundle/[AbilityInfo](js-apis-bundle-AbilityInfo.md) - bundle/[ApplicationInfo](js-apis-bundle-ApplicationInfo.md) - bundle/[BundleInfo](js-apis-bundle-BundleInfo.md) - bundle/[BundleInstaller](js-apis-bundle-BundleInstaller.md) + - bundle/[BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) - bundle/[CustomizeData](js-apis-bundle-CustomizeData.md) - bundle/[DispatchInfo](js-apis-dispatchInfo.md) - bundle/[ElementName](js-apis-bundle-ElementName.md) @@ -86,15 +87,17 @@ - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) - bundle/[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.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.promptAction](js-apis-promptAction.md) - [@ohos.router](js-apis-router.md) - - [@ohos.uiAppearance](js-apis-uiappearance.md) - Graphics - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) - [@ohos.display ](js-apis-display.md) - [@ohos.effectKit](js-apis-effectKit.md) + - [@ohos.graphics.colorSpaceManager](js-apis-colorSpaceManager.md) - [@ohos.screen](js-apis-screen.md) - [@ohos.screenshot](js-apis-screenshot.md) - [@ohos.window](js-apis-window.md) @@ -133,7 +136,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) @@ -145,6 +147,7 @@ - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) - [@ohos.fileio](js-apis-fileio.md) + - [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) @@ -160,9 +163,13 @@ - [@ohos.telephony.sms](js-apis-sms.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.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 @@ -174,8 +181,8 @@ - [@ohos.rpc](js-apis-rpc.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - - [@ohos.nfc.tag](js-apis-nfctech.md) - - [@ohos.nfc.tag](js-apis-tagSession.md) + - 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) @@ -196,6 +203,7 @@ - [@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 @@ -255,8 +263,10 @@ - [@ohos.application.testRunner](js-apis-testRunner.md) - [@ohos.uitest](js-apis-uitest.md) - APIs No Longer Maintained + - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@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) @@ -278,4 +288,4 @@ - [@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 + - [console](js-apis-logs.md) diff --git a/en/application-dev/reference/apis/figures/en-us_image_0001.gif b/en/application-dev/reference/apis/figures/en-us_image_0001.gif new file mode 100644 index 0000000000000000000000000000000000000000..099acf91f8a1a6936c56e0ae09aaf7530b080828 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0001.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0002.gif b/en/application-dev/reference/apis/figures/en-us_image_0002.gif new file mode 100644 index 0000000000000000000000000000000000000000..6e4c041811c24ffba57eee64c64d12532150fe4b Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0002.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0004.gif b/en/application-dev/reference/apis/figures/en-us_image_0004.gif new file mode 100644 index 0000000000000000000000000000000000000000..f622ab0eca3995baece321539984c289ab1b8b1a Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0004.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0005.gif b/en/application-dev/reference/apis/figures/en-us_image_0005.gif new file mode 100644 index 0000000000000000000000000000000000000000..5d904fbfabdc50751afd51e9a29b0aa18c6e445f Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0005.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0006.gif b/en/application-dev/reference/apis/figures/en-us_image_0006.gif new file mode 100644 index 0000000000000000000000000000000000000000..7477b94b0437fadfc2d875841f182648d1bcccc9 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0006.gif differ diff --git a/en/application-dev/reference/apis/figures/en_us_image_ExtensionContext_Example.png b/en/application-dev/reference/apis/figures/en_us_image_ExtensionContext_Example.png new file mode 100644 index 0000000000000000000000000000000000000000..eb9314b00afe2cbb7534f7aefe0dc3d2499284bb Binary files /dev/null and b/en/application-dev/reference/apis/figures/en_us_image_ExtensionContext_Example.png differ diff --git a/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..2f601b14073d922a6b5812dc0d0368e16024a751 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @@ -0,0 +1,19 @@ +# BundleStatusCallback + +The **BundleStatusCallback** module provides bundle callback information, which is obtained through [innerBundleManager.on](js-apis-Bundle-InnerBundleManager.md). + +> **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. + +## BundleStatusCallback + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name | Type | Description | +| ------ | --------------------------------------------- | -------------------------------------- | +| add | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is added.| +| update | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is updated.| +| remove | (bundleName : string, userId: number) => void | Callback invoked when a **launcherStatusCallback** is removed.| diff --git a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md index 3691d636ac769e8bfad9099f92554a2476925d40..8beab3711f2933ce0701e5cdb79319c4d0bfdfcd 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -106,8 +106,8 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------------------- | --------------------- | ---- | ---------------------------------------------------- | -| type | "BundleStatusChange" | Yes | Event type. | -| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register. | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported. | +| bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. | | callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| ## innerBundleManager.on @@ -130,10 +130,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------------------- | -------------------- | ---- | ------------------ | -| type | "BundleStatusChange" | Yes | Event type. | -| bundleStatusCallback | BundleStatusCallback | Yes | Callback to register.| +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------ | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported.| +| bundleStatusCallback | [BundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) | Yes | Callback to register. | **Return value** @@ -163,7 +163,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------------------------------- | -| type | "BundleStatusChange" | Yes | Event type. | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported. | | callback | AsyncCallback\ | Yes | Callback used to return a successful result or error information.| ## innerBundleManager.off @@ -186,9 +186,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------------------- | ---- | ---------------- | -| type | "BundleStatusChange" | Yes | Event type.| +| Name| Type | Mandatory| Description | +| ---- | ------ | ---- | ------------------------------------------ | +| type | string | Yes | Event type. Only **BundleStatusChange** is supported.| **Return value** 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-accessibility-config.md b/en/application-dev/reference/apis/js-apis-accessibility-config.md index 71517bfb32ca3880637b565c85c02e53acbad8e6..c33230f7181ce92a50cee6c1417eb5d71a124f68 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -22,7 +22,7 @@ import config from "@ohos.accessibility.config"; | -------- | -------- | -------- | -------- | -------- | | highContrastText | [Config](#config)\| Yes| Yes| Whether to enable high-contrast text.| | invertColor | [Config](#config)\| Yes| Yes| Whether to enable color inversion.| -| daltonizationColorFilter | [Config](#config)<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Configuration of the daltonization filter.| +| daltonizationColorFilter | [Config](#config)\<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Daltonization filter. | | contentTimeout | [Config](#config)\| Yes| Yes| Recommended duration for content display. The value ranges from 0 to 5000, in milliseconds.| | animationOff | [Config](#config)\| Yes| Yes| Whether to enable animation.| | brightnessDiscount | [Config](#config)\| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.| @@ -163,7 +163,7 @@ Adds a listener for changes in the list of enabled accessibility extension abili | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating that the changes in the list of enabled accessibility extension abilities.| +| type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | | callback | Callback<void> | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** @@ -186,7 +186,7 @@ Cancels the listener for changes in the list of enabled accessibility extension | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating that the changes in the list of enabled accessibility extension abilities.| +| type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating the changes in the list of enabled accessibility extension abilities. | | callback | Callback<void> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md index 6a592ba663ec3723884fd0f44fef90a733230fa7..9fee7500eae2ec8435f0c3bdc2b48c986b14686a 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md @@ -34,13 +34,13 @@ Enumerates the focus directions. | up | Search for the next focusable item above the current item in focus.| | down | Search for the next focusable item below the current item in focus.| | left | Search for the next focusable item on the left of the current item in focus.| -| right | Search for the next focusable item on the right the current item in focus.| +| right | Search for the next focusable item on the right of the current item in focus.| | forward | Search for the next focusable item before the current item in focus.| | backward | Search for the next focusable item after the current item in focus.| ## FocusType -Enumerates of the focus types. +Enumerates the focus types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -55,8 +55,6 @@ Defines a rectangle. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - | Name | Type | Readable | Writable | Description | | ------ | ------ | ---- | ---- | --------- | | left | number | Yes | No | Left boundary of the rectangle.| @@ -75,35 +73,9 @@ Enumerates the window types. | application | Application window.| | system | System window.| -## AccessibilityExtensionContext.setEventTypeFilter - -setEventTypeFilter(type: Array): Promise\; - -Sets the concerned event type. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | ---- | -------- | -| type | Array<[EventType](js-apis-accessibility.md#EventType)> | Yes | Event type.| - -**Return value** - -| Type | Description | -| ---------------------- | --------------------- | -| Promise<boolean> | Promise used to return the result.| - -**Example** - -```ts -this.context.setEventTypeFilter(['click', 'longClick']); -``` - ## AccessibilityExtensionContext.setTargetBundleName -setTargetBundleName(targetNames: Array\): Promise\; +setTargetBundleName(targetNames: Array\): Promise\; Sets the concerned target bundle. @@ -139,7 +111,7 @@ Obtains the focus element. | Name | Type | Mandatory | Description | | -------------------- | ------- | ---- | ------------------- | -| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is false.| +| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| **Return value** @@ -213,7 +185,7 @@ this.context.getWindows().then(windows => { ## AccessibilityExtensionContext.injectGesture -injectGesture(gesturePath: GesturePath, listener: Callback\): Promise\): void Injects a gesture. @@ -224,13 +196,7 @@ Injects a gesture. | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | -------------- | | gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. | -| listener | Callback<boolean> | Yes | Callback used to return the result.| - -**Return value** - -| Type | Description | -| ---------------------- | ---------------------- | -| Promise<boolean> | Promise used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -244,3 +210,170 @@ this.context.gestureInject(gesturePath, (result) => { console.info('gestureInject result: ' + result); }) ``` +## AccessibilityElement.attributeNames + +attributeNames\(): Promise\>; + +Obtains all attribute names of this element. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<T>> | Promise used to return all attribute names of the element.| + +**Example** + +```ts +let accessibilityElement; +try { + accessibilityElement.attributeNames().then((values) => { + console.log("get attribute names success"); + }).catch((err) => { + console.log("get attribute names err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T): Promise\; + +Obtains the attribute value based on an attribute name. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<ElementAttributeValues[T]>> | Promise used to return the attribute value.| + +**Example** + +```ts +let accessibilityElement; +try { + let attributeName = 'name'; + accessibilityElement.attributeValue(attributeName).then((value) => { + console.log("get attribute value by name success"); + }).catch((err) => { + console.log("get attribute value by name err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.actionNames + +actionNames(): Promise\>; + +Obtains the names of all actions supported by this element. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<string>> | Promise used to return the names of all actions supported by the element.| + +**Example** + +```ts +let accessibilityElement; +try { + accessibilityElement.actionNames().then((values) => { + console.log("get action names success"); + }).catch((err) => { + console.log("get action names err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.performAction + +performAction(actionName: string, parameters?: object): Promise\; + +Performs an action based on the specified action name. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Action name. | +| parameters | object | No | Parameter required for performing the target action. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<boolean>> | Promise used to return the result.| + +**Example** + +```ts +let accessibilityElement; +try { + + accessibilityElement.performAction('action').then((result) => { + console.info('perform action result: ' + result); + }).catch((err) => { + console.log("perform action err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` + +## AccessibilityElement.findElement + +findElement(type: 'content', condition: string): Promise\>; + +Queries the information about this element based on the specified information type and condition. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'content'**. | +| condition | string | Yes | Search criteria. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<Array<T>> | Promise used to return the result.| + +**Example** + +```ts +let accessibilityElement; +try { + let condition = 'keyword'; + accessibilityElement.findElement('content', condition).then((values) => { + console.log("find element success"); + }).catch((err) => { + console.log("find element err: " + JSON.stringify(err)); + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md index c7a280fecc755160c7e7c602aed0f80e958fc9ee..7798cdee3d2f71f54e7cc6937816cbb4c253a833 100644 --- a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @@ -48,8 +48,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -94,8 +94,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -139,8 +139,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -181,8 +181,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -224,8 +224,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { @@ -269,8 +269,8 @@ import rdb from '@ohos.data.rdb'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " -+ TBL_NAME -+ " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; + + TBL_NAME + + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, phoneNumber DOUBLE, isStudent BOOLEAN, Binary BINARY)"; let rdbStore; export default class DataShareExtAbility extends DataShareExtensionAbility { diff --git a/en/application-dev/reference/apis/js-apis-application-quickFixManager.md b/en/application-dev/reference/apis/js-apis-application-quickFixManager.md new file mode 100644 index 0000000000000000000000000000000000000000..5abe8c19658d484fb335efc0d3fe8e2aa49bdc48 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-quickFixManager.md @@ -0,0 +1,186 @@ +# quickFixManager + +The **quickFixManager** module provides APIs for quick fix. With quick fix, you can fix bugs in your application by applying patches, which is more efficient than by updating the entire 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 + +``` +import quickFixManager from '@ohos.application.quickFixManager'; +``` + +## HapModuleQuickFixInfo + +Defines the quick fix information at the HAP file level. + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| moduleName | Read only | string | Yes | Name of the HAP file. | +| originHapHash | Read only | string | Yes | Hash value of the HAP file. | +| quickFixFilePath | Read only | string | Yes | Installation path of the quick fix file. | + +## ApplicationQuickFixInfo + +Defines the quick fix information at the application level. + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| bundleName | Read only | string | Yes | Bundle name of the application. | +| bundleVersionCode | Read only | number | Yes | Internal version number of the application. | +| bundleVersionName | Read only | string | Yes | Version number of the application that is shown to users. | +| quickFixVersionCode | Read only | number | Yes | Version code of the quick fix patch package. | +| quickFixVersionName | Read only | string | Yes | Text description of the version number of the quick fix patch package. | +| hapModuleQuickFixInfo | Read only | Array\<[HapModuleQuickFixInfo](#hapmodulequickfixinfo)> | Yes | Quick fix information at the HAP file level. | + +## quickFixManager.applyQuickFix + +applyQuickFix(hapModuleQuickFixFiles: Array\, callback: AsyncCallback\): void; + +Applies a quick fix patch. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | hapModuleQuickFixFiles | Array\ | No| Quick fix files, each of which must contain a valid file path.| + | callback | AsyncCallback\ | No| Callback used to return the result.| + +**Example** + +```js + import quickFixManager from '@ohos.application.quickFixManager' + + let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + quickFixManager.applyQuickFix(hapModuleQuickFixFiles, (error) => { + if (error) { + console.info( `applyQuickFix failed with error + ${error}`) + } else { + console.info( 'applyQuickFix success') + } + }) +``` + +## quickFixManager.applyQuickFix + +applyQuickFix(hapModuleQuickFixFiles: Array\): Promise\; + +Applies a quick fix patch. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INSTALL_BUNDLE + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | hapModuleQuickFixFiles | Array\ | No| Quick fix files, each of which must contain a valid file path.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise\ | Promise used to return the result.| + +**Example** + +```js + import quickFixManager from '@ohos.application.quickFixManager' + + let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { + console.info('applyQuickFix success') + }).catch((error) => { + console.info(`applyQuickFix err: + ${error}`) + }) +``` + +## quickFixManager.getApplicationQuickFixInfo + +getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\): void; + +Obtains the quick fix information of the application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | No|Bundle name of the application. | + | callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | No| Callback used to return the quick fix information.| + +**Example** + +```js + import quickFixManager from '@ohos.application.quickFixManager' + + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { + if (error) { + console.info(`getApplicationQuickFixInfo error: + ${error}`) + } else { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + } + }) +``` + +## quickFixManager.getApplicationQuickFixInfo + +getApplicationQuickFixInfo(bundleName: string): Promise\; + +Obtains the quick fix information of the application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.AbilityRuntime.QuickFix + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Parameter| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | No| Bundle name of the application. | + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| + +**Example** + + ```js + import quickFixManager from '@ohos.application.quickFixManager' + + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + }).catch((error) => { + console.info(`getApplicationQuickFixInfo err: + ${error}`) + }) +``` 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-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index eb54d689022397f603f9d93d2cc8591d9d1cdc82..b852a673ab6ca120497e1c40443d19990cfbd74b 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -223,7 +223,7 @@ cancelPairedDevice(deviceId: string): boolean Cancels a paired remote device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -389,7 +389,7 @@ startBluetoothDiscovery(): boolean Starts Bluetooth scan to discover remote devices. -**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION +**Required permissions**: ohos.permission.DISCOVER_BLUETOOTH and ohos.permission.LOCATION **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1293,7 +1293,7 @@ No value is returned. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let retArray = a2dpSrc.getConnectionDevices(); ``` @@ -1322,7 +1322,7 @@ Obtains the connection state of the profile. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let ret = a2dpSrc.getDeviceState('XX:XX:XX:XX:XX:XX'); ``` @@ -1356,7 +1356,7 @@ Sets up an Advanced Audio Distribution Profile (A2DP) connection. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let ret = a2dpSrc.connect('XX:XX:XX:XX:XX:XX'); ``` @@ -1386,7 +1386,7 @@ Disconnects an A2DP connection. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let ret = a2dpSrc.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1416,7 +1416,7 @@ No value is returned. function onReceiveEvent(data) { console.info('a2dp state = '+ JSON.stringify(data)); } -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; a2dpSrc.on('connectionStateChange', onReceiveEvent); ``` @@ -1446,7 +1446,7 @@ No value is returned. function onReceiveEvent(data) { console.info('a2dp state = '+ JSON.stringify(data)); } -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; a2dpSrc.on('connectionStateChange', onReceiveEvent); a2dpSrc.off('connectionStateChange', onReceiveEvent); ``` @@ -1475,7 +1475,7 @@ Obtains the playing state of a device. **Example** ```js -let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE); +let a2dpSrc = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_A2DP_SOURCE) as bluetooth.A2dpSourceProfile; let state = a2dpSrc.getPlayingState('XX:XX:XX:XX:XX:XX'); ``` @@ -1510,7 +1510,8 @@ Sets up a Hands-free Profile (HFP) connection of a device. **Example** ```js -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; let ret = hfpAg.connect('XX:XX:XX:XX:XX:XX'); ``` @@ -1540,7 +1541,8 @@ Disconnects the HFP connection of a device. **Example** ```js -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; let ret = hfpAg.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1570,7 +1572,8 @@ No value is returned. function onReceiveEvent(data) { console.info('hfp state = '+ JSON.stringify(data)); } -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; hfpAg.on('connectionStateChange', onReceiveEvent); ``` @@ -1600,7 +1603,8 @@ No value is returned. function onReceiveEvent(data) { console.info('hfp state = '+ JSON.stringify(data)); } -let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY); +let hfpAg = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HANDS_FREE_AUDIO_GATEWAY) as + bluetooth.HandsFreeAudioGatewayProfile; hfpAg.on('connectionStateChange', onReceiveEvent); hfpAg.off('connectionStateChange', onReceiveEvent); ``` @@ -1617,7 +1621,7 @@ connect(device: string): boolean Connects to the HidHost service of a device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -1638,7 +1642,7 @@ This is a system API. **Example** ```js -let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; let ret = hidHostProfile.connect('XX:XX:XX:XX:XX:XX'); ``` @@ -1649,7 +1653,7 @@ disconnect(device: string): boolean Disconnects from the HidHost service of a device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -1670,7 +1674,7 @@ This is a system API. **Example** ```js -let hidHostProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHostProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; let ret = hidHostProfile.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1700,7 +1704,7 @@ No value is returned. function onReceiveEvent(data) { console.info('hidHost state = '+ JSON.stringify(data)); } -let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; hidHost.on('connectionStateChange', onReceiveEvent); ``` @@ -1730,7 +1734,7 @@ No value is returned. function onReceiveEvent(data) { console.info('hidHost state = '+ JSON.stringify(data)); } -let hidHost = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_HID_HOST); +let hidHost = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_HID_HOST) as bluetooth.HidHostProfile; hidHost.on('connectionStateChange', onReceiveEvent); hidHost.off('connectionStateChange', onReceiveEvent); ``` @@ -1747,7 +1751,7 @@ disconnect(device: string): boolean Disconnects from the Personal Area Network (PAN) service of a device. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.USE_BLUETOOTH @@ -1768,7 +1772,7 @@ This is a system API. **Example** ```js -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; let ret = panProfile.disconnect('XX:XX:XX:XX:XX:XX'); ``` @@ -1798,7 +1802,7 @@ No value is returned. function onReceiveEvent(data) { console.info('pan state = '+ JSON.stringify(data)); } -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; panProfile.on('connectionStateChange', onReceiveEvent); ``` @@ -1828,7 +1832,7 @@ No value is returned. function onReceiveEvent(data) { console.info('pan state = '+ JSON.stringify(data)); } -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; panProfile.on('connectionStateChange', onReceiveEvent); panProfile.off('connectionStateChange', onReceiveEvent); ``` @@ -1840,7 +1844,7 @@ setTethering(enable: boolean): void Sets tethering. -This is a system API. +**System API**: This is a system API. **Required permissions**: ohos.permission.DISCOVER_BLUETOOTH @@ -1861,7 +1865,7 @@ This is a system API. **Example** ```js -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; let ret = panProfile.setTethering(true); ``` @@ -1872,7 +1876,7 @@ isTetheringOn(): boolean Obtains the tethering state. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.Bluetooth.Core @@ -1885,7 +1889,7 @@ This is a system API. **Example** ```js -let panProfile = bluetooth.getProfile(bluetooth.ProfileId.PROFILE_PAN_NETWORK); +let panProfile = bluetooth.getProfileInst(bluetooth.ProfileId.PROFILE_PAN_NETWORK) as bluetooth.PanProfile; let ret = panProfile.isTetheringOn(); ``` @@ -2217,7 +2221,7 @@ function ReadCharacteristicReq(CharacteristicReadReq) { let characteristicUuid = CharacteristicReadReq.characteristicUuid; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); @@ -2294,10 +2298,10 @@ function WriteCharacteristicReq(CharacteristicWriteReq) { let needRsp = CharacteristicWriteReq.needRsp; let value = new Uint8Array(CharacteristicWriteReq.value); let characteristicUuid = CharacteristicWriteReq.characteristicUuid; - + cccValue[0] = value[0]; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferCCC}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); @@ -2374,7 +2378,7 @@ function ReadDescriptorReq(DescriptorReadReq) { let descriptorUuid = DescriptorReadReq.descriptorUuid; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); @@ -2454,7 +2458,7 @@ function WriteDescriptorReq(DescriptorWriteReq) { descValue[0] = value[0]; let serverResponse = {deviceId: deviceId, transId: transId, status: 0, offset: offset, value:arrayBufferDesc}; - + let ret = gattServer.sendResponse(serverResponse); if (ret) { console.log('bluetooth sendResponse successfully'); diff --git a/en/application-dev/reference/apis/js-apis-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-ElementName.md b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md index 205c9f15192c4c2c9abfcb08b1f1ae156d7baf75..4a22bff59f56ba6756e08c0af59046530fea1a80 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -1,20 +1,24 @@ # ElementName -The **ElementName** module provides the element name information. +The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md). > **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. -## ElementName +## ElementName(deprecated) -**System capability**: SystemCapability.BundleManager.BundleFramework +> This API is deprecated since API version 9. You are advised to use [ElementName](js-apis-bundleManager-elementName.md) instead. + + **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | ----------------------- | ---------| ---- | ---- | ------------------------- | -| deviceId | string | Yes | Yes | Device ID. | -| bundleName | string | Yes | Yes | Bundle name of the application. | -| abilityName | string | Yes | Yes | Name of the ability. | -| uri | string | Yes | Yes | URI. | -| shortName | string | Yes | Yes | Short name of the ability. | -| moduleName9+ | string | Yes | Yes | Name of the HAP file to which the ability belongs. | +| deviceId | string | Yes | Yes | Device ID. | +| bundleName | string | Yes | Yes | Bundle name of the application. | +| abilityName | string | Yes | Yes | Name of the ability. | +| uri | string | Yes | Yes | Resource ID. | +| shortName | string | Yes | Yes | Short name of the ability. | +| moduleName9+ | string | Yes | Yes | Name of the HAP file to which the ability belongs. | + + \ No newline at end of file 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 ab561f552758ed5af3c79bc2c4406d84ceb56f2b..34fe47f45abe436abf986da809e343fd638540d7 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -403,7 +403,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. **Example** ```js -call.formatPhoneNumber("138xxxxxxxx",{ +call.formatPhoneNumber("138xxxxxxxx", { countryCode: "CN" }, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); 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-colorSpaceManager.md b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md new file mode 100644 index 0000000000000000000000000000000000000000..ca879b489145b7d741cdf990e36656b78cd3033b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md @@ -0,0 +1,197 @@ +# Color Space Management + +The **colorSpaceManager** module provides APIs for creating and managing color space objects and obtaining basic color space attributes. + +> **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 colorSpaceManager from '@ohos.graphics.colorSpaceManager'; +``` + +## ColorSpace + +Enumerates the color space types. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +| Name | Value | Description | +| --------------------------- | ------ | ----------------------- | +| UNKNOWN | 0 | Unknown type.| +| ADOBE_RGB_1998 | 1 | Adobe RGB (1998).| +| DCI_P3 | 2 | DCI-P3.| +| DISPLAY_P3 | 3 | Display P3.| +| SRGB | 4 | SRGB.
This is the default color space type.| +| CUSTOM | 5 | Custom type.| + +## ColorSpacePrimaries + +Defines the color space primaries. A color space is defined by chromaticity coordinates of the red, green, and blue additive primaries, the white point, and the gamma. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +| Name | Type| Readable| Writable| Description | +| ---------------------------- | -------- | ---- | ---- | ----------------------------------------------------- | +| redX | number | Yes | Yes | X coordinate of the red color in the color space.| +| redY | number | Yes | Yes | Y coordinate of the red color in the color space.| +| greenX | number | Yes | Yes | X coordinate of the green color in the color space.| +| greenY | number | Yes | Yes | Y coordinate of the green color in the color space.| +| blueX | number | Yes | Yes | X coordinate of the blue color in the color space.| +| blueY | number | Yes | Yes | Y coordinate of the blue color in the color space.| +| whitePointX | number | Yes | Yes | X coordinate of the white point in the color space.| +| whitePointY | number | Yes | Yes | Y coordinate of the white point in the color space.| + +## colorSpaceManager.create + +create(colorSpaceName: ColorSpace): ColorSpaceManager + +Creates a standard color space object. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Parameters** + +| Parameter | Type | Mandatory| Description | +| --------------- | ------------------------ | ---- | -----------------------------| +| colorSpaceName | [ColorSpace](#colorspace)| Yes | Type of the color space.
**UNKNOWN** and **CUSTOM** cannot be used when creating standard color space objects. | + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| [ColorSpaceManager](#colorspacemanager) | Color space object created. | + +**Example** + +```js +let colorSpace = null; +try { + colorSpace = colorSpaceManager.create(colorSpaceManager.ColorSpace.SRGB); +} catch (err) { + console.log(`Failed to create SRGB colorSpace. Cause: ` + JSON.stringify(err)); +} +``` + +## colorSpaceManager.create + +create(primaries: ColorSpacePrimaries, gamma: number): ColorSpaceManager + +Creates a custom color space object. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Parameters** + +| Parameter | Type | Mandatory| Description | +| --------------- | ------------------------------------------ | ---- | -----------------------------| +| primaries | [ColorSpacePrimaries](#colorspaceprimaries)| Yes | Primaries of the color space. | +| gamma | number | Yes | Gamma of the color space. | + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| [ColorSpaceManager](#colorspacemanager) | Color space object created.
The color space type is **CUSTOM** of [ColorSpace](#colorspace).| + +**Example** + +```js +let colorSpace = null; +try { + let primaries = { + redX: 0.1, + redY: 0.1, + greenX: 0.2, + greenY: 0.2, + blueX: 0.3, + blueY: 0.3, + whitePointX: 0.4, + whitePointY: 0.4 + }; + let gamma = 2.2; + colorSpace = colorSpaceManager.create(primaries, gamma); +} catch (err) { + console.log(`Failed to create colorSpace with customized primaries and gamma. Cause: ` + JSON.stringify(err)); +} +``` + +## ColorSpaceManager + +Implements management of color space objects. + +Before calling any of the following APIs, you must use [create()](#colorspacemanagercreate) to create a color space object. + +### getColorSpaceName + +getColorSpaceName(): ColorSpace + +Obtains the color space type. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| [ColorSpace](#colorspace) | Color space type.| + +**Example** + +```js +try { + let csType = colorSpace.getColorSpaceName(); +} catch (err) { + console.log(`Fail to get colorSpace's name. Cause: ` + JSON.stringify(err)); +} +``` + +### getWhitePoint + +getWhitePoint(): Array\ + +Obtains the coordinates of the white point of the color space. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| Array\ | Coordinates [x, y] of the white point.| + +**Example** + +```js +try { + let wp = colorSpace.getWhitePoint(); +} catch (err) { + console.log(`Failed to get white point. Cause: ` + JSON.stringify(err)); +} +``` + +### getGamma + +getGamma(): number + +Obtains the gamma of the color space. + +**System capability**: SystemCapability.Graphic.Graphic2D.ColorManager.Core + +**Return value** + +| Type | Description | +| ------------------ | ------------------------ | +| number | Gamma of the color space.| + +**Example** + +```js +try { + let gamma = colorSpace.getGamma(); +} catch (err) { + console.log(`Failed to get gamma. Cause: ` + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 4cb3ef3bc5f1672b883ae42d722e593aabf03d24..5aaacbe7d104cf965d398240ff8e19468644713b 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -167,7 +167,7 @@ Provides the event types supported by the **CommonEvent** module. The name and v | 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. | diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md index 5d393653ce602b60438df2b6f9e54f6ba9cb9fe6..779d30c40263eecd1a8ecf70209a95008aa228dd 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -726,7 +726,7 @@ Sets a **DataAbilityPredicates** object to specify the index column. in(field: string, value: Array<ValueType>): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type Array and value within the specified range. +Sets a **DataAbilityPredicates** object to match the field with data type Array\ and value within the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core @@ -754,7 +754,7 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array< notIn(field: string, value: Array<ValueType>): DataAbilityPredicates -Sets a **DataAbilityPredicates** object to match the field with data type Array and value out of the specified range. +Sets a **DataAbilityPredicates** object to match the field with data type Array\ and value out of the specified range. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core diff --git a/en/application-dev/reference/apis/js-apis-device-info.md b/en/application-dev/reference/apis/js-apis-device-info.md index a1e16d5e0b970a82d9b4e866eb053cb014ced89f..46a110814dc474f66393135a91313ab5df03b98e 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -1,5 +1,7 @@ # Device Information +The **deviceInfo** module provides product information. + > **NOTE** > > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index 9d51475957c8e9c891980c0d42880a6b1db649de..46c9d2e80e30fad1c21827d41de7418934f3bbdc 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -10,6 +10,7 @@ System applications can call the APIs to do the following: - Query the trusted device list. - Query local device information, including the device name, type, and ID. - Publish device information for discovery purposes. + > **NOTE** > > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,7 +19,7 @@ System applications can call the APIs to do the following: ## Modules to Import -``` +```js import deviceManager from '@ohos.distributedHardware.deviceManager'; ``` @@ -32,23 +33,37 @@ Creates a **DeviceManager** instance. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------------- | ---- | ------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| + + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------------------------------------ | + | bundleName | string | Yes | Bundle name of an application. | + | callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600102 | Failed to obtain the service. | **Example** -``` -deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { - if (err) { - console.info("createDeviceManager err:" + JSON.stringify(err)); + ```js + try { + deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { + if (err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); return; - } - console.info("createDeviceManager success"); - let dmInstance = data; -}); -``` + } + console.info("createDeviceManager success"); + let dmInstance = data; + }); + } catch(err) { + console.error("createDeviceManager errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ## DeviceInfo @@ -191,7 +206,7 @@ Defines published device information. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | ------------- | --------------------------------- | ---- | ----------------- | | publishId | number | Yes | ID used to identify a publication period.| | mode | [DiscoverMode ](#discovermode) | Yes | Device discovery mode. | @@ -202,7 +217,6 @@ Defines published device information. Provides APIs to obtain information about trusted devices and local devices. Before calling any API in **DeviceManager**, you must use **createDeviceManager** to create a **DeviceManager** instance, for example, **dmInstance**. - ### release release(): void @@ -211,12 +225,23 @@ Releases this **DeviceManager** instance when it is no longer used. **System capability**: SystemCapability.DistributedHardware.DeviceManager -**Example** +**Error codes** -```js -dmInstance.release(); -``` +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**Example** + ```js + try { + dmInstance.release(); + } catch (err) { + console.error("release errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### getTrustedDeviceListSync @@ -228,16 +253,27 @@ Obtains all trusted devices synchronously. **Return value** -| Name | Description | -| -------------------------------------- | --------- | -| Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| + | Name | Description | + | -------------------------------------- | --------- | + | Array<[DeviceInfo](#deviceinfo)> | List of trusted devices obtained.| -**Example** +**Error codes** -```js -var deviceInfoList = dmInstance.getTrustedDeviceListSync(); -``` +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**Example** + + ```js + try { + var deviceInfoList = dmInstance.getTrustedDeviceListSync(); + } catch (err) { + console.error("getTrustedDeviceListSync errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### getTrustedDeviceList8+ @@ -248,17 +284,33 @@ Obtains all trusted devices. This API uses an asynchronous callback to return th **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------- | -| callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | Yes | Callback used to return the list of trusted devices.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------- | + | callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | Yes | Callback used to return the list of trusted devices.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.getTrustedDeviceList((err, data) => { - console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + try { + dmInstance.getTrustedDeviceList((err, data) => { + if (err) { + console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); + return; + } console.log('get trusted device info: ' + JSON.stringify(data)); - } - ); + }); + } catch (err) { + console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### getTrustedDeviceList8+ @@ -270,16 +322,26 @@ Obtains all trusted devices. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the list of trusted devices.| + + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise used to return the list of trusted devices.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.getTrustedDeviceList().then((data) => { - console.log('get trusted device info: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getTrustedDeviceList err: " + JSON.stringify(err)); + dmInstance.getTrustedDeviceList().then((data) => { + console.log('get trusted device info: ' + JSON.stringify(data)); + }).catch((err) => { + console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); }); ``` @@ -292,16 +354,29 @@ Obtains local device information synchronously. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** -| Name | Description | -| -------------------------------------- | --------- | -| Array<[DeviceInfo](#deviceinfo)> | List of local devices obtained.| + + | Name | Description | + | ------------------------- | ---------------- | + | [DeviceInfo](#deviceinfo) | List of local devices obtained.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - var deviceInfo = dmInstance.getLocalDeviceInfoSync(); + try { + var deviceInfo = dmInstance.getLocalDeviceInfoSync(); + } catch (err) { + console.error("getLocalDeviceInfoSync errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### getLocalDeviceInfo8+ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void @@ -311,17 +386,33 @@ Obtains local device information. This API uses an asynchronous callback to retu **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | Yes | Callback used to return the local device information.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------- | + | callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | Yes | Callback used to return the local device information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.getLocalDeviceInfo((err, data) => { - console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); - console.log('get local device info: ' + JSON.stringify(data)); + try { + dmInstance.getLocalDeviceInfo((err, data) => { + if (err) { + console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); + return; } - ); + console.log('get local device info: ' + JSON.stringify(data)); + }); + } catch (err) { + console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### getLocalDeviceInfo8+ @@ -333,16 +424,26 @@ Obtains local device information. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the local device information.| + + | Type | Description | + | ---------------------------------------- | --------------------- | + | Promise<[DeviceInfo](#deviceinfo)> | Promise used to return the local device information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| ------- | --------------------------------------------------------------- | +| 11600101| Failed to execute the function. | **Example** + ```js - dmInstance.getLocalDeviceInfo().then((data) => { - console.log('get local device info: ' + JSON.stringify(data)); + dmInstance.getLocalDeviceInfo().then((data) => { + console.log('get local device info: ' + JSON.stringify(data)); }).catch((err) => { - console.log("getLocalDeviceInfo err: " + JSON.stringify(err)); + console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); }); ``` @@ -355,11 +456,22 @@ Starts to discover peripheral devices. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------------------------- | ---- | ----- | -| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + + | Name | Type | Mandatory| Description | + | ------------- | ------------------------------- | ---- | ----- | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600104 | Discovery invalid. | **Example** + ```js // Automatically generate a unique subscription ID. var subscribeId = Math.floor(Math.random() * 10000 + 1000); @@ -372,7 +484,11 @@ Starts to discover peripheral devices. "isWakeRemote": false, "capability": 1 }; - dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. + try { + dmInstance.startDeviceDiscovery(subscribeInfo); // The deviceFound callback is invoked to notify the application when a device is discovered. + } catch (err) { + console.error("startDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### startDeviceDiscovery9+ @@ -384,10 +500,20 @@ Starts to discover peripheral devices and filters discovered devices. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ------------- | ------------------------------- | ---- | ----- | -| subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| -| filterOptions | string | No | Options for filtering discovered devices.| + + | Name | Type | Mandatory | Description | + | ------------- | ------------------------------- | ---- | ----- | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | Yes | Subscription information.| + | filterOptions | string | No | Options for filtering discovered devices.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600104 | Discovery invalid. | **Example** @@ -412,7 +538,11 @@ Starts to discover peripheral devices and filters discovered devices. } ] }; - dmInstance.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions)); // The deviceFound callback is invoked to notify the application when a device is discovered. + try { + dmInstance.startDeviceDiscovery(subscribeInfo, JSON.stringify(filterOptions)); // The deviceFound callback is invoked to notify the application when a device is discovered. + } catch (err) { + console.error("startDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### stopDeviceDiscovery @@ -424,14 +554,28 @@ Stops device discovery. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ----- | -| subscribeId | number | Yes | Subscription ID.| + + | Name | Type | Mandatory | Description | + | ----------- | ------ | ---- | ----- | + | subscribeId | number | Yes | Subscription ID.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js // The subscribeId input must be the same as that automatically generated in startDeviceDiscovery. - dmInstance.stopDeviceDiscovery(subscribeId); + try { + dmInstance.stopDeviceDiscovery(subscribeId); + } catch (err) { + console.error("stopDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### publishDeviceDiscovery9+ @@ -443,11 +587,22 @@ Publishes device information for discovery purposes. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------------- | ---- | ----- | -| publishInfo | [PublishInfo](#publishinfo) | Yes | Device information to publish.| + + | Name | Type | Mandatory| Description | + | ------------- | ------------------------------- | ---- | ----- | + | publishInfo | [PublishInfo](#publishinfo) | Yes | Device information to publish.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600105 | Publish invalid. | **Example** + ```js // Automatically generate a unique subscription ID. var publishId = Math.floor(Math.random() * 10000 + 1000); @@ -457,9 +612,13 @@ Publishes device information for discovery purposes. "freq": 2, // High frequency "ranging": 1 // The device supports reporting the distance to the discovery initiator. }; - dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published. + try { + dmInstance.publishDeviceDiscovery(publishInfo); // A callback is invoked to notify the application when the device information is published. + } catch (err) { + console.error("publishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` - + ### unPublishDeviceDiscovery9+ unPublishDeviceDiscovery(publishId: number): void @@ -470,14 +629,27 @@ Stops publishing device information. **Parameters** -| Name | Type| Mandatory| Description | -| ----------- | -------- | ---- | ----- | -| publishId | number | Yes | Publish ID.| + | Name | Type| Mandatory| Description | + | ----------- | -------- | ---- | ----- | + | publishId | number | Yes | Publish ID.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js // The publishId input must be the same as that automatically generated in publishDeviceDiscovery. - dmInstance.unPublishDeviceDiscovery(publishId); + try { + dmInstance.unPublishDeviceDiscovery(publishId); + } catch (err) { + console.error("unPublishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### authenticateDevice @@ -489,13 +661,24 @@ Authenticates a device. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------------- | ---- | ------- | -| deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | -| authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | -| callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| + + | Name | Type | Mandatory | Description | + | ---------- | ---------------------------------------- | ---- | ------- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information. | + | authParam | [AuthParam](#authparam) | Yes | Authentication parameter. | + | callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | Yes | Callback used to return the authentication result.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600103 | Authentication invalid. | **Example** + ```js // Information about the device to authenticate. The information can be obtained from the device discovery result. var deviceInfo ={ @@ -507,14 +690,18 @@ Authenticates a device. "authType": 1, // Authentication type. The value 1 means no account PIN authentication. "extraInfo": {} } - dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { + try { + dmInstance.authenticateDevice(deviceInfo, authParam, (err, data) => { if (err) { - console.info(TAG + "authenticateDevice err:" + JSON.stringify(err)); + console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message); return; } - console.info(TAG + "authenticateDevice result:" + JSON.stringify(data)); - token = data.pinToken; - }); + console.info("authenticateDevice result:" + JSON.stringify(data)); + let token = data.pinToken; + }); + } catch (err) { + console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### unAuthenticateDevice8+ @@ -527,16 +714,28 @@ Deauthenticates a device. **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | ---- | ----- | -| deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| + | Name | Type | Mandatory | Description | + | ---------- | ------------------------- | ---- | ----- | + | deviceInfo | [DeviceInfo](#deviceinfo) | Yes | Device information.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js - dmInstance.unAuthenticateDevice(deviceInfo); + try { + dmInstance.unAuthenticateDevice(deviceInfo); + } catch (err) { + console.error("unAuthenticateDevice errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### verifyAuthInfo verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void @@ -546,27 +745,132 @@ Verifies authentication information. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------- | -| authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | -| authInfo | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------- | + | authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | + | callback | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + +**Error codes** + +For details about the error codes, see [Device Management Error Codes](../errorcodes/errorcode-device-manager.md). + +| ID| Error Message | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | **Example** + ```js let authInfo = { "authType": 1, "token": xxxxxx, "extraInfo": {} } - dmInstance.verifyAuthInfo(authInfo, (err, data) => { + try { + dmInstance.verifyAuthInfo(authInfo, (err, data) => { if (err) { - console.info(TAG + "verifyAuthInfo err:" + JSON.stringify(err)); + console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message); return; } - console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data)); + console.info("verifyAuthInfo result:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +### setUserOperation9+ + +setUserOperation(operateAction: number, params: string): void; + +Sets a user operation action. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory | Description | + | ------------- | --------------- | ---- | ------------------- | + | operateAction | number | Yes | User operation action. | + | params | string | Yes | Input parameters of the user.| + +**Example** + + ```js + try { + /* + operateAction = 0 - Grant the permission. + operateAction = 1 - Revoke the permission. + operateAction = 2 - The user operation in the permission request dialog box times out. + operateAction = 3 - Cancel the display of the PIN box. + operateAction = 4 - Cancel the display of the PIN text box. + operateAction = 5 - Confirm in the pin text box. + */ + let operation = 0; + this.dmInstance.setUserOperation(operation, "extra") + } catch (err) { + console.error("setUserOperation errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +### on('uiStateChange')9+ + +on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; + +Subscribes to UI status changes. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------ | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'uiStateChange'** indicates a UI status change event.| + | callback | Callback<{ param: string}> | Yes | Callback used to return the UI status. | + +**Example** + + ```js + try { + dmInstance.on('uiStateChange', (data) => { + console.log("uiStateChange executed, dialog closed" + JSON.stringify(data)) + var tmpStr = JSON.parse(data.param) + this.isShow = tmpStr.verifyFailed + console.log("uiStateChange executed, dialog closed" + this.isShow) + if (!this.isShow) { + this.destruction() + } }); + } catch (err) { + console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); + } ``` +### off('uiStateChange')9+ + +off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; + +Unsubscribes from UI status changes. + +**System capability**: SystemCapability.DistributedHardware.DeviceManager + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'uiStateChange'** indicates a UI status change event.| + | callback | Callback<{ param: string}> | Yes | Callback used to return the UI status.| + +**Example** + + ```js + try { + dmInstance.off('uiStateChange'); + } catch (err) { + console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### on('deviceStateChange') @@ -577,20 +881,24 @@ Subscribes to changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| -| callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state. | + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used to return the device information and state. | **Example** + ```js - dmInstance.on('deviceStateChange', (data) => { - console.info("deviceStateChange on:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('deviceStateChange', (data) => { + console.info("deviceStateChange on:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("deviceStateChange errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### off('deviceStateChange') off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void @@ -600,20 +908,23 @@ Unsubscribes from changes in the device state. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------- | -| type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. | -| callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceStateChange'** indicates a device state change event. | + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo)  }> | Yes | Callback used to return the device information and state.| **Example** -```js -dmInstance.off('deviceStateChange', (data) => { + ```js + try { + dmInstance.off('deviceStateChange', (data) => { console.info('deviceStateChange' + JSON.stringify(data)); - } -); -``` - + }); + } catch (err) { + console.error("deviceStateChange errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### on('deviceFound') @@ -624,17 +935,22 @@ Subscribes to device discovery events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------- | -| type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| -| callback | Callback<{ subscribeId: number, device: DeviceInfo }> | Yes | Callback used for device discovery. | + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | -------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered.| + | callback | Callback<{ subscribeId: number, device: DeviceInfo }> | Yes | Callback used for device discovery. | **Example** + ```js - dmInstance.on('deviceFound', (data) => { - console.info("deviceFound:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('deviceFound', (data) => { + console.info("deviceFound:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("deviceFound errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### off('deviceFound') @@ -646,17 +962,22 @@ Unsubscribes from device discovery events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------------------------- | -| type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | -| callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback invoked to return the device information and state.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'deviceFound'** indicates an event reported when a device is discovered. | + | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used to return the device information and state.| **Example** + ```js - dmInstance.off('deviceFound', (data) => { - console.info('deviceFound' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('deviceFound', (data) => { + console.info('deviceFound' + JSON.stringify(data)); + }); + } catch (err) { + console.error("deviceFound errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('discoverFail') @@ -668,17 +989,22 @@ Subscribes to device discovery failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| -| callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails.| + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | **Example** + ```js - dmInstance.on('discoverFail', (data) => { - this.log("discoverFail on:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('discoverFail', (data) => { + console.info("discoverFail on:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("discoverFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### off('discoverFail') @@ -690,17 +1016,22 @@ Unsubscribes from device discovery failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------- | -| type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | -| callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure.| + + | Name | Type | Mandatory | Description | + | -------- | ---------------------------------------- | ---- | ----------------- | + | type | string | Yes | Event type. The event **'discoverFail'** indicates an event reported when device discovery fails. | + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure.| **Example** + ```js - dmInstance.off('deviceFound', (data) => { - console.info('deviceFound' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('discoverFail', (data) => { + console.info('discoverFail' + JSON.stringify(data)); + }); + } catch (err) { + console.error("discoverFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('publishSuccess')9+ @@ -712,18 +1043,24 @@ Subscribes to device information publication success events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | -------------------------- | -| type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published.| -| callback | Callback<{ publishId: number }> | Yes | Callback invoked to return the publish ID. | + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------------- | ---- | -------------------------- | + | type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published.| + | callback | Callback<{ publishId: number }> | Yes | Callback used to return the publish ID. | + **Example** -```js -dmInstance.on('publishSuccess', (data) => { + + ```js + try { + dmInstance.on('publishSuccess', (data) => { console.info("publishSuccess:" + JSON.stringify(data)); - } -); -``` + }); + } catch (err) { + console.error("publishSuccess errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### off('publishSuccess')9+ @@ -734,17 +1071,22 @@ Unsubscribes from device information publication success events. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | --------------------------- | -| type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published. | -| callback | Callback<{ publishId: number }> | Yes | Callback used to return the publish ID.| + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------------- | ---- | --------------------------- | + | type | string | Yes | Event type. The value **'publishSuccess'** indicates an event reported when device information is published. | + | callback | Callback<{ publishId: number }> | Yes | Callback used to return the publish ID.| **Example** + ```js - dmInstance.off('publishSuccess', (data) => { - console.info('publishSuccess' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('publishSuccess', (data) => { + console.info('publishSuccess' + JSON.stringify(data)); + }); + } catch (err) { + console.error("publishSuccess errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('publishFail')9+ @@ -756,17 +1098,22 @@ Subscribes to device information publication failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ------------------------------ | -| type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails.| -| callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the publication failure. | + + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------------------------- | ---- | ------------------------------ | + | type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails.| + | callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the publication failure. | **Example** + ```js - dmInstance.on('publishFail', (data) => { - this.log("publishFail on:" + JSON.stringify(data)); - } - ); + try { + dmInstance.on('publishFail', (data) => { + console.info("publishFail on:" + JSON.stringify(data)); + }); + } catch (err) { + console.error("publishFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### off('publishFail')9+ @@ -778,17 +1125,22 @@ Unsubscribes from device information publication failures. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------- | ---- | ----------------- | -| type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails. | -| callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the device discovery failure.| + + | Name | Type | Mandatory| Description | + | -------- | ----------------------------------------------------- | ---- | ----------------- | + | type | string | Yes | Event type. The event **'publishFail'** indicates an event reported when publishing device information fails. | + | callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the device discovery failure.| **Example** + ```js - dmInstance.off('publishFail', (data) => { - console.info('publishFail' + JSON.stringify(data)); - } - ); + try { + dmInstance.off('publishFail', (data) => { + console.info('publishFail' + JSON.stringify(data)); + }); + } catch (err) { + console.error("publishFail errCode:" + err.code + ",errMessage:" + err.message); + } ``` ### on('serviceDie') @@ -800,20 +1152,24 @@ Subscribes to dead events of the **DeviceManager** service. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| -| callback | () => void | Yes | Callback invoked when a dead event of the **DeviceManager** service occurs. | + + | Name | Type | Mandatory | Description | + | -------- | ----------------------- | ---- | ---------------------------------------- | + | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | Yes | Callback invoked when a dead event of the **DeviceManager** service occurs. | **Example** + ```js - dmInstance.on("serviceDie", () => { - console.info("serviceDie on"); - } - ); + try { + dmInstance.on("serviceDie", () => { + console.info("serviceDie on"); + }); + } catch (err) { + console.error("serviceDie errCode:" + err.code + ",errMessage:" + err.message); + } ``` - ### off('serviceDie') off(type: 'serviceDie', callback?: () => void): void @@ -823,15 +1179,20 @@ Unsubscribes from dead events of the **DeviceManager** service. **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------- | ---- | ---------------------------------------- | -| type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| -| callback | () => void | No | Callback used to return the dead event of the **DeviceManager** service. | + + | Name | Type | Mandatory | Description | + | -------- | ----------------------- | ---- | ---------------------------------------- | + | type | string | Yes | Event type. The value **'serviceDie'** indicates an event reported when the **DeviceManager** service is terminated unexpectedly.| + | callback | () => void | No | Callback used to return the dead event of the **DeviceManager** service. | **Example** + ```js - dmInstance.off("serviceDie", () => { - console.info("serviceDie off"); - } - ); + try { + dmInstance.off("serviceDie", () => { + console.info("serviceDie off"); + }); + } catch (err) { + console.error("serviceDie errCode:" + err.code + ",errMessage:" + err.message); + } ``` diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 02c4680e1e082798d81c692cb178ca72fe21cf9a..199469589d8a67a47b993eacc36eac69a25aa8c1 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -11,7 +11,6 @@ The **Display** module provides APIs for managing displays, such as obtaining in import display from '@ohos.display'; ``` - ## DisplayState Enumerates the display states. @@ -65,61 +64,6 @@ Describes the cutout, which is an area that is not intended for displaying conte | boundingRects | Array\<[Rect](#rect9)> | Yes | No | Bounding rectangle for punch holes and notches.| | waterfallDisplayAreaRects | [WaterfallDisplayAreaRects](#waterfalldisplayarearects9) | Yes| No| Curved area on the waterfall display.| -## display.getDefaultDisplay - -getDefaultDisplay(callback: AsyncCallback<Display>): void - -Obtains the default display object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[Display](#display)> | Yes| Callback used to return the default display object.| - -**Example** - -```js -var displayClass = null; -display.getDefaultDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); - displayClass = data; -}); -``` - -## display.getDefaultDisplay - -getDefaultDisplay(): Promise<Display> - -Obtains the default display object. This API uses a promise to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Return value** - - | Type | Description | - | ---------------------------------- | ---------------------------------------------- | - | Promise<[Display](#display)> | Promise used to return the default display object.| - -**Example** - -```js -var displayClass = null; -let promise = display.getDefaultDisplay(); -promise.then((data) => { - displayClass = data; - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); -}); -``` - ## display.getDefaultDisplaySync9+ getDefaultDisplaySync(): Display @@ -134,15 +78,28 @@ Obtains the default display object. This API returns the result synchronously. | ------------------------------| ----------------------------------------------| | [Display](#display) | Default display object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var displayClass = display.getDefaultDisplaySync(); +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +}; ``` -## display.getAllDisplay +## display.getAllDisplays9+ -getAllDisplay(callback: AsyncCallback<Array<Display>>): void +getAllDisplays(callback: AsyncCallback<Array<Display>>): void Obtains all display objects. This API uses an asynchronous callback to return the result. @@ -150,14 +107,24 @@ Obtains all display objects. This API uses an asynchronous callback to return th **Parameters** - | Name | Type | Mandatory| Description | - | -------- | ---------------------------------------------------- | ---- | ------------------------------- | - | callback | AsyncCallback<Array<[Display](#display)>> | Yes | Callback used to return all the display objects.| +| Name| Type| Mandatory| Description| +| -------- | ---------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<Array<[Display](#display)>> | Yes| Callback used to return all the display objects.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js -display.getAllDisplay((err, data) => { +let displayClass = null; +display.getAllDisplays((err, data) => { + displayClass = data; if (err.code) { console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); return; @@ -166,9 +133,9 @@ display.getAllDisplay((err, data) => { }); ``` -## display.getAllDisplay +## display.getAllDisplays9+ -getAllDisplay(): Promise<Array<Display>> +getAllDisplays(): Promise<Array<Display>> Obtains all display objects. This API uses a promise to return the result. @@ -176,15 +143,25 @@ Obtains all display objects. This API uses a promise to return the result. **Return value** - | Type | Description | - | ----------------------------------------------- | ------------------------------------------------------- | - | Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| +| Type| Description| +| ----------------------------------------------- | ------------------------------------------------------- | +| Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js -let promise = display.getAllDisplay(); +let displayClass = null; +let promise = display.getAllDisplays(); promise.then((data) => { + displayClass = data; console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); @@ -195,7 +172,7 @@ promise.then((data) => { hasPrivateWindow(displayId: number): boolean -Checks whether there is a visible privacy window on a display. The privacy window can be set by calling `[setPrivacyMode](js-apis-window.md#setprivacymode7)`. The content in the privacy window cannot be captured or recorded. +Checks whether there is a visible privacy window on a display. The privacy window can be set by calling [setWindowPrivacyMode()](js-apis-window.md#setwindowprivacymode9). The content in the privacy window cannot be captured or recorded. **System API**: This is a system API. @@ -211,30 +188,41 @@ Checks whether there is a visible privacy window on a display. The privacy windo | Type | Description | | -------------------------------- |-----------------------------------------------------------------------| -|boolean | Whether there is a visible privacy window on the display.
The value `true` means that there is a visible privacy window on the display, and `false` means the opposite.
| +|boolean | Whether there is a visible privacy window on the display.
The value **true** means that there is a visible privacy window on the display, and **false** means the opposite.
| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | **Example** ```js -var displayClass = null; -display.getDefaultDisplay((err, data) => { - if (err.code) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); return; - } - console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); - displayClass = data; -}); - -var ret = display.hasPrivateWindow(displayClass.id); +}; + +let ret = undefined; +try { + ret = display.hasPrivateWindow(displayClass.id); +} catch (exception) { + console.error('Failed to check has privateWindow or not. Code: ' + JSON.stringify(exception)); +}; if (ret == undefined) { - console.log("Failed to check has privateWindow or not."); + console.log("Failed to check has privateWindow or not."); } if (ret) { console.log("There has privateWindow."); } else if (!ret) { console.log("There has no privateWindow."); -} +}; ``` ## display.on('add'|'remove'|'change') @@ -249,16 +237,20 @@ Subscribes to display changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event indicating that a display is connected to a PC.
- **remove**, indicating the display removal event. Example: event that a display is disconnected from a PC.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| | callback | Callback<number> | Yes| Callback used to return the ID of the display.| **Example** ```js -var callback = (data) => { +let callback = (data) => { console.info('Listening enabled. Data: ' + JSON.stringify(data)); -} -display.on("add", callback); +}; +try { + display.on("add", callback); +} catch (exception) { + console.error('Failed to register callback. Code: ' + JSON.stringify(exception)); +}; ``` ## display.off('add'|'remove'|'change') @@ -271,21 +263,147 @@ Unsubscribes from display changes. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type.
- **add**, indicating the display addition event.
- **remove**, indicating the display removal event.
- **change**, indicating the display change event.| - | callback | Callback<number> | No| Callback used to return the ID of the display.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event indicating that a display is connected to a PC.
- **remove**, indicating the display removal event. Example: event that a display is disconnected from a PC.
- **change**, indicating the display change event. Example: event that the display orientation is changed.| +| callback | Callback<number> | No| Callback used to return the ID of the display.| + +**Example** + +```js +try { + display.off("remove"); +} catch (exception) { + console.error('Failed to unregister callback. Code: ' + JSON.stringify(exception)); +}; +``` + +## display.getDefaultDisplay(deprecated) + +getDefaultDisplay(callback: AsyncCallback<Display>): void + +Obtains the default display object. 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 [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[Display](#display)> | Yes| Callback used to return the default display object.| + +**Example** + +```js +let displayClass = null; +display.getDefaultDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); + displayClass = data; +}); +``` + +## display.getDefaultDisplay(deprecated) + +getDefaultDisplay(): Promise<Display> + +Obtains the default display object. 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 [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------------------------------------- | +| Promise<[Display](#display)> | Promise used to return the default display object.| + +**Example** + +```js +let displayClass = null; +let promise = display.getDefaultDisplay(); +promise.then((data) => { + displayClass = data; + console.info('Succeeded in obtaining the default display object. Data:' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(err)); +}); +``` + +## display.getAllDisplay(deprecated) + +getAllDisplay(callback: AsyncCallback<Array<Display>>): void + +Obtains all display objects. 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 [getAllDisplays()](#displaygetalldisplays9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------------- | +| callback | AsyncCallback<Array<[Display](#display)>> | Yes | Callback used to return all the display objects.| **Example** ```js -display.off("remove"); +display.getAllDisplay((err, data) => { + if (err.code) { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}); +``` + +## display.getAllDisplay(deprecated) + +getAllDisplay(): Promise<Array<Display>> + +Obtains all display objects. 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 [getAllDisplays()](#displaygetalldisplays9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------------------------------------- | +| Promise<Array<[Display](#display)>> | Promise used to return all the display objects.| + +**Example** + +```js +let promise = display.getAllDisplay(); +promise.then((data) => { + console.info('Succeeded in obtaining all the display objects. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); +}); ``` ## Display -Implements a `Display` instance, with properties and APIs defined. +Implements a **Display** instance, with properties and APIs defined. -To call an API in the following API examples, you must first use `[getAllDisplay()](#displaygetalldisplay)`, `[getDefaultDisplay()](#displaygetdefaultdisplay)`, or `[getDefaultDisplaySync()](#displaygetdefaultdisplaysync)` to obtain a `Display` instance. +Before calling any API in **Display**, you must use [getAllDisplays()](#displaygetalldisplays9) or [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) to obtain a **Display** instance. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -296,7 +414,7 @@ To call an API in the following API examples, you must first use `[getAllDisplay | alive | boolean | Yes| No| Whether the display is alive.| | state | [DisplayState](#displaystate) | Yes| No| State of the display.| | refreshRate | number | Yes| No| Refresh rate of the display.| -| rotation | number | Yes| No| Screen rotation angle of the display.| +| rotation | number | Yes| No| Screen rotation angle of the display.
The value **0** indicates that the screen of the display rotates by 0°.
The value **1** indicates that the screen of the display rotates by 90°.
The value **2** indicates that the screen of the display rotates by 180°.
The value **3** indicates that the screen of the display rotates by 270°.| | width | number | Yes| No| Width of the display, in pixels.| | height | number | Yes| No| Height of the display, in pixels.| | densityDPI | number | Yes| No| Screen density of the display, in DPI.| @@ -308,29 +426,46 @@ To call an API in the following API examples, you must first use `[getAllDisplay ### getCutoutInfo9+ getCutoutInfo(callback: AsyncCallback<CutoutInfo>): void -Obtains the cutout information of the display. This API uses an asynchronous callback to return the result. +Obtains the cutout information of the display. This API uses an asynchronous callback to return the result. You are advised not to use the cutout area during application layout. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[CutoutInfo](#cutoutinfo9)> | Yes | Callback used to If the operation is successful, `err` is `undefined` and `data` is the `CutoutInfo` object obtained. Otherwise, `err` is an error object.| +| callback | AsyncCallback<[CutoutInfo](#cutoutinfo9)> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the **CutoutInfo** object obtained. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +}; + displayClass.getCutoutInfo((err, data) => { if (err.code) { - console.error('Failed to get cutoutInfo. Cause: ' + JSON.stringify(err)); + console.error('Failed to get cutoutInfo. Code: ' + JSON.stringify(err)); return; } console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); -}) +}); ``` ### getCutoutInfo9+ getCutoutInfo(): Promise<CutoutInfo> -Obtains the cutout information of the display. This API uses a promise to return the result. +Obtains the cutout information of the display. This API uses a promise to return the result. You are advised not to use the cutout area during application layout. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -338,11 +473,26 @@ Obtains the cutout information of the display. This API uses a promise to return | Type | Description | | ------------------- | ------------------------- | -| Promise<[CutoutInfo](#cutoutinfo9)> | Promise used to return the `CutoutInfo` object.| +| Promise<[CutoutInfo](#cutoutinfo9)> | Promise used to return the **CutoutInfo** object.| + +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | **Example** ```js +let displayClass = null; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); +}; + let promise = displayClass.getCutoutInfo(); promise.then((data) => { console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data)); 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-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index f15805a326e19b0a579d1da1ae0e44e9937fef6f..92118167ad603189eac98eae73e156a794542f99 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -14,7 +14,7 @@ import geolocation from '@ohos.geolocation'; ## geolocation.on('locationChange') -on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>) : void +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void Registers a listener for location changes with a location request initiated. @@ -34,6 +34,7 @@ Registers a listener for location changes with a location request initiated. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -44,7 +45,7 @@ Registers a listener for location changes with a location request initiated. ## geolocation.off('locationChange') -off(type: 'locationChange', callback?: Callback<Location>) : void +off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. @@ -63,6 +64,7 @@ Unregisters the listener for location changes with the corresponding location re **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { console.log('locationChanger: data: ' + JSON.stringify(location)); @@ -74,7 +76,7 @@ Unregisters the listener for location changes with the corresponding location re ## geolocation.on('locationServiceState') -on(type: 'locationServiceState', callback: Callback<boolean>) : void +on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. @@ -93,6 +95,7 @@ Registers a listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); } @@ -102,7 +105,7 @@ Registers a listener for location service status change events. ## geolocation.off('locationServiceState') -off(type: 'locationServiceState', callback?: Callback<boolean>) : void; +off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. @@ -121,6 +124,7 @@ Unregisters the listener for location service status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); } @@ -131,7 +135,7 @@ Unregisters the listener for location service status change events. ## geolocation.on('cachedGnssLocationsReporting')8+ -on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>) : void; +on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; Registers a listener for cached GNSS location reports. @@ -151,6 +155,7 @@ Registers a listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -161,7 +166,7 @@ Registers a listener for cached GNSS location reports. ## geolocation.off('cachedGnssLocationsReporting')8+ -off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>) : void; +off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; Unregisters the listener for cached GNSS location reports. @@ -180,6 +185,7 @@ Unregisters the listener for cached GNSS location reports. **Example** ```js + import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); } @@ -191,7 +197,7 @@ Unregisters the listener for cached GNSS location reports. ## geolocation.on('gnssStatusChange')8+ -on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>) : void; +on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; Registers a listener for GNSS satellite status change events. @@ -210,6 +216,7 @@ Registers a listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -219,7 +226,7 @@ Registers a listener for GNSS satellite status change events. ## geolocation.off('gnssStatusChange')8+ -off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>) : void; +off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; Unregisters the listener for GNSS satellite status change events. @@ -237,6 +244,7 @@ Unregisters the listener for GNSS satellite status change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); } @@ -247,7 +255,7 @@ Unregisters the listener for GNSS satellite status change events. ## geolocation.on('nmeaMessageChange')8+ -on(type: 'nmeaMessageChange', callback: Callback<string>) : void; +on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. @@ -266,6 +274,7 @@ Registers a listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -275,7 +284,7 @@ Registers a listener for GNSS NMEA message change events. ## geolocation.off('nmeaMessageChange')8+ -off(type: 'nmeaMessageChange', callback?: Callback<string>) : void; +off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. @@ -294,6 +303,7 @@ Unregisters the listener for GNSS NMEA message change events. **Example** ```js + import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); } @@ -304,7 +314,7 @@ Unregisters the listener for GNSS NMEA message change events. ## geolocation.on('fenceStatusChange')8+ -on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. @@ -331,13 +341,13 @@ Registers a listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], operationType: wantAgent.OperationType.START_ABILITY, requestCode: 0, - wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], }; wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { @@ -349,7 +359,7 @@ Registers a listener for status change events of the specified geofence. ## geolocation.off('fenceStatusChange')8+ -off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent) : void; +off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. @@ -375,7 +385,7 @@ Unregisters the listener for status change events of the specified geofence. wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "com.example.myapplication.MainAbility", action: "action1", } ], @@ -392,62 +402,9 @@ Unregisters the listener for status change events of the specified geofence. ``` -## geolocation.on('countryCodeChange')9+ - -on(type: 'countryCodeChange', callback: Callback<CountryCode>) : void; - -Subscribe to country code information reporting events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means subscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - ``` - - -## geolocation.off('countryCodeChange')9+ - -off(type: 'countryCodeChange', callback?: Callback<CountryCode>) : void; - -Unsubscribe from the country code to report events. - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is "countrycodechange", which means unsubscribing to the submission of country code information. | - | callback | Callback<CountryCode> | Yes | Callback is used to receive the country code information report. | - - -**Example** - - ```js - var callback = (code) => { - console.log('countryCodeChange: ' + JSON.stringify(code)); - } - geolocation.on('countryCodeChange', callback); - geolocation.off('countryCodeChange', callback); - ``` - - ## geolocation.getCurrentLocation -getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>) : void +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void Obtains the current location. This API uses an asynchronous callback to return the result. @@ -466,6 +423,7 @@ Obtains the current location. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { if (err) { @@ -482,7 +440,7 @@ Obtains the current location. This API uses an asynchronous callback to return t ## geolocation.getCurrentLocation -getCurrentLocation(request?: CurrentLocationRequest) : Promise<Location> +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> Obtains the current location. This API uses a promise to return the result. @@ -507,6 +465,7 @@ Obtains the current location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { console.log('current location: ' + JSON.stringify(result)); @@ -516,7 +475,7 @@ Obtains the current location. This API uses a promise to return the result. ## geolocation.getLastLocation -getLastLocation(callback: AsyncCallback<Location>) : void +getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. @@ -534,6 +493,7 @@ Obtains the previous location. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { console.log('getLastLocation: err=' + JSON.stringify(err)); @@ -547,7 +507,7 @@ Obtains the previous location. This API uses an asynchronous callback to return ## geolocation.getLastLocation -getLastLocation() : Promise<Location> +getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. @@ -565,6 +525,7 @@ Obtains the previous location. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); }); @@ -573,7 +534,7 @@ Obtains the previous location. This API uses a promise to return the result. ## geolocation.isLocationEnabled -isLocationEnabled(callback: AsyncCallback<boolean>) : void +isLocationEnabled(callback: AsyncCallback<boolean>): void Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. @@ -591,6 +552,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { console.log('isLocationEnabled: err=' + JSON.stringify(err)); @@ -604,7 +566,7 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ## geolocation.isLocationEnabled -isLocationEnabled() : Promise<boolean> +isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. @@ -621,15 +583,16 @@ Checks whether the location service is enabled. This API uses a promise to retur **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { - console.log('promise, isLocationEnabled: ' + result); + console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); }); ``` ## geolocation.requestEnableLocation -requestEnableLocation(callback: AsyncCallback<boolean>) : void +requestEnableLocation(callback: AsyncCallback<boolean>): void Requests to enable the location service. This API uses an asynchronous callback to return the result. @@ -647,6 +610,7 @@ Requests to enable the location service. This API uses an asynchronous callback **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { console.log('requestEnableLocation: err=' + JSON.stringify(err)); @@ -660,7 +624,7 @@ Requests to enable the location service. This API uses an asynchronous callback ## geolocation.requestEnableLocation -requestEnableLocation() : Promise<boolean> +requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. @@ -677,6 +641,7 @@ Requests to enable the location service. This API uses a promise to return the r **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation().then((result) => { console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); @@ -685,7 +650,7 @@ Requests to enable the location service. This API uses a promise to return the r ## geolocation.enableLocation -enableLocation(callback: AsyncCallback<boolean>) : void; +enableLocation(callback: AsyncCallback<boolean>): void; Enables the location service. This API uses an asynchronous callback to return the result. @@ -704,6 +669,7 @@ Enables the location service. This API uses an asynchronous callback to return t **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation((err, data) => { if (err) { console.log('enableLocation: err=' + JSON.stringify(err)); @@ -717,7 +683,7 @@ Enables the location service. This API uses an asynchronous callback to return t ## geolocation.enableLocation -enableLocation() : Promise<boolean> +enableLocation(): Promise<boolean> Enables the location service. This API uses a promise to return the result. @@ -736,6 +702,7 @@ Enables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.enableLocation().then((result) => { console.log('promise, enableLocation: ' + JSON.stringify(result)); }); @@ -743,7 +710,7 @@ Enables the location service. This API uses a promise to return the result. ## geolocation.disableLocation -disableLocation(callback: AsyncCallback<boolean>) : void; +disableLocation(callback: AsyncCallback<boolean>): void; Disables the location service. This API uses an asynchronous callback to return the result. @@ -762,6 +729,7 @@ Disables the location service. This API uses an asynchronous callback to return **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation((err, data) => { if (err) { console.log('disableLocation: err=' + JSON.stringify(err)); @@ -775,7 +743,7 @@ Disables the location service. This API uses an asynchronous callback to return ## geolocation.disableLocation -disableLocation() : Promise<boolean> +disableLocation(): Promise<boolean> Disables the location service. This API uses a promise to return the result. @@ -794,6 +762,7 @@ Disables the location service. This API uses a promise to return the result. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.disableLocation().then((result) => { console.log('promise, disableLocation: ' + JSON.stringify(result)); }); @@ -801,7 +770,7 @@ Disables the location service. This API uses a promise to return the result. ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable(callback: AsyncCallback<boolean>) : void +isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. @@ -818,6 +787,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { console.log('isGeoServiceAvailable: err=' + JSON.stringify(err)); @@ -831,7 +801,7 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ## geolocation.isGeoServiceAvailable -isGeoServiceAvailable() : Promise<boolean> +isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. @@ -848,6 +818,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); }); @@ -856,7 +827,7 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocation(request: ReverseGeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts coordinates into geographic description through reverse geocoding. This API uses an asynchronous callback to return the result. @@ -874,6 +845,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { if (err) { @@ -888,7 +860,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocation -getAddressesFromLocation(request: ReverseGeoCodeRequest) : Promise<Array<GeoAddress>>; +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. @@ -911,6 +883,7 @@ Converts coordinates into geographic description through reverse geocoding. This **Example** ```js + import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { console.log('getAddressesFromLocation: ' + JSON.stringify(data)); @@ -920,7 +893,7 @@ Converts coordinates into geographic description through reverse geocoding. This ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>) : void +getAddressesFromLocationName(request: GeoCodeRequest, callback: AsyncCallback<Array<GeoAddress>>): void Converts geographic description into coordinates through geocoding. This API uses an asynchronous callback to return the result. @@ -938,6 +911,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { if (err) { @@ -952,7 +926,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getAddressesFromLocationName -getAddressesFromLocationName(request: GeoCodeRequest) : Promise<Array<GeoAddress>> +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. @@ -975,6 +949,7 @@ Converts geographic description into coordinates through geocoding. This API use **Example** ```js + import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); @@ -984,7 +959,7 @@ Converts geographic description into coordinates through geocoding. This API use ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize(callback: AsyncCallback<number>) : void; +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. @@ -1001,6 +976,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); @@ -1014,7 +990,7 @@ Obtains the number of cached GNSS locations. ## geolocation.getCachedGnssLocationsSize8+ -getCachedGnssLocationsSize() : Promise<number>; +getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. @@ -1031,6 +1007,7 @@ Obtains the number of cached GNSS locations. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); }); @@ -1039,7 +1016,7 @@ Obtains the number of cached GNSS locations. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations(callback: AsyncCallback<boolean>) : void; +flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1056,6 +1033,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); @@ -1069,7 +1047,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.flushCachedGnssLocations8+ -flushCachedGnssLocations() : Promise<boolean>; +flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. @@ -1086,6 +1064,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. **Example** ```js + import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); }); @@ -1094,7 +1073,7 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>) : void; +sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1112,6 +1091,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { if (err) { @@ -1126,7 +1106,7 @@ Sends an extended command to the location subsystem. This API can only be called ## geolocation.sendCommand8+ -sendCommand(command: LocationCommand) : Promise<boolean>; +sendCommand(command: LocationCommand): Promise<boolean>; Sends an extended command to the location subsystem. This API can only be called by system applications. @@ -1149,6 +1129,7 @@ Sends an extended command to the location subsystem. This API can only be called **Example** ```js + import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { console.log('promise, sendCommand: ' + JSON.stringify(result)); @@ -1156,826 +1137,182 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## geolocation.isLocationPrivacyConfirmed8+ - -isLocationPrivacyConfirmed(type : LocationPrivacyType, callback: AsyncCallback<boolean>) : void; - -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## LocationRequestPriority -**System API**: This is a system API and cannot be called by third-party applications. +Sets the priority of the location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Default Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x200 | Priority unspecified.| +| ACCURACY | 0x201 | Location accuracy.| +| LOW_POWER | 0x202 | Power efficiency.| +| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1, (err, result) => { - if (err) { - console.log('isLocationPrivacyConfirmed: err=' + JSON.stringify(err)); - } - if (result) { - console.log('isLocationPrivacyConfirmed: result=' + JSON.stringify(result)); - } - }); - ``` +## LocationRequestScenario + + Sets the scenario of the location request. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.isLocationPrivacyConfirmed8+ +| Name| Default Value| Description| +| -------- | -------- | -------- | +| UNSET | 0x300 | Scenario unspecified.| +| NAVIGATION | 0x301 | Navigation.| +| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| +| CAR_HAILING | 0x303 | Ride hailing.| +| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| +| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| -isLocationPrivacyConfirmed(type : LocationPrivacyType,) : Promise<boolean>; -Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. +## GeoLocationErrorCode -**System API**: This is a system API and cannot be called by third-party applications. +Enumerates error codes of the location service. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Default Value| Description| +| -------- | -------- | -------- | +| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| +| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| +| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| +| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| +| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| +| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| +| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| -**Return value** +## ReverseGeoCodeRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the result, which indicates whether the user agrees with the privacy statement.| +Defines a reverse geocoding request. -**Example** - - ```js - geolocation.isLocationPrivacyConfirmed(1).then((result) => { - console.log('promise, isLocationPrivacyConfirmed: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| maxItems | number | No| Maximum number of location records to be returned.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed: boolean, callback: AsyncCallback<boolean>) : void; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## GeoCodeRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a geocoding request. **Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core +**System capability**: SystemCapability.Location.Location.Geocoder -**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| +| maxItems | number | No| Maximum number of location records to be returned.| +| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| +| minLongitude | number | No| Minimum longitude.| +| maxLatitude | number | No| Maximum latitude.| +| maxLongitude | number | No| Maximum longitude.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| -**Example** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true, (err, result) => { - if (err) { - console.log('setLocationPrivacyConfirmStatus: err=' + JSON.stringify(err)); - } - if (result) { - console.log('setLocationPrivacyConfirmStatus: result=' + JSON.stringify(result)); - } - }); - ``` +## GeoAddress + +Defines a geographic location. + +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Geocoder -## geolocation.setLocationPrivacyConfirmStatus8+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| +| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | No| Landmark of the location.| +| countryCode7+ | string | No| Country code.| +| countryName7+ | string | No| Country name.| +| administrativeArea7+ | string | No| Administrative region name.| +| subAdministrativeArea7+ | string | No| Sub-administrative region name.| +| locality7+ | string | No| Locality information. | +| subLocality7+ | string | No| Sub-locality information. | +| roadName7+ | string | No| Road name.| +| subRoadName7+ | string | No| Auxiliary road information.| +| premises7+ | string | No| House information.| +| postalCode7+ | string | No| Postal code.| +| phoneNumber7+ | string | No| Phone number.| +| addressUrl7+ | string | No| Website URL.| +| descriptions7+ | Array<string> | No| Additional description.| +| descriptionsSize7+ | number | No| Total number of additional descriptions.| -setLocationPrivacyConfirmStatus(type : LocationPrivacyType, isConfirmed : boolean) : Promise<boolean>; -Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. +## LocationRequest -**System API**: This is a system API and cannot be called by third-party applications. +Defines a location request. **Permission required**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -**Parameters** +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| +| timeInterval | number | No| Time interval at which location information is reported.| +| distanceInterval | number | No| Distance interval at which location information is reported.| +| maxAccuracy | number | No| Location accuracy.| - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | LocationPrivacyType | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when enabling the location service.| - | isConfirmed | boolean | Yes| Callback used to return the result, which indicates whether the user agrees with the privacy statement.| -**Return value** +## CurrentLocationRequest - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result.| +Defines the current location request. -**Example** - - ```js - geolocation.setLocationPrivacyConfirmStatus(1, true).then((result) => { - console.log('promise, setLocationPrivacyConfirmStatus: ' + JSON.stringify(result)); - }); - ``` +**Permission required**: ohos.permission.LOCATION +**System capability**: SystemCapability.Location.Location.Core -## geolocation.getCountryCode9+ +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| +| maxAccuracy | number | No| Location accuracy, in meters.| +| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| -getCountryCode(callback: AsyncCallback<CountryCode>) : void; -Query the current country code. +## SatelliteStatusInfo8+ -**System capability**: SystemCapability.Location.Location.Core +Defines the satellite status information. -**Parameters** +**Permission required**: ohos.permission.LOCATION - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<CountryCode> | Yes | Callback is used to receive the country code. | +**System capability**: SystemCapability.Location.Location.Gnss -**Example**: - - ```js - geolocation.getCountryCode((err, result) => { - if (err) { - console.log('getCountryCode: err=' + JSON.stringify(err)); - } - if (result) { - console.log('getCountryCode: result=' + JSON.stringify(result)); - } - }); - ``` +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| Number of satellites.| +| satelliteIds | Array<number> | Yes| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| Altitude information.| +| azimuths | Array<number> | Yes| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| Carrier frequency.| -## geolocation.getCountryCode9+ +## CachedGnssLocationsRequest8+ -getCountryCode() : Promise<CountryCode>; +Represents a request for reporting cached GNSS locations. -Query the current country code. +**Permission required**: ohos.permission.LOCATION -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<CountryCode> | return country code. | - -**Example**: - - ```js - geolocation.getCountryCode() - .then((result) => { - console.log('promise, getCountryCode: result=' + JSON.stringify(result)); - }) - .catch((error) => { - console.log('promise, getCountryCode: error=' + JSON.stringify(error)); - }); - ``` - - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates under what scenario the position simulation function is enabled. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request, (err, result) => { - if (err) { - console.log('enableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('enableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - -## geolocation.enableLocationMock9+ - -enableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -Enable the position simulation function of a scene, and only one scene can be enabled at the same time. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates which scene's position simulation function is enabled. If this parameter is not carried, it means that the position simulation function of all scenes is enabled. | - - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.enableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, enableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario, callback: AsyncCallback<void>) : void; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request, (err, result) => { - if (err) { - console.log('disableLocationMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableLocationMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableLocationMock9+ - -disableLocationMock(scenario?: LocationRequestScenario) : Promise<void>; - -To disable the position simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | scenario | LocationRequestScenario | No | Indicates to disable the position simulation function of a scene. If this parameter is not carried, it means to disable the position simulation function of all scenes. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr, otherwise it will return an error message | - -**Example**: - - ```js - var request = {"scenario": 0x0301}; - geolocation.disableLocationMock(request) - .then((result) => { - if (result) { - console.log('promise, disableLocationMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableLocationMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig, callback: AsyncCallback<void>) : void; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations": locations}; - geolocation.setMockedLocations(config, (err, data) => { - if (err) { - console.log('setMockedLocations: err=' + JSON.stringify(err)); - } - if (data) { - console.log('setMockedLocations: data=' + JSON.stringify(data)); - } - }); - ``` - -## geolocation.setMockedLocations9+ - -setMockedLocations(config: LocationMockConfig) : Promise<void>; - -Set the simulated location information, and then report the simulated location at the time interval carried in the interface. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | LocationMockConfig | Yes | Indicates the configuration parameters of location simulation, including the time interval of simulation location reporting and the array of simulation locations. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var locations = [ - {"latitude": 30.12, "longitude": 120.11, "altitude": 123, "accuracy": 1, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 1000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 31.13, "longitude": 121.11, "altitude": 123, "accuracy": 2, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 2000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 32.14, "longitude": 122.11, "altitude": 123, "accuracy": 3, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 3000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 33.15, "longitude": 123.11, "altitude": 123, "accuracy": 4, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 4000000000, "additionSize": 0, "isFromMock": true}, - {"latitude": 34.16, "longitude": 124.11, "altitude": 123, "accuracy": 5, "speed": 5.2, "timeStamp": 16594326109, "direction": 123.11, "timeSinceBoot": 5000000000, "additionSize": 0, "isFromMock": true} - ]; - var config = {"timeInterval": 5, "locations":locations}; - geolocation.setMockedLocations(config) - .then((result) => { - if (result) { - console.log('promise, setMockedLocations: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setMockedLocations: error=' + JSON.stringify(error)); - } - }); - ``` - - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock((err, data) => { - if (err) { - console.log('enableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableReverseGeocodingMock: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableReverseGeocodingMock9+ - -enableReverseGeocodingMock() : Promise<void>; - -Enable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.enableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, enableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, enableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock(callback: AsyncCallback<void>) : void; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock((err, result) => { - if (err) { - console.log('disableReverseGeocodingMock: err=' + JSON.stringify(err)); - } - if (result) { - console.log('disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }); - ``` - - -## geolocation.disableReverseGeocodingMock9+ - -disableReverseGeocodingMock() : Promise<void>; - -Disable reverse geocoding simulation function. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters**: - -None - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - geolocation.disableReverseGeocodingMock() - .then((result) => { - if (result) { - console.log('promise, disableReverseGeocodingMock: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, disableReverseGeocodingMock: error=' + JSON.stringify(error)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>, callback: AsyncCallback<void>) : void; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - | callback | AsyncCallback<void> | Yes | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos, (err, data) => { - if (err) { - console.log('promise, setReverseGeocodingMockInfo, err:' + JSON.stringify(err)); - } - if (data) { - console.log('promise, setReverseGeocodingMockInfo, data:' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.setReverseGeocodingMockInfo9+ - -setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>) : Promise<void>; - -Set the configuration information of the reverse geocoding simulation function, including the corresponding relationship between location and place name. If the location information is in the configuration information during the subsequent reverse geocoding query, the corresponding place name will be returned. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mockInfos | Array<ReverseGeocodingMockInfo> | Yes | An array of configuration parameters indicating the inverse geocoding simulation function. The configuration parameters of the inverse geocoding simulation function include a location and a place name. | - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<void> | It is used to receive the execution result. If the execution is successful, it will return nullptr. Otherwise, it will return an error message. | - -**Example**: - - ```js - var mockInfos = [ - {"location": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 30.12, "longitude": 120.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 31.12, "longitude": 121.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 32.12, "longitude": 122.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 33.12, "longitude": 123.11, "maxItems": 1, "isFromMock": true}}, - {"location": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1}, "geoAddress": {"locale": "zh", "latitude": 34.12, "longitude": 124.11, "maxItems": 1, "isFromMock": true}}, - ]; - geolocation.setReverseGeocodingMockInfo(mockInfos) - .then((result) => { - if (result) { - console.log('promise, setReverseGeocodingMockInfo: result=' + JSON.stringify(result)); - } - }) - .catch((error) => { - if (error) { - console.log('promise, setReverseGeocodingMockInfo: error=' + JSON.stringify(error)); - } - }); - ``` - - -## LocationRequestPriority - -Sets the priority of the location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| UNSET | 0x200 | Priority unspecified.| -| ACCURACY | 0x201 | Location accuracy.| -| LOW_POWER | 0x202 | Power efficiency.| -| FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| - - -## LocationRequestScenario - - Sets the scenario of the location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| UNSET | 0x300 | Scenario unspecified.| -| NAVIGATION | 0x301 | Navigation.| -| TRAJECTORY_TRACKING | 0x302 | Trajectory tracking.| -| CAR_HAILING | 0x303 | Ride hailing.| -| DAILY_LIFE_SERVICE | 0x304 | Daily life services.| -| NO_POWER | 0x305 | Power efficiency. Your application does not proactively start the location service. When responding to another application requesting the same location service, the system marks a copy of the location result to your application. In this way, your application will not consume extra power for obtaining the user location.| - - -## GeoLocationErrorCode - -Enumerates error codes of the location service. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| NOT_SUPPORTED9+ | 100 | Indicates that the interface function is not supported. | -| INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| -| REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| -| GEOCODE_ERROR7+ | 103 | Failed to call the geocoding API.| -| LOCATOR_ERROR7+ | 104 | Failed to obtain the location.| -| LOCATION_SWITCH_ERROR7+ | 105 | Failed to change the location service switch.| -| LAST_KNOWN_LOCATION_ERROR7+ | 106 | Failed to obtain the previous location.| -| LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| -| QUERY_COUNTRY_CODE_ERROR9+ | 108 | Indicates that the country code query failed. | - - -## ReverseGeoCodeRequest - -Defines a reverse geocoding request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| latitude | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| maxItems | number | No| Maximum number of location records to be returned.| - - -## GeoCodeRequest - -Defines a geocoding request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| locale | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| description | number | Yes| Location description, for example, No. xx, xx Road, Pudong New District, Shanghai.| -| maxItems | number | No| Maximum number of location records to be returned.| -| minLatitude | number | No| Minimum latitude. This parameter is used with minLongitude, maxLatitude, and maxLongitude to specify the latitude and longitude ranges.| -| minLongitude | number | No| Minimum longitude.| -| maxLatitude | number | No| Maximum latitude.| -| maxLongitude | number | No| Maximum longitude.| - - -## GeoAddress - -Defines a geographic location. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Geocoder - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | No| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| locale7+ | string | No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| -| placeName7+ | string | No| Landmark of the location.| -| countryCode7+ | string | No| Country code.| -| countryName7+ | string | No| Country name.| -| administrativeArea7+ | string | No| Administrative region name.| -| subAdministrativeArea7+ | string | No| Sub-administrative region name.| -| locality7+ | string | No| Locality information. | -| subLocality7+ | string | No| Sub-locality information. | -| roadName7+ | string | No| Road name.| -| subRoadName7+ | string | No| Auxiliary road information.| -| premises7+ | string | No| House information.| -| postalCode7+ | string | No| Postal code.| -| phoneNumber7+ | string | No| Phone number.| -| addressUrl7+ | string | No| Website URL.| -| descriptions7+ | Array<string> | No| Additional description.| -| descriptionsSize7+ | number | No| Total number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the geographical name information comes from the reverse geocoding simulation function. | - - -## LocationRequest - -Defines a location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Scenario of the location request.| -| timeInterval | number | No| Time interval at which location information is reported.| -| distanceInterval | number | No| Distance interval at which location information is reported.| -| maxAccuracy | number | No| Location accuracy.| - - -## CurrentLocationRequest - -Defines the current location request. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | [LocationRequestPriority](#locationrequestpriority) | No| Priority of the location request.| -| scenario | [LocationRequestScenario](#locationrequestscenario) | No| Scenario of the location request.| -| maxAccuracy | number | No| Location accuracy, in meters.| -| timeoutMs | number | No| Timeout duration, in milliseconds. The minimum value is 1000.| - - -## SatelliteStatusInfo8+ - -Defines the satellite status information. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Gnss - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| satellitesNumber | number | Yes| Number of satellites.| -| satelliteIds | Array<number> | Yes| Array of satellite IDs.| -| carrierToNoiseDensitys | Array<number> | Yes| Carrier-to-noise density ratio, that is, **cn0**.| -| altitudes | Array<number> | Yes| Altitude information.| -| azimuths | Array<number> | Yes| Azimuth information.| -| carrierFrequencies | Array<number> | Yes| Carrier frequency.| - - -## CachedGnssLocationsRequest8+ - -Represents a request for reporting cached GNSS locations. - -**Permission required**: ohos.permission.LOCATION - -**System capability**: SystemCapability.Location.Location.Gnss +**System capability**: SystemCapability.Location.Location.Gnss | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -2063,58 +1400,3 @@ Defines a location. | timeSinceBoot7+ | number | Yes| Location timestamp since boot.| | additions7+ | Array<string> | No| Additional information.| | additionSize7+ | number | No| Number of additional descriptions.| -| isFromMock9+ | Boolean | No | Indicates whether the location information comes from the location simulation function. | - - -## ReverseGeocodingMockInfo9+ - -The configuration information of the reverse geocoding simulation function includes a location information and a place name information. - -**System capability**:SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| location | ReverseGeoCodeRequest | Yes | Indicates longitude and latitude information. | -| geoAddress | GeoAddress | Yes | Represents a geographic location. | - - -## LocationMockConfig9+ - -The configuration parameters of the location simulation function include the time interval of the simulation position report and the array of simulation locations. - -**System capability**: SystemCapability.Location.Location.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timeInterval | number | Yes | Indicates the time interval of analog location reporting, in seconds. | -| locations | Array<Location> | Yes | Represents an array of mocked locations. | - - -## CountryCode9+ - -The country code information structure contains the country code string and the source information of the country code. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| country | string | Yes | Represents the country code string. | -| type | CountryCodeType | Yes | Indicates the source of country code information. | - - -## CountryCodeType9+ - -Country code source type. - -**System capability**: SystemCapability.Location.Location.Core - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| COUNTRY_CODE_FROM_LOCALE | 1 | The country code obtained from the language configuration information of the globalization module. | -| COUNTRY_CODE_FROM_SIM | 2 | The country code obtained from the SIM card. | -| COUNTRY_CODE_FROM_LOCATION | 3 | Based on the user's location information, the country code is queried through reverse geocoding. | -| COUNTRY_CODE_FROM_NETWORK | 4 | The country code obtained from the cellular network registration information. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 866a5833b69feb01da451f2464fbdd7915f06172..6b7463a11b96f468bd275b0fd0fd841fe690713c 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -40,9 +40,11 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper const color = new ArrayBuffer(96); let bufferArr = new Uint8Array(color); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts) - .then((pixelmap) => { - }) +image.createPixelMap(color, opts).then((pixelmap) => { + console.log('Succeeded in creating pixelmap.'); +}).catch(error => { + console.log('Failed to create pixelmap.'); +}) ``` ## image.createPixelMap8+ @@ -115,7 +117,7 @@ const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer).then(() => { console.log('Succeeded in reading image pixel data.'); // Called if the condition is met. }).catch(error => { - console.log('Failed to read image pixel data.'); // Called if no condition is met. + console.log('Failed to read image pixel data.'); // Called if no condition is met. }) ``` @@ -392,7 +394,6 @@ Obtains pixel map information of this image. This API uses a promise to return t const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 2, size: { height: 6, width: 8 } } image.createPixelMap(color, opts).then(pixelmap => { - globalpixelmap = pixelmap; if (pixelmap == undefined) { console.error("Failed to obtain the image pixel map information."); } @@ -428,7 +429,6 @@ const color = new ArrayBuffer(96); let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } image.createPixelMap(color, opts, (err, pixelmap) => { if (pixelmap == undefined) { - globalpixelmap = pixelmap; console.error("Failed to obtain the image pixel map information."); } pixelmap.getImageInfo((err, imageInfo) => { @@ -559,9 +559,8 @@ Sets an opacity rate for this image pixel map. This API uses a promise to return **Example** ```js -async function () { - var rate = 0.5; - await pixelmap.opacity(rate); +async function Demo() { + await pixelmap.opacity(0.5); } ``` @@ -582,9 +581,9 @@ Creates a **PixelMap** object that contains only the alpha channel information. **Example** ```js -async function () { - await pixelmap.createAlphaPixelmap(); -}) +async function Demo() { + await pixelmap.createAlphaPixelmap(); +} ``` ### createAlphaPixelmap9+ @@ -632,7 +631,7 @@ Scales this image based on the input width and height. This API uses an asynchro **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -661,7 +660,7 @@ Scales this image based on the input width and height. This API uses a promise t **Example** ```js -async function () { +async function Demo() { await pixelmap.scale(2.0, 1.0); } ``` @@ -685,7 +684,7 @@ Translates this image based on the input coordinates. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -714,7 +713,7 @@ Translates this image based on the input coordinates. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.translate(3.0, 1.0); } ``` @@ -737,7 +736,7 @@ Rotates this image based on the input angle. This API uses an asynchronous callb **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -765,7 +764,7 @@ Rotates this image based on the input angle. This API uses a promise to return t **Example** ```js -async function () { +async function Demo() { await pixelmap.rotate(90.0); } ``` @@ -789,7 +788,7 @@ Flips this image horizontally or vertically, or both. This API uses an asynchron **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -818,7 +817,7 @@ Flips this image horizontally or vertically, or both. This API uses a promise to **Example** ```js -async function () { +async function Demo() { await pixelmap.flip(false, true); } ``` @@ -841,7 +840,7 @@ Crops this image based on the input size. This API uses an asynchronous callback **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -869,7 +868,7 @@ Crops this image based on the input size. This API uses a promise to return the **Example** ```js -async function () { +async function Demo() { await pixelmap.crop({ x: 0, y: 0, size: { height: 100, width: 100 } }); } ``` @@ -891,15 +890,10 @@ Releases this **PixelMap** object. This API uses a promise to return the result. **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }).catch(error => { - console.log('Failed to release pixelmap object.'); - }) +pixelmap.release().then(() => { + console.log('Succeeded in releasing pixelmap object.'); +}).catch(error => { + console.log('Failed to release pixelmap object.'); }) ``` @@ -920,13 +914,8 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Example** ```js -const color = new ArrayBuffer(96); -let bufferArr = new Uint8Array(color); -let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } -image.createPixelMap(color, opts, (pixelmap) => { - pixelmap.release().then(() => { - console.log('Succeeded in releasing pixelmap object.'); - }) +pixelmap.release(() => { + console.log('Succeeded in releasing pixelmap object.'); }) ``` @@ -1345,11 +1334,10 @@ Modifies the value of a property in this image. This API uses a promise to retur **Example** ```js -imageSourceApi.modifyImageProperty("ImageWidth", "120") - .then(() => { - const w = imageSourceApi.getImageProperty("ImageWidth") - console.info('w', w); - }) +imageSourceApi.modifyImageProperty("ImageWidth", "120").then(() => { + const w = imageSourceApi.getImageProperty("ImageWidth") + console.info('w', w); +}) ``` ### modifyImageProperty9+ @@ -1401,9 +1389,9 @@ Updates incremental data. This API uses a promise to return the result. ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10).then(data => { - console.info('Succeeded in updating data.'); - }) +imageSourceApi.updateData(array, false, 0, 10).then(data => { + console.info('Succeeded in updating data.'); +}) ``` @@ -1429,11 +1417,11 @@ Updates incremental data. This API uses an asynchronous callback to return the r ```js const array = new ArrayBuffer(100); -imageSourceIncrementalSApi.updateData(array, false, 0, 10,(error,data )=> { - if(data !== undefined){ - console.info('Succeeded in updating data.'); - } - }) +imageSourceApi.updateData(array, false, 0, 10,(error,data )=> { + if(data !== undefined){ + console.info('Succeeded in updating data.'); + } +}) ``` ### createPixelMap7+ @@ -1617,6 +1605,7 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, data => {}) ``` @@ -1645,6 +1634,7 @@ Packs an image. This API uses a promise to return the result. **Example** ```js +const imageSourceApi = image.createImageSource(0); let packOpts = { format:"image/jpeg", quality:98 } imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { @@ -1673,10 +1663,14 @@ Packs an image. This API uses an asynchronous callback to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts, data => { - console.log('Succeeded in packing the image.'); +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts, data => { + console.log('Succeeded in packing the image.'); + }) }) ``` @@ -1704,14 +1698,18 @@ Packs an image. This API uses a promise to return the result. **Example** ```js -let packOpts = { format:"image/jpeg", quality:98 } -const pixelMapApi = new ArrayBuffer(400); -imagePackerApi.packing(pixelMapApi, packOpts) - .then( data => { - console.log('Succeeded in packing the image.'); - }).catch(error => { - console.log('Failed to pack the image..'); - }) +const color = new ArrayBuffer(96); +let bufferArr = new Uint8Array(color); +let opts = { editable: true, pixelFormat: 3, size: { height: 4, width: 6 } } +image.createPixelMap(color, opts).then((pixelmap) => { + let packOpts = { format:"image/jpeg", quality:98 } + imagePackerApi.packing(pixelmap, packOpts) + .then( data => { + console.log('Succeeded in packing the image.'); + }).catch(error => { + console.log('Failed to pack the image..'); + }) +}) ``` ### release @@ -1764,7 +1762,7 @@ imagePackerApi.release().then(()=>{ createImageReceiver(width: number, height: number, format: number, capacity: number): ImageReceiver -Create an **ImageReceiver** instance by specifying the image width, height, format, and capacity. +Creates an **ImageReceiver** instance by specifying the image width, height, format, and capacity. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver @@ -1774,7 +1772,7 @@ Create an **ImageReceiver** instance by specifying the image width, height, form | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format. | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1955,7 +1953,7 @@ receiver.readNextImage().then(img => { }) ``` -### on('imageArrival')9+ +### on9+ on(type: 'imageArrival', callback: AsyncCallback\): void @@ -2020,6 +2018,228 @@ receiver.release().then(() => { }) ``` +## image.createImageCreator9+ + +createImageCreator(width: number, height: number, format: number, capacity: number): ImageCreator + +Creates an **ImageCreator** instance by specifying the image width, height, format, and capacity. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| width | number | Yes | Default image width. | +| height | number | Yes | Default image height. | +| format | number | Yes | Image format, for example, YCBCR_422_SP or JPEG. | +| capacity | number | Yes | Maximum number of images that can be accessed at the same time.| + +**Return value** + +| Type | Description | +| ------------------------------ | --------------------------------------- | +| [ImageCreator](#imagecreator9) | Returns an **ImageCreator** instance if the operation is successful.| + +**Example** + +```js +var creator = image.createImageCreator(8192, 8, 4, 8); +``` + +## ImageCreator9+ + +Requests an image native data area, and provides APIs for applications to compile native image data. +Before calling any APIs in **ImageCreator**, you must create an **ImageCreator** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +| Name | Type | Readable| Writable| Description | +| -------- | ---------------------------- | ---- | ---- | ------------------ | +| capacity | number | Yes | No | Maximum number of images that can be accessed at the same time.| +| format | [ImageFormat](#imageformat9) | Yes | No | Image format. | + +### dequeueImage9+ + +dequeueImage(callback: AsyncCallback\): void + +Obtains an image buffer from the idle queue and writes image data into it. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ---------------------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage((err, img) => { + if (err) { + console.info('dequeueImage succeeded.'); + } + console.info('dequeueImage failed.')); +}); +``` + +### dequeueImage9+ + +dequeueImage(): Promise\ + +Obtains an image buffer from the idle queue and writes image data into it. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| --------------- | ------------- | +| Promise\ | Promise used to return the drawn image.| + +**Example** + +```js +creator.dequeueImage().then(img => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.log('dequeueImage failed: ' + error); +}) +``` + +### queueImage9+ + +queueImage(interface: Image, callback: AsyncCallback\): void + +Places the drawn image in the dirty queue. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| interface | Image | Yes | Drawn image.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img, (err) => { + if (err) { + console.info('dequeueImage failed: ' + err); + } + console.info('dequeueImage succeeded'); +}) +``` + +### queueImage9+ + +queueImage(interface: Image): Promise\ + +Places the drawn image in the dirty queue. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | --------| ---- | ------------------- | +| interface | Image | Yes | Drawn image.| + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.queueImage(img).then(() => { + console.info('dequeueImage succeeded.'); +}).catch(error => { + console.info('dequeueImage failed: ' + error); +}) +``` + +### on9+ + +on(type: 'imageRelease', callback: AsyncCallback\): void + +Listens for image release events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| type | string | Yes | Type of event, which is **'imageRelease'**.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.on('imageRelease', (err) => { + if (err) { + console.info('on faild' + err); + } + console.info('on succeeded'); +}) +``` + +### release9+ + +release(callback: AsyncCallback\): void + +Releases this **ImageCreator** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------------| ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release((err) => { + if (err) { + console.info('release failed: ' + err); + } + console.info('release succeeded'); +}); +``` +### release9+ + +release(): Promise\ + +Releases this **ImageCreator** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Image.ImageCreator + +**Return value** + +| Type | Description | +| -------------- | ------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +creator.release().then(() => { + console.info('release succeeded'); +}).catch(error => { + console.info('release failed'); +}) +``` + ## Image9+ Provides APIs for basic image operations, including obtaining image information and reading and writing image data. An **Image** instance is returned when [readNextImage](#readnextimage9) and [readLatestImage](#readlatestimage9) are called. @@ -2147,7 +2367,7 @@ Describes area information in an image. | ------ | ------------------ | ---- | ---- | ------------------------------------------------------------ | | pixels | ArrayBuffer | Yes | No | Pixels of the image. | | offset | number | Yes | No | Offset for data reading. | -| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | +| stride | number | Yes | No | Number of bytes from one row of pixels in memory to the next row of pixels in memory. The value of **stride** must be greater than or equal to the value of **region.size.width** multiplied by 4. | | region | [Region](#region7) | Yes | No | Region to read or write. The width of the region to write plus the X coordinate cannot be greater than the width of the original image. The height of the region to write plus the Y coordinate cannot be greater than the height of the original image.| ## ImageInfo @@ -2159,6 +2379,7 @@ Describes image information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ---------- | | size | [Size](#size) | Yes | Yes | Image size.| +| density9+ | number | Yes | Yes | Pixel density, in ppi.| ## Size @@ -2181,8 +2402,13 @@ Enumerates the pixel formats of images. | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | -| RGBA_8888 | 3 | RGBA_8888. | -| BGRA_88889+ | 4 | BGRA_8888. | +| RGBA_8888 | 3 | RGBA_8888.| +| BGRA_88889+ | 4 | BGRA_8888.| +| RGB_8889+ | 5 | RGB_888. | +| ALPHA_89+ | 6 | ALPHA_8. | +| RGBA_F169+ | 7 | RGBA_F16. | +| NV219+ | 8 | NV21. | +| NV129+ | 9 | NV12. | ## AlphaType9+ @@ -2194,8 +2420,8 @@ Enumerates the alpha types of images. | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| -| PREMUL | 2 | Premultiplied alpha. | -| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | +| PREMUL | 2 | Premultiplied alpha. | +| UNPREMUL | 3 | Unpremultiplied alpha, that is, straight alpha. | ## ScaleMode9+ @@ -2250,6 +2476,7 @@ Defines image decoding options. | desiredRegion | [Region](#region7) | Yes | Yes | Region to decode. | | desiredPixelFormat | [PixelMapFormat](#pixelmapformat7) | Yes | Yes | Pixel map format for decoding.| | index | number | Yes | Yes | Index of the image to decode. | +| fitDensity9+ | number | Yes | Yes | Image pixel density, in ppi. | ## Region7+ @@ -2260,7 +2487,7 @@ Describes region information. | Name| Type | Readable| Writable| Description | | ---- | ------------- | ---- | ---- | ------------ | | size | [Size](#size) | Yes | Yes | Region size. | -| x | number | Yes | Yes | X coordinate of the region.| +| x | number | Yes | Yes | X coordinate to translate.| | y | number | Yes | Yes | Y coordinate of the region.| ## PackingOption @@ -2271,8 +2498,9 @@ Defines the option for image packing. | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | --------------------------------------------------- | -| format | string | Yes | Yes | Format of the packed image.
Currently, the JPEG and WebP formats are supported. | +| format | string | Yes | Yes | Format of the packed image.
Currently, the following raw formats are supported: .jpg, .png, .gif, .bmp, and .webp.| | quality | number | Yes | Yes | Quality of the output image during JPEG encoding. The value ranges from 1 to 100.| +| bufferSize9+ | number | Yes | Yes | Buffer size, which is used to set the image size. The default value is 10 MB.| ## GetImagePropertyOptions7+ @@ -2299,8 +2527,14 @@ Describes the exchangeable image file format (EXIF) information of an image. | IMAGE_WIDTH | "ImageWidth" | Image width. | | GPS_LATITUDE | "GPSLatitude" | Image latitude. | | GPS_LONGITUDE | "GPSLongitude" | Image longitude. | -| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | -| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| GPS_LATITUDE_REF | "GPSLatitudeRef" | Latitude reference, for example, N or S. | +| GPS_LONGITUDE_REF | "GPSLongitudeRef" | Longitude reference, for example, W or E. | +| DATE_TIME_ORIGINAL9+ | "DateTimeOriginal" | Shooting time, for example, 2022:09:06 15:48:00. | +| EXPOSURE_TIME9+ | "ExposureTime" | Exposure time, for example, 1/33 sec.| +| SCENE_TYPE9+ | "SceneType" | Shooting scene mode, for example, portrait, scenery, motion, and night sight. | +| ISO_SPEED_RATINGS9+ | "ISOSpeedRatings" | ISO sensitivity or ISO speed, for example, 400. | +| F_NUMBER9+ | "FNumber" | Aperture, for example, f/1.8. | + ## ImageFormat9+ diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md index ae8312d452b3a7a0fdea35b0330b5f092ddef05d..a6554d89363a60c801a547d76f306b1b8744e71e 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @@ -47,10 +47,11 @@ Starts an ability with the **want** parameter. This API uses an asynchronous cal ```js let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility"}; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringify(err)); + 'bundleName': 'com.example.myapp', + 'abilityName': 'MyAbility' + }; + this.context.startAbility(want, (err) => { + console.log('startAbility result:' + JSON.stringify(err)); }); ``` @@ -79,8 +80,8 @@ Starts an ability with the mandatory **want** and optional **options** parameter ```js let want = { - "bundleName": "com.example.myapp", - "abilityName": "MyAbility" + 'bundleName': 'com.example.myapp', + 'abilityName': 'MyAbility' }; this.context.startAbility(want).then((data) => { console.log('success:' + JSON.stringify(data)); @@ -110,15 +111,15 @@ Starts an ability with the **want** and **options** parameters. This API uses an ```js var want = { - "deviceId": "", - "bundleName": "com.extreme.test", - "abilityName": "MainAbility" + 'deviceId': '', + 'bundleName': 'com.extreme.test', + 'abilityName': 'MainAbility' }; var options = { windowMode: 0, }; this.context.startAbility(want, options, (error) => { - console.log("error.code = " + error.code) + console.log('error.code = ' + error.code) }) ``` @@ -140,7 +141,7 @@ Terminates this ability. This API uses an asynchronous callback to return the re ```js this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); + console.log('terminateSelf result:' + JSON.stringify(err)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md index 07084623fbe78c307fdc787b1715b398e3d97675..9fdcb88e96a336e19a87efab9c9856af746df558 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -101,7 +101,7 @@ This is a system API. inputMonitor.off("touch"); ``` -off(type: "mouse", receiver?:Callback):void +off(type: "mouse", receiver?:Callback\):void Stops listening for global mouse events. diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md index a0d7d5ccf282bb20fe549332e57e580ee3e52d7c..4502b4cd9601bf0ae050f972a674028fb271a86a 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -16,7 +16,7 @@ import connection from '@ohos.net.connection' getDefaultNet(callback: AsyncCallback\): void -Obtains the default active data network. This API uses an asynchronous callback to return the result. +Obtains the default active data network. This API uses an asynchronous callback to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -41,7 +41,7 @@ connection.getDefaultNet(function (error, netHandle) { getDefaultNet(): Promise\ -Obtains the default active data network. This API uses a promise to return the result. +Obtains the default active data network. This API uses a promise to return the result. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -61,11 +61,36 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` +## connection.getDefaultNetSync + +getDefaultNetSync(): NetHandle; + +Obtains the default active data network in synchronous mode. You can use [getNetCapabilities](#connectiongetnetcapabilities) to obtain information such as the network type and capabilities. + +**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. +Checks whether the default data network is activated. This API uses an asynchronous callback to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. + +**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core @@ -88,7 +113,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. +Checks whether the default data network is activated. This API uses a promise to return the result. You can use [getDefaultNet](#connectiongetdefaultnet) to obtain the default data network, if any. + +**Required permission**: ohos.permission.GET_NETWORK_INFO **System capability**: SystemCapability.Communication.NetManager.Core @@ -110,7 +137,7 @@ connection.hasDefaultNet().then(function (has) { getAllNets(callback: AsyncCallback<Array<NetHandle>>): void -Obtains the list of all connected networks. This API uses an asynchronous callback to return the result. +Obtains the list of all active data networks. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -136,7 +163,7 @@ connection.getAllNets(function (error, nets) { getAllNets(): Promise<Array<NetHandle>> -Obtains the list of all connected networks. This API uses a promise to return the result. +Obtains the list of all active data networks. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -160,7 +187,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 @@ -280,7 +307,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports connection of the data network to the network management module. This API uses an asynchronous callback to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. +Reports connection of the data network. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -308,7 +335,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetConnected(netHandle: NetHandle): Promise<void> -Reports connection of the data network to the network management module. This API uses a promise to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. +Reports connection of the data network. This API uses a promise to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -341,7 +368,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback<void>): void -Reports disconnection of the data network to the network management module. This API uses an asynchronous callback to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. +Reports disconnection of the data network. This API uses an asynchronous callback to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -369,8 +396,7 @@ connection.getDefaultNet().then(function (netHandle) { reportNetDisconnected(netHandle: NetHandle): Promise<void> -Reports disconnection of the data network to the network management module. This API uses a promise to return the result. If this API is called, the application considers that the network connection state (**ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED**) is inconsistent with that in the network management module. - +Reports disconnection of the data network. This API uses a promise to return the result. **Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET @@ -559,7 +585,7 @@ connection.disableAirplaneMode().then(function (error) { createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection -Creates a **NetConnection** object. **netSpecifier** specifies the network, and **timeout** specifies the timeout interval in ms. **timeout** is configurable only when **netSpecifier** is specified. If neither of them is present, the default network is used. +Obtains the handle of the network specified by **netSpecifier**. **System capability**: SystemCapability.Communication.NetManager.Core @@ -793,6 +819,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 @@ -951,9 +1079,9 @@ Defines the network capability. | ------------------------ | ---- | ---------------------- | | NET_CAPABILITY_MMS | 0 | The network can connect to the carrier's Multimedia Messaging Service Center (MMSC) to send and receive multimedia messages.| | NET_CAPABILITY_NOT_METERED | 11 | The network traffic is not metered.| -| NET_CAPABILITY_INTERNET | 12 | The network has the Internet access capability, which is set by the network provider.| +| NET_CAPABILITY_INTERNET | 12 | The network can connect to the Internet.| | NET_CAPABILITY_NOT_VPN | 15 | The network does not use a Virtual Private Network (VPN).| -| NET_CAPABILITY_VALIDATED | 16 | The Internet access capability of the network is successfully verified by the network management module. | +| NET_CAPABILITY_VALIDATED | 16 | The network is available. | ## NetBearType diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md new file mode 100644 index 0000000000000000000000000000000000000000..bf132f3c63710fc83b04a3411eb2477f2fe8b855 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -0,0 +1,301 @@ +# Ethernet Connection Management + +The Ethernet Connection Management module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import ethernet from '@ohos.net.ethernet' +``` + +## ethernet.setIfaceConfig + +setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void; + +Sets the network interface configuration. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ------------------------------------------ | +| iface | string | Yes | Name of the network interface. | +| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the return result is empty. If the operation fails, an error code is returned.| + +**Example** + +```js +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", + gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}, + (error) => { + if (error) { + console.log("setIfaceConfig callback error = " + error); + } else { + console.log("setIfaceConfig callback ok "); + } + }); +``` + +## ethernet.setIfaceConfig + +setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\; + +Sets the network interface configuration. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------- | ---- | ------------------------ | +| iface | string | Yes | Name of the network interface. | +| ic | [InterfaceConfiguration](#interfaceconfiguration) | Yes | Network interface configuration to set.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", routeAddr:"192.168.1.1", + gateAddr:"192.168.1.1", maskAddr:"255.255.255.0", dnsAddr0:"1.1.1.1", dnsAddr1:"2.2.2.2"}).then(() => { + console.log("setIfaceConfig promiss ok "); +}).catch((error) => { + console.log("setIfaceConfig promiss error = " + error); +}); +``` + +## ethernet.getIfaceConfig + +getIfaceConfig(iface: string, callback: AsyncCallback\): void; + +Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------------- | ----- | ------------ | +| iface | string | Yes | Name of the network interface.| +| callback | AsyncCallback\<[InterfaceConfiguration](#interfaceconfiguration)> | Yes | Callback used to return the configuration. | + +**Example** + +```js +ethernet.getIfaceConfig("eth0", (error, value) => { + if (error) { + console.log("getIfaceConfig callback error = " + error); + } else { + console.log("getIfaceConfig callback mode = " + value.mode); + console.log("getIfaceConfig callback ipAddr = " + value.ipAddr); + console.log("getIfaceConfig callback routeAddr = " + value.routeAddr); + console.log("getIfaceConfig callback gateAddr = " + value.gateAddr); + console.log("getIfaceConfig callback maskAddr = " + value.maskAddr); + console.log("getIfaceConfig callback dns0Addr = " + value.dns0Addr); + console.log("getIfaceConfig callback dns1Addr = " + value.dns1Addr); + } +}); +``` + +## ethernet.getIfaceConfig + +getIfaceConfig(iface: string): Promise\; + +Obtains the configuration of a network interface. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ------------ | +| iface | string | Yes | Name of the network interface.| + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------------------------- | +| Promise\<[InterfaceConfiguration](#interfaceconfiguration)> | Promise used to return the configuration. | + +**Example** + +```js +ethernet.getIfaceConfig("eth0").then((data) => { + console.log("getIfaceConfig promiss mode = " + data.mode); + console.log("getIfaceConfig promiss ipAddr = " + data.ipAddr); + console.log("getIfaceConfig promiss routeAddr = " + data.routeAddr); + console.log("getIfaceConfig promiss gateAddr = " + data.gateAddr); + console.log("getIfaceConfig promiss maskAddr = " + data.maskAddr); + console.log("getIfaceConfig promiss dns0Addr = " + data.dns0Addr); + console.log("getIfaceConfig promiss dns1Addr = " + data.dns1Addr); +}).catch((error) => { + console.log("getIfaceConfig promiss error = " + error); +}); +``` + +## ethernet.isIfaceActive + +isIfaceActive(iface?: string, callback: AsyncCallback\): void; + +Checks whether a network interface is active. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------------------------------- | +| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| + +**Example** + +```js +ethernet.isIfaceActive("eth0", (error, value) => { + if (error) { + console.log("whether2Activate callback error = " + error); + } else { + console.log("whether2Activate callback = " + value); + } +}); +``` + +## ethernet.isIfaceActive + +isIfaceActive(iface?: string): Promise\; + +Checks whether a network interface is active. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| iface | string | No | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| + +**Return value** + +| Type | Description | +| ----------------| ------------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **1** means that the network interface is active, **0** means that the network interface is inactive, and any other value means that an error has occurred.| + +**Example** + +```js +ethernet.isIfaceActive("eth0").then((data) => { + console.log("isIfaceActive promiss = " + data); +}).catch((error) => { + console.log("isIfaceActive promiss error = " + error); +}); +``` + +## ethernet.getAllActiveIfaces + +getAllActiveIfaces(callback: AsyncCallback\>): void; + +Obtains all active network interfaces. This API uses an asynchronous callback to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return all the active network interface names obtained.| + +**Example** + +```js +ethernet.getAllActiveIfaces((error, value) => { + if (error) { + console.log("getAllActiveIfaces callback error = " + error); + } else { + console.log("getAllActiveIfaces callback value.length = " + value.length); + for (let i = 0; i < value.length; i++) { + console.log("getAllActiveIfaces callback = " + value[i]); + } + } +}); +``` + +## ethernet.getAllActiveIfaces + +getAllActiveIfaces(): Promise\>; + +Obtains all active network interfaces. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +**Return value** + +| Type | Description | +| ------------------------------ | ----------------------------------------------- | +| Promise\> | Promise used to return all the active network interface names obtained.| + +**Example** + +```js +ethernet.getAllActiveIfaces().then((data) => { + console.log("getAllActiveIfaces promiss data.length = " + data.length); + for (let i = 0; i < data.length; i++) { + console.log("getAllActiveIfaces promiss = " + data[i]); + } +}).catch((error) => { + console.log("getAllActiveIfaces promiss error = " + error); +}); +``` + +## InterfaceConfiguration + +Defines the network configuration for the Ethernet connection. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| mode | [IPSetMode](#ipsetmode) | Configuration mode of the Ethernet connection.| +| ipAddr | string | Static IP address of the Ethernet connection. The value must be an IPv4 address, which is a 32-bit number displayed in dotted decimal notation and each 8-bit field ranges from 0 to 255. This parameter does not need to be configured in Dynamic Host Configuration Protocol (DHCP) mode.| +| route | string | Route of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| gateway | string | Gateway of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| netMask | string | Subnet mask of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode.| +| dnsServers | string | DNS server addresses of the Ethernet connection. The value must be an IPv4 address. This parameter does not need to be configured in DHCP mode. Multiple addresses are separated by commas (,).| + +## IPSetMode + +Defines the configuration mode of the Ethernet connection. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| STATIC | 0 | Static configuration.| +| DHCP | 1 | Dynamic configuration.| diff --git a/en/application-dev/reference/apis/js-apis-net-policy.md b/en/application-dev/reference/apis/js-apis-net-policy.md new file mode 100644 index 0000000000000000000000000000000000000000..4537266a60faa11243140aee10a7f9d9a36bfa7b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-policy.md @@ -0,0 +1,1120 @@ +# Network Policy Management + +The Network Policy Management module provides APIs for managing network policies, through which you can control and manage the data volume used. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import policy from '@ohos.net.policy' +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean, callback: AsyncCallback\): void + +Sets a background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.setBackgroundPolicy + +setBackgroundPolicy(isAllowed: boolean): Promise\ + +Sets a background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| isAllowed | boolean | Yes | Whether applications running in the background are allowed to use mobile data.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicy + +getBackgroundPolicy(callback: AsyncCallback\): void; + +Obtains the background network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If **true** is returned, applications running in the background are allowed to use mobile data.| + +**Example** + +```js +policy.getBackgroundPolicy((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}); +``` + +## policy.getBackgroundPolicy + +getBackgroundPolicy(): Promise\; + +Obtains the background network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.getBackgroundPolicy().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy, callback: AsyncCallback\): void; + +Sets an application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setPolicyByUid + +setPolicyByUid(uid: number, policy: NetUidPolicy): Promise\; + +Sets an application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Unique ID of the application.| +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Application-specific network policy to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy) +} +policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number, callback: AsyncCallback\): void; + +Obtains an application-specific network policy by **uid**. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetUidPolicy](#netuidpolicy)> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getPolicyByUid + +getPolicyByUid(uid: number): Promise\; + +Obtains an application-specific network policy by **uid**. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetUidPolicy](#netuidpolicy)> | Promise used to return the result.| + +**Example** + +```js +policy.getPolicyByUid(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getUidsByPolicy + +getUidsByPolicy(policy: NetUidPolicy, callback: AsyncCallback\>): void; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.currentNetUidPolicy), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getUidsByPolicy + +function getUidsByPolicy(policy: NetUidPolicy): Promise\>; + +Obtains the UID array of applications configured with a certain application-specific network policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| policy | [NetUidPolicy](#netuidpolicy) | Yes| Target application-specific network policy.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(callback: AsyncCallback\>): void; + +Obtains the network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getNetQuotaPolicies((err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getNetQuotaPolicies + +getNetQuotaPolicies(): Promise\>; + +Obtains the network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getNetQuotaPolicies().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\, callback: AsyncCallback\): void; + +Sets an array of network quota policies. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setNetQuotaPolicies + +setNetQuotaPolicies(quotaPolicies: Array\): Promise\; + +Sets an array of network quota policies. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| quotaPolicies | Array\<[NetQuotaPolicy](#netquotapolicy)> | Yes| An array of network quota policies to set.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes), + limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction}; +this.netQuotaPolicyList.push(param); + +policy.setNetQuotaPolicies(this.netQuotaPolicyList).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string, callback: AsyncCallback\): void; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.restoreAllPolicies + +restoreAllPolicies(iccid: string): Promise\; + +Restores all the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +this.firstParam = iccid; +policy.restoreAllPolicies(this.firstParam).then((err, data){ + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean, callback: AsyncCallback\): void; + +Checks whether an application is allowed to access metered networks. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access metered networks, and **false** means the opposite.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, isMetered: boolean): Promise\; + +Checks whether an application is allowed to access metered networks. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isMetered | boolean | Yes| Whether the network is a metered network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean)) +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string, callback: AsyncCallback\): void; + +Checks whether an application is allowed to access the given network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the application is allowed to access the given network, and **false** means the opposite.| + +**Example** + +```js + +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.isUidNetAllowed + +isUidNetAllowed(uid: number, iface: string): Promise\; + +Checks whether an application is allowed to access the given network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| iface | string | Yes| Name of the target network.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), iface: this.secondParam +} +policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.setDeviceIdleAllowlist + +setDeviceIdleAllowList(uid: number, isAllowed: boolean, callback: AsyncCallback\): void; + +Sets whether to add an application to the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| +| callback | callback: AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean)), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.setDeviceIdleAllowlist + +setDeviceIdleAllowList(uid: number, isAllowed: boolean): Promise\; + +Sets whether to add an application to the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| isAllowed | boolean | Yes| Whether to add the application to the allowlist.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean)) +} +policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.getDeviceIdleAllowlist + +getDeviceIdleAllowList(callback: AsyncCallback\>): void; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.getDeviceIdleAllowList((err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getDeviceIdleAllowlist + +getDeviceIdleAllowList(): Promise\>; + +Obtains the UID array of applications that are on the device idle allowlist. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +policy.getDeviceIdleAllowList().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number, callback: AsyncCallback\): void; + +Obtains the background network policies configured for the given application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| +| callback | AsyncCallback\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.getBackgroundPolicyByUid + +getBackgroundPolicyByUid(uid: number): Promise\; + +Obtains the background network policies configured for the given application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes| Unique ID of the application.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[NetBackgroundPolicy](#netbackgroundpolicy)> | Promise used to return the result.| + +**Example** + +```js +this.firstParam = uid +policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## policy.resetPolicies + +resetPolicies(iccid: string, callback: AsyncCallback\): void; + +Resets the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +this.firstParam = iccid +policy.resetPolicies(this.firstParam, (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.resetPolicies + +resetPolicies(iccid: string): Promise\; + +Resets the policies (cellular network, background network, firewall, and application-specific network policies) for the given SIM card. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| iccid | string | Yes| SIM card ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then((err, data) { + +}) +this.firstParam = iccid +policy.resetPolicies(this.firstParam).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType, callback: AsyncCallback\): void; + +Updates a reminder policy. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType), (err, data) => { + this.callBack(err, data); +}); +``` + +## policy.updateRemindPolicy + +updateRemindPolicy(netType: NetBearType, iccid: string, remindType: RemindType): Promise\; + +Updates a reminder policy. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Yes| Network type.| +| iccid | string | Yes| SIM card ID.| +| remindType | [RemindType](#remindtype) | Yes| Reminder type.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let param = { + netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType +} +policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) + +``` + +## policy.on + +Functions as the handle to a network policy. + +### on('netUidPolicyChange') + +on(type: "netUidPolicyChange", callback: Callback\<{ uid: number, policy: NetUidPolicy }>): void; + +Subscribes to policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidPolicyChange | Yes| Event type. The value **netUidPolicyChange** indicates a policy change event.| +| callback | Callback\<{ uid: number, policy: [NetUidPolicy](#netuidpolicy) }> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netUidPolicyChange', (data) => { + this.log('on netUidPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netUidRuleChange') + +on(type: "netUidRuleChange", callback: Callback\<{ uid: number, rule: NetUidRule }>): void; + +Subscribes to rule changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netUidRuleChange | Yes| Event type. The value **netUidRuleChange** indicates a rule change event.| +| callback | Callback\<{ uid: number, rule: [NetUidRule](#netuidrule) }> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netUidRuleChange', (data) => { + this.log('on netUidRuleChange: ' + JSON.stringify(data)); +}) +``` + +### on('netMeteredIfacesChange') + +on(type: "netMeteredIfacesChange", callback: Callback\>): void; + +Subscribes to metered network name (specified by **iface**) changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netMeteredIfacesChange | Yes| Event type. The value **netMeteredIfacesChange** indicates a metered network name change event.| +| callback | Callback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netMeteredIfacesChange', (data) => { + this.log('on netMeteredIfacesChange: ' + JSON.stringify(data)); +}) +``` + +### on('netQuotaPolicyChange') + +on(type: "netQuotaPolicyChange", callback: Callback\>): void; + +Subscribes to network quota policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netQuotaPolicyChange | Yes| Event type. The value **netQuotaPolicyChange** indicates a network quota policy change event.| +| callback | Callback\> | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netQuotaPolicyChange', (data) => { + this.log('on netQuotaPolicyChange: ' + JSON.stringify(data)); +}) +``` + +### on('netBackgroundPolicyChange') + +on(type: "netBackgroundPolicyChange", callback: Callback\): void; + +Subscribes to background network policy changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------------ | +| type | netBackgroundPolicyChange | Yes| Event type. The value **netBackgroundPolicyChange** indicates a background network policy change event.| +| callback | Callback\ | Yes | Callback used to return the result.| + +**Example** + +```js +policy.on('netBackgroundPolicyChange', (data) => { + this.log('on netBackgroundPolicyChange: ' + JSON.stringify(data)); +}) +``` + +## NetBackgroundPolicy + +Enumerates the background network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| NET_BACKGROUND_POLICY_NONE | 0 | Default policy.| +| NET_BACKGROUND_POLICY_ENABLE | 1 | Applications running in the background are allowed to access metered networks.| +| NET_BACKGROUND_POLICY_DISABLE | 2 | Applications running in the background are not allowed to access metered networks.| +| NET_BACKGROUND_POLICY_ALLOW_LIST | 3 | Only applications on the device idle allowlist are allowed to access metered networks when they are running in the background.| + +## NetQuotaPolicy + +Defines a network quota policy. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | +| netType | [NetBearType](js-apis-net-connection.md#netbeartype) | Network type.| +| iccid | string | Identifier of the SIM card on the metered cellular network. It is not used for Wi-Fi networks.| +| ident | string | Identifier of the SIM card on the metered cellular network. It is used for Wi-Fi networks. It is used together with **iccid**.| +| periodDuration | string | Start time of metering.| +| warningBytes | number | Data volume threshold for generating an alarm.| +| limitBytes | number | Data volume quota.| +| lastWarningRemind | string | Last time when an alarm was generated.| +| lastLimitRemind | string | Last time when the quota was exhausted.| +| metered | string | Whether the network is a metered network.| +| limitAction | [LimitAction](#limitaction) | Action to take when the data volume quota is reached.| + +## LimitAction + +Enumerates the actions that can be taken when the data volume quota is reached. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| LIMIT_ACTION_NONE | -1 | Default action.| +| LIMIT_ACTION_DISABLE | 0 | Internet access is disabled.| +| LIMIT_ACTION_AUTO_BILL| 1 | Users will be automatically charged for the data volume they use.| + +## NetUidRule + +Enumerates the metered network rules. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_RULE_NONE | 0 | Default rule.| +| NET_RULE_ALLOW_METERED_FOREGROUND | 1 | Applications running in the foreground are allowed to access metered networks.| +| NET_RULE_ALLOW_METERED | 2 | Applications are allowed to access metered networks.| +| NET_RULE_REJECT_METERED | 4 | Applications are not allowed to access metered networks.| +| NET_RULE_ALLOW_ALL | 32 | Applications are allowed to access all networks (metered or non-metered).| +| NET_RULE_REJECT_ALL | 64 | Applications are not allowed to access any networks (metered or non-metered).| + +## RemindType + +Enumerates the reminder types. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | - | ------- | +| REMIND_TYPE_WARNING | 1 | Warning.| +| REMIND_TYPE_LIMIT | 2 | Limit.| + +## NetUidPolicy + +Enumerates the application-specific network policies. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value| Description | +| ---------------------- | ----- | ------------ | +| NET_POLICY_NONE | 0 | Default network policy.| +| NET_POLICY_ALLOW_METERED_BACKGROUND | 1 | Applications running in the background are allowed to access metered networks.| +| NET_POLICY_REJECT_METERED_BACKGROUND | 2 | Applications running in the background are not allowed to access metered networks.| diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md new file mode 100644 index 0000000000000000000000000000000000000000..23284aeb1715a3f8aed9ec7b2d79ad55d1408319 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -0,0 +1,746 @@ +# Network Sharing Management + +The Network Sharing Management module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import sharing from '@ohos.net.sharing' +``` + +## sharing.isSharingSupported + +isSharingSupported(callback: AsyncCallback\): void + +Checks whether network sharing is supported. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharingSupported((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.isSharingSupported + +isSharingSupported(): Promise\ + +Checks whether network sharing is supported. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that network sharing is supported, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharingSupported().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.isSharing + +isSharing(callback: AsyncCallback\): void + +Checks whether network sharing is in progress. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharing((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.isSharing + +isSharing(): Promise\ + +Checks whether network sharing is in progress. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that network sharing is in progress, and **false** means the opposite.| + +**Example** + +```js +sharing.isSharing().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.startSharing + +startSharing(type: SharingIfaceType, callback: AsyncCallback\): void + +Starts network sharing of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.startSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.startSharing + +startSharing(type: SharingIfaceType): Promise\ + +Starts network sharing of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.startSharing(SharingIfaceType.SHARING_WIFI).then(() => { + console.log("start wifi sharing successful"); +}).catch(error => { + console.log("start wifi sharing failed"); +}); +``` + +## sharing.stopSharing + +stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void + +Stops network sharing of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.stopSharing(SharingIfaceType.SHARING_WIFI, (error) => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.stopSharing + +stopSharing(type: SharingIfaceType): Promise\ + +Stops network sharing of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.stopSharing(SharingIfaceType.SHARING_WIFI).then(() => { + console.log("stop wifi sharing successful"); +}).catch(error => { + console.log("stop wifi sharing failed"); +}); +``` + +## sharing.getStatsRxBytes + +getStatsRxBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic received via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsRxBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsRxBytes + +getStatsRxBytes(): Promise\ + +Obtains the volume of mobile data traffic received via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsRxBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getStatsTxBytes + +getStatsTxBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTxBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsTxBytes + +getStatsTxBytes(): Promise\ + +Obtains the volume of mobile data traffic sent via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTxBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getStatsTotalBytes + +getStatsTotalBytes(callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent and received via network sharing. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTotalBytes((error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getStatsTotalBytes + +getStatsTotalBytes(): Promise\ + +Obtains the volume of mobile data traffic sent and received via network sharing. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in KB.| + +**Example** + +```js +sharing.getStatsTotalBytes().then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharingIfaces + +getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\>): void + +Obtains the names of NICs in the specified network sharing state. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of NIC names.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharingIfaces + +getSharingIfaces(state: SharingIfaceState): Promise\> + +Obtains the names of NICs in the specified network sharing state. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return an array of NIC names.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharingState + +getSharingState(type: SharingIfaceType, callback: AsyncCallback\): void + +Obtains the network sharing state of the specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\<[SharingIfaceState](#sharingifacestate)> | Yes | Callback used to return the network sharing state.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharingState + +getSharingState(type: SharingIfaceType): Promise\ + +Obtains the network sharing state of the specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\<[SharingIfaceState](#sharingifacestate)> | Promise used to return the network sharing state.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharingIfaces(SharingIfaceType.SHARING_WIFI).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## sharing.getSharableRegexes + +getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\>): void + +Obtains regular expressions of NICs of a specified type. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| +| callback | AsyncCallback\> | Yes | Callback used to return an array of regular expressions.| + +**Example** + +```js +import SharingIfaceState from '@ohos.net.sharing' +sharing.getSharingState(SharingIfaceType.SHARING_WIFI, (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## sharing.getSharableRegexes + +getSharableRegexes(type: SharingIfaceType): Promise\> + +Obtains regular expressions of NICs of a specified type. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | [SharingIfaceType](#sharingifacetype) | Yes | Sharing type. The value **0** means Wi-Fi hotspot sharing, **1** means USB sharing, and **2** means Bluetooth sharing.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return an array of regular expressions.| + +**Example** + +```js +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { + console.log(JSON.stringify(data)); +}).catch(error => { + console.log(JSON.stringify(error)); +}); +``` + +## on('sharingStateChange') + +on(type: 'sharingStateChange', callback: Callback\): void + +Subscribes to network sharing state changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | Yes | Callback used to return the network sharing state.| + +**Example** + +```js +sharing.on('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('sharingStateChange') + +off(type: 'sharingStateChange', callback?: Callback\): void + +Unsubscribes from network sharing state changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('sharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## on('interfaceSharingStateChange') + +on(type: 'interfaceSharingStateChange', callback: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void + +Subscribes to network sharing state changes of a specified NIC. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | Yes | Callback invoked when the network sharing state of the specified NIC changes.| + +**Example** + +```js +sharing.on('interfaceSharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('interfaceSharingStateChange') + +off(type: 'interfaceSharingStateChange', callback?: Callback\<{ type: SharingIfaceType, iface: string, state: SharingIfaceState }>): void + +Unsubscribes from network sharing status changes of a specified NIC. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | No | Event name.| +| callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('interfaceSharingStateChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## on('sharingUpstreamChange') + +on(type: 'sharingUpstreamChange', callback: Callback\): void + +Subscribes to upstream network changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | Yes | Callback invoked when the upstream network changes.| + +**Example** + +```js +sharing.on('sharingUpstreamChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## off('sharingUpstreamChange') + +off(type: 'sharingUpstreamChange', callback?: Callback\): void + +Unsubscribes from upstream network changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| type | string | Yes | Event name.| +| callback | AsyncCallback\ | No | Callback used for unsubscription.| + +**Example** + +```js +sharing.off('sharingUpstreamChange', (error, data) => { + console.log(JSON.stringify(error)); + console.log(JSON.stringify(data)); +}); +``` + +## SharingIfaceState + +Enumerates the network sharing states of an NIC. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| SHARING_NIC_SERVING | 1 | Network sharing is in progress.| +| SHARING_NIC_CAN_SERVER | 2 | Network sharing is supported.| +| SHARING_NIC_ERROR | 3 | An error occurred during network sharing.| + +## SharingIfaceType + +Enumerates the network sharing types of an NIC. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | ---------------------- | +| SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| +| SHARING_USB | 1 | USB sharing.| +| SHARING_BLUETOOTH | 2 | Bluetooth sharing.| diff --git a/en/application-dev/reference/apis/js-apis-net-statistics.md b/en/application-dev/reference/apis/js-apis-net-statistics.md new file mode 100644 index 0000000000000000000000000000000000000000..37d470deb661f185c4d87aa0259d67f38324651e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-net-statistics.md @@ -0,0 +1,409 @@ +# Network Traffic Management + +The Network Traffic Management module collects statistics on the mobile data traffic and allows you to query the data volume by network interface (cellular or Wi-Fi) or application. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import statistics from '@ohos.net.statistics' +``` + +## statistics.getIfaceRxBytes + +getIfaceRxBytes(nic: string, callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic received by a specified NIC. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceRxBytes(this.nic, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceRxBytes + +getIfaceRxBytes(nic: string): Promise\; + +Obtains the volume of mobile data traffic received by a specified NIC. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceRxBytes(this.nic).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceTxBytes + +getIfaceTxBytes(nic: string, callback: AsyncCallback\): void + +Obtains the volume of mobile data traffic sent by a specified NIC. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceTxBytes(this.nic, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getIfaceTxBytes + +getIfaceTxBytes(nic: string): Promise\; + +Obtains the volume of mobile data traffic sent by a specified NIC. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| nic | string | Yes | NIC name.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getIfaceTxBytes(this.nic).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularRxBytes + +getCellularRxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by the cellular network. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularRxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularRxBytes + +getCellularRxBytes(): Promise\; + +Obtains the volume of mobile data traffic received by the cellular network. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularRxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularTxBytes + +getCellularTxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by the cellular network. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularTxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getCellularTxBytes + +getCellularTxBytes(): Promise\; + +Obtains the volume of mobile data traffic sent by the cellular network. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getCellularTxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllRxBytes + +getAllRxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by all NICs. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllRxBytes(err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllRxBytes + +getAllRxBytes(): Promise\; + +Obtains the volume of mobile data traffic received by all NICs. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllRxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllTxBytes + +getAllTxBytes(callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by all NICs. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllTxBytes((err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getAllTxBytes + +getAllTxBytes(): Promise\; + +Obtains the volume of mobile data traffic sent by all NICs. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getAllTxBytes().then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidRxBytes + +getUidRxBytes(uid: number, callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic received by a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidRxBytes(this.uid, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidRxBytes + +getUidRxBytes(uid: number): Promise\; + +Obtains the volume of mobile data traffic received by a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidRxBytes(this.uid).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidTxBytes + +getUidTxBytes(uid: number, callback: AsyncCallback\): void; + +Obtains the volume of mobile data traffic sent by a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidTxBytes(this.uid, (err, data) => { + this.callBack(err, data); + console.log(JSON.stringify(error)) + console.log(JSON.stringify(data)) +}) +``` + +## statistics.getUidTxBytes + +getUidTxBytes(uid: number): Promise\; + +Obtains the volume of mobile data traffic sent by a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetManager.Core + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| uid | number | Yes | Application ID.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the data volume, in bytes.| + +**Example** + +```js +statistics.getUidTxBytes(this.uid).then((err, data) { + console.log(JSON.stringify(err)) + console.log(JSON.stringify(data)) +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-nfcController.md b/en/application-dev/reference/apis/js-apis-nfcController.md index c8a9d7cf699963e494c5f04c1d5e887e8795eb0f..105af3cf95ca3a052faddbb6fe632940169fbcd1 100644 --- a/en/application-dev/reference/apis/js-apis-nfcController.md +++ b/en/application-dev/reference/apis/js-apis-nfcController.md @@ -1,6 +1,6 @@ # Standard NFC -The **nfcController** module implements Near-Field Communication (NFC). +The **nfcController** module provides APIs for opening and closing Near-Field Communication (NFC) and reading the NFC state. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,12 +12,24 @@ The **nfcController** module implements Near-Field Communication (NFC). import controller from '@ohos.nfc.controller'; ``` +## NfcState + +Enumerates the NFC states. + +**System capability**: SystemCapability.Communication.NFC.Core + +| Name| Default Value| Description| +| -------- | -------- | -------- | +| STATE_OFF | 1 | NFC is closed (OFF).| +| STATE_TURNING_ON | 2 | NFC is turning on.| +| STATE_ON | 3 | NFC is open (ON).| +| STATE_TURNING_OFF | 4 | NFC is turning off.| ## controller.isNfcAvailable isNfcAvailable(): boolean -Checks whether NFC is available. +Checks whether the device supports NFC. **System capability**: SystemCapability.Communication.NFC.Core @@ -25,7 +37,7 @@ Checks whether NFC is available. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if NFC is available; returns **false** otherwise.| +| boolean | Returns **true** if the device supports NFC; returns **false** otherwise.| ## controller.openNfc @@ -42,7 +54,7 @@ Opens NFC. | **Type**| **Description**| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## controller.closeNfc @@ -76,7 +88,7 @@ Checks whether NFC is open. ## controller.getNfcState -getNfcState(): NfcState +getNfcState(): [NfcState](#nfcstate) Obtains the NFC state. @@ -86,13 +98,13 @@ Obtains the NFC state. | **Type**| **Description** | | -------- | ---------------------- | -| NfcState | NFC state obtained. For details, see [NfcState](#nfcstate).| +| [NfcState](#nfcstate) | NFC state obtained. For details, see [NfcState](#nfcstate).| ## controller.on('nfcStateChange') -on(type: "nfcStateChange", callback: Callback<NfcState>): void +on(type: "nfcStateChange", callback: Callback<[NfcState](#nfcstate)>): void -Subscribes to NFC state changes. +Subscribes to NFC state changes. A callback will be invoked to return the NFC state when the NFC state changes. **System capability**: SystemCapability.Communication.NFC.Core @@ -101,15 +113,15 @@ Subscribes to NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to subscribe to. The value is **nfcStateChange**.| - | callback | Callback<NfcState> | Yes| Callback invoked to return the NFC state changes.| + | callback | Callback<[NfcState](#nfcstate)> | Yes| Callback invoked to return the NFC state.| ## controller.off('nfcStateChange') -off(type: "nfcStateChange", callback?: Callback<NfcState>): void +off(type: "nfcStateChange", callback?: Callback<[NfcState](#nfcstate)>): void -Unsubscribes from the NFC state changes. +Unsubscribes from the NFC state changes. The subscriber will not receive NFC state change notifications. **System capability**: SystemCapability.Communication.NFC.Core @@ -118,35 +130,37 @@ Unsubscribes from the NFC state changes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type to unsubscribe from. The value is **nfcStateChange**.| -| callback | Callback<NfcState> | No| Callback used to return the NFC state changes. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| +| callback | Callback<[NfcState](#nfcstate)> | No| Callback for the NFC state changes. This parameter can be left blank.| **Example** ```js - import nfcController from '@ohos.nfcController'; - - var NFC_STATE_NOTIFY = "nfcStateChange"; - - var recvNfcStateNotifyFunc = result => { - console.info("nfc state receive state: " + result); + import controller from '@ohos.nfc.controller'; + + // Define a callback key. + var NFC_STATE_CALLBACK_KEY = "nfcStateChange"; + + // Register the callback to receive NFC state change notifications. + controller.on(NFC_STATE_CALLBACK_KEY, (err, nfcState)=> { + if (err) { + console.log("controller on callback err: " + err); + } else { + console.log("controller on callback nfcState: " + nfcState); + } + }); + + // Open NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (!controller.isNfcOpen()) { + var ret = controller.openNfc(); + console.log("controller openNfc ret: " + ret); } - - // Subscribe to the NFC state changes. - nfcController.on(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - - // Unsubscribe from the NFC state changes. - nfcController.off(NFC_STATE_NOTIFY, recvNfcStateNotifyFunc); - ``` - -## NfcState - -Enumerates the NFC states. -**System capability**: SystemCapability.Communication.NFC.Core + // Close NFC. Require permission: ohos.permission.MANAGE_SECURE_SETTINGS. + if (controller.isNfcOpen()) { + var ret = controller.closeNfc(); + console.log("controller closeNfc ret: " + ret); + } -| Name| Default Value| Description| -| -------- | -------- | -------- | -| STATE_OFF | 1 | Off| -| STATE_TURNING_ON | 2 | Turning on| -| STATE_ON | 3 | On| -| STATE_TURNING_OFF | 4 | Turning off| + // Unregister the callback. + controller.off(NFC_STATE_CALLBACK_KEY); + ``` diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 5941d465a085a425ef7d10cb28d5fe4b621bc0b2..2f3a208fe1f95b2c4f936709d047fa4c9581f8b6 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,19 +1,100 @@ # NFC Tags -The **nfcTag** module provides methods for managing Near-Field Communication (NFC) tags. +The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. > **NOTE**
> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +## **Declaration** + +Before developing applications related to tag read and write, you must declare NFC-related attributes in the attribute configuration file of the applications. For example, declare the following attributes in the **module.json5** file: +```js +{ + "module": { + // Attributes to declare. + + "abilities": [ + { + "skills": [ + { + "actions": [ + // Actions to declare. + + // Add the nfc tag action. + "ohos.nfc.tag.action.TAG_FOUND" + ] + } + ], + "metadata": [ + { + "name": "tag-tech", + "value": "NfcA" + }, + { + "name": "tag-tech", + "value": "IsoDep" + }, + // Add other technologies, + // such as NfcB, NfcF, NfcV, Ndef, MifareClassic, MifareUL, and NdefFormatable. + ] + } + ], + "requestPermissions": [ + "name": "ohos.permission.NFC_TAG", + "reason": "tag", + ] + } +} +``` +> **CAUTION**
+> +> - The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. +> - The **name** field of **metadata** is mandatory. It must be **tag-tech** and cannot be changed. +> - The **value** field of **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or their combinations. Incorrect setting of this field will cause a parsing failure. +> - The **name** field of **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. + + ## **Modules to Import** ```js import tag from '@ohos.nfc.tag'; ``` +## **tag.TagInfo** +Before reading or writing data to a card with tags, the application must obtain **TagInfo** to determine the tag technologies supported by the card. Then, the application can invoke the correct API to communicate with the card. +```js +import tag from '@ohos.nfc.tag'; + +onCreate(want, launchParam) { + // Add other code here. + + // want is initialized by the NFC service and contains taginfo. + var tagInfo = tag.getTagInfo(want); + if (tagInfo == undefined) { + console.log("no TagInfo to be created, ignore it."); + return; + } + var isNfcATag = false; + for (var i = 0; i < tagInfo.technology.length; i++) { + if (tagInfo.technology[i] == tag.NFC_A) { + isNfcATag = true; + break; + } + // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. + } + if (isNfcATag) { + var nfcA = tag.getNfcATag(taginfo); + // Other code to read or write this tag. + } + + // use the same code to handle "NfcA/NfcB/NfcF/NfcV/IsoDep/Ndef/MifareClassic/MifareUL/NdefFormatable", such as, + // var isoDep = tag.getIsoDepTag(taginfo); +} +``` + ## tag.getNfcATag -getNfcATag(tagInfo: [TagInfo](#taginfo9)): [NfcATag](js-apis-nfctech.md#nfcatag) +getNfcATag(tagInfo: [TagInfo](#taginfo)): [NfcATag](js-apis-nfctech.md#nfcatag) Obtains an **NfcATag** object, which allows access to the tags that use the NFC-A technology. @@ -29,7 +110,7 @@ Obtains an **NfcATag** object, which allows access to the tags that use the NFC- ## tag.getNfcBTag -getNfcBTag(tagInfo: [TagInfo](#taginfo9)): [NfcBTag](js-apis-nfctech.md#nfcbtag) +getNfcBTag(tagInfo: [TagInfo](#taginfo)): [NfcBTag](js-apis-nfctech.md#nfcbtag) Obtains an **NfcBTag** object, which allows access to the tags that use the NFC-B technology. @@ -45,7 +126,7 @@ Obtains an **NfcBTag** object, which allows access to the tags that use the NFC- ## tag.getNfcFTag -getNfcFTag(tagInfo: [TagInfo](#taginfo9)): [NfcFTag](js-apis-nfctech.md#nfcftag) +getNfcFTag(tagInfo: [TagInfo](#taginfo)): [NfcFTag](js-apis-nfctech.md#nfcftag) Obtains an **NfcFTag** object, which allows access to the tags that use the NFC-F technology. @@ -61,7 +142,7 @@ Obtains an **NfcFTag** object, which allows access to the tags that use the NFC- ## tag.getNfcVTag -getNfcVTag(tagInfo: [TagInfo](#taginfo9)): [NfcVTag](js-apis-nfctech.md#nfcvtag) +getNfcVTag(tagInfo: [TagInfo](#taginfo)): [NfcVTag](js-apis-nfctech.md#nfcvtag) Obtains an **NfcVTag** object, which allows access to the tags that use the NFC-V technology. @@ -77,11 +158,10 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- ## tag.getIsoDepTag9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo9)): [IsoDepTag](js-apis-nfctech.md#isodeptag9 ) +getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) Obtains an **IsoDepTag** object, which allows access to the tags that use the ISO-DEP technology. - **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.NFC.Core @@ -94,7 +174,7 @@ Obtains an **IsoDepTag** object, which allows access to the tags that use the IS ## tag.getNdefTag9+ -getNdefTag(tagInfo: [TagInfo](#taginfo9)): [NdefTag](js-apis-nfctech.md#ndeftag9) +getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). @@ -111,7 +191,7 @@ Obtains an **NdefTag** object, which allows access to the tags in the NFC Data E ## tag.getMifareClassicTag9+ -getMifareClassicTag(tagInfo: [TagInfo](#taginfo9)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. @@ -127,7 +207,7 @@ Obtains a **MifareClassicTag** object, which allows access to the tags that use ## tag.getMifareUltralightTag9+ -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo9)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. @@ -143,7 +223,7 @@ Obtains a **MifareUltralightTag** object, which allows access to the tags that u ## tag.getNdefFormatableTag9+ -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo9)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. @@ -157,15 +237,143 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar | ------------------ | --------------------------| | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.| -## TagInfo9+ +## tag.getTagInfo9+ + +getTagInfo(want: Want): [TagInfo](#taginfo) + +Obtains **TagInfo** from **Want**, which is initialized by the NFC service and contains the attributes required by **TagInfo**. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [TagInfo](#taginfo) | **TagInfo** object obtained.| + +## TagInfo + +Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. -Represents the NFC tag information. +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core | **Name**| **Type**| **Description**| | -------- | -------- | -------- | -| uid | string | UID of the tag.| -| technology | number[] | Technology supported by the tag.| -| extrasData | PacMap[] | Additional information about the tag.| -| tagRfDiscId | number | RF discovery ID of the tag.| -| remoteTagService | rpc.RemoteObject | RPC remote object of the tag service.| -| supportedProfiles | number[] | Profiles supported by the tag.| +| uid9+ | number[] | Tag unique identifier (UID). Each number of the UID is a hexadecimal number ranging from **0x00** to **0xFF**.| +| technology9+ | number[] | Supported technologies. Each number is a constant indicating the supported technology.| +| supportedProfiles | number[] | Supported technologies. This parameter is not supported since API version 9 and is replaced by **technology**.| + +## NdefRecord9+ +Defines an NDEF tag record. For details, see *NFCForum-TS-NDEF_1.0*. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Type**| **Description**| +| -------- | -------- | -------- | +| tnf | number | Type name field (TNF) of an NDEF record.| +| rtdType| number[] | Record type definition (RTD) of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| +| id | number[] | ID of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| +| payload | number[] | Payload of an NDEF record. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| + +## Technology Type Definition +Enumerates the tag technology types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| NFC_A | 1 | NFC-A (ISO 14443-3A).| +| NFC_B | 2 | NFC-A (ISO 14443-3B).| +| ISO_DEP | 3 | ISO-DEP (ISO 14443-4).| +| NFC_F | 4 | NFC-F (JIS 6319-4).| +| NFC_V | 5 | NFC-V (ISO 15693).| +| NDEF | 6 | NDEF.| +| MIFARE_CLASSIC | 8 | MIFARE Classic.| +| MIFARE_ULTRALIGHT | 9 | MIFARE Ultralight.| +| NDEF_FORMATABLE9+ | 10 | NDEF formattable.| + +## TnfType9+ +Enumerates the TNF types. For details, see *NFCForum-TS-NDEF_1.0*. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TNF_EMPTY | 0x0 | Empty.| +| TNF_WELL_KNOWN | 0x01 | NFC Forum Well Known Type [NFC RTD].| +| TNF_MEDIA | 0x02 | Media-type as defined in RFC 2046 [RFC 2046].| +| TNF_ABSOLUTE_URI | 0x03 | Absolute URI as defined in RFC 3986 [RFC 3986].| +| TNF_EXT_APP | 0x04 | NFC Forum external type [NFC RTD].| +| TNF_UNKNOWN | 0x05 | Unknown.| +| TNF_UNCHANGED | 0x06 | Unchanged (see section 2.3.3).| + +## NDEF Record RTD +Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-NDEF_1.0*. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| RTD_TEXT9+ | [0x54] | NDEF record of the text type.| +| RTD_URI9+ | [0x55] | NDEF record of the URI type.| + +## NfcForumType9+ +Enumerates the NFC Forum tag types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| NFC_FORUM_TYPE_1 | 1 | NFC Forum tag type 1.| +| NFC_FORUM_TYPE_2 | 2 | NFC Forum tag type 2.| +| NFC_FORUM_TYPE_3 | 3 | NFC Forum tag type 3.| +| NFC_FORUM_TYPE_4 | 4 | NFC Forum tag type 4.| +| MIFARE_CLASSIC | 101 | MIFARE Classic type.| + +## MifareClassicType9+ +Enumerates the MIFARE Classic tag types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKNOWN | -1 | Unknown type.| +| TYPE_CLASSIC | 0 | MIFARE Classic.| +| TYPE_PLUS | 1 | MIFARE Plus.| +| TYPE_PRO | 2 | MIFARE Pro.| + +## MifareClassicSize9+ +Enumerates the storage sizes of MIFARE Classic tags. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| +| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.| +| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| +| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| + +### MifareUltralightType9+ +Enumerates the MIFARE Ultralight tag types. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| TYPE_UNKOWN | -1 | Unknown type.| +| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| +| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| + diff --git a/en/application-dev/reference/apis/js-apis-nfctech.md b/en/application-dev/reference/apis/js-apis-nfctech.md index d471510aeec29a3fce389284a54866a55b1ca507..9817e5fd5c1f2a7f797f2c20fa7b6eff18dc25a5 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -33,16 +33,17 @@ Obtains the SAK value of this NFC-A tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | SAK value obtained.| +| number | SAK value obtained. The SAK is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let sak = tag.getNfcATag(taginfo).getSak(); -console.log("sak:" +sak); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. + +let sak = nfcA.getSak(); +console.log("nfcA sak: " + sak); ``` ### NfcATag.getAtqa @@ -59,16 +60,16 @@ Obtains the ATQA value of this NFC-A tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | ATQA value obtained.| +| number[] | ATQA value obtained. Each number of the ATQA is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let atqa = tag.getNfcATag(taginfo).getAtqa(); -console.log("atqa:" +atqa); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. +let atqa = nfcA.getAtqa(); +console.log("nfcA atqa: " + atqa); ``` ## NfcBTag @@ -93,16 +94,16 @@ Obtains the application data of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Application data obtained.| +| number[] | Application data obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let appData = tag.getNfcBTag(taginfo).getRespAppData(); -console.log("appData:" +appData); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +let respAppData = nfcB.getRespAppData(); +console.log("nfcB respAppData: " + respAppData); ``` ### NfcBTag.getRespProtocol @@ -119,16 +120,16 @@ Obtains the protocol information of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Protocol information obtained.| +| number[] | Protocol information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let protocol = tag.getNfcBTag(taginfo).getRespProtocol(); -console.log("appData:" +protocol); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +let respProtocol = nfcB.getRespProtocol(); +console.log("nfcB respProtocol: " + respProtocol); ``` ## NfcFTag @@ -153,16 +154,16 @@ Obtains the system code from this NFC-F tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | System code obtained.| +| number[] | System code obtained. Each number in the system code is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let systemCode = tag.getNfcFTag(taginfo).getSystemCode(); -console.log("systemCode:" +systemCode); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +let systemCode = nfcF.getSystemCode(); +console.log("nfcF systemCode: " + systemCode); ``` ### NfcFTag.getPmm @@ -179,16 +180,16 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | PMm information obtained.| +| number[] | PMm information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let pmm = tag.getNfcFTag(taginfo).getPmm(); -console.log("pmm:" +pmm); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +let pmm = nfcF.getPmm(); +console.log("nfcF pmm: " + pmm); ``` ## NfcVTag @@ -213,16 +214,16 @@ Obtains the response flags from this NFC-V tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | Response flags obtained.| +| number | Response flags obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let flags = tag.getNfcVTag(taginfo).getResponseFlags(); -console.log("flags:" +flags); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +let responseFlags = nfcV.getResponseFlags(); +console.log("nfcV responseFlags: " + responseFlags); ``` ### NfcvTag.getDsfId @@ -239,16 +240,16 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | DSFID obtained.| +| number | DSFID obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let dsfId = tag.getNfcVTag(taginfo).getDsfId(); -console.log("dsfId:" +dsfId); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +let dsfId = nfcV.getDsfId(); +console.log("nfcV dsfId: " + dsfId); ``` ## IsoDepTag9+ @@ -261,7 +262,7 @@ The following describes the unique interfaces of **IsoDepTag**. ### IsoDepTag.getHistoricalBytes9+ -getHistoricalBytes(): string +getHistoricalBytes(): number[] Obtains the historical bytes of this tag. @@ -273,21 +274,21 @@ Obtains the historical bytes of this tag. | **Type**| **Description** | | ------------------ | --------------------------| -| string | Historical bytes obtained.| +| number[] | Historical bytes obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let historicalBytes = tag.getIsoDepTag(taginfo).getHistoricalBytes(); -console.log("historicalBytes:" +historicalBytes); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +let historicalBytes = isoDep.getHistoricalBytes(); +console.log("isoDep historicalBytes: " + historicalBytes); ``` ### IsoDepTag.getHiLayerResponse9+ -getHiLayerResponse(): string +getHiLayerResponse(): number[] Obtains the HiLayer response of this tag. @@ -299,16 +300,16 @@ Obtains the HiLayer response of this tag. | **Type**| **Description** | | ------------------ | --------------------------| -| string | HiLayer response obtained.| +| number[] | HiLayer response obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let hiLayerResponse = tag.getIsoDepTag(taginfo).getHiLayerResponse(); -console.log("hiLayerResponse:" +hiLayerResponse); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +let hiLayerResponse = isoDep.getHiLayerResponse(); +console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -332,10 +333,13 @@ Checks whether an extended application protocol data unit (APDU) is supported. T ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.getIsoDepTag(taginfo).isExtendedApduSupported().then(function (has) { - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +isoDep.isExtendedApduSupported() + .then((data) => { + console.log("isoDep isExtendedApduSupported data: " + data); + }).catch((err)=> { + console.log("isoDep isExtendedApduSupported err: " + err); + }); ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -357,11 +361,14 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.getIsoDepTag(taginfo).isExtendedApduSupported(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +isoDep.isExtendedApduSupported((err, data)=> { + if (err) { + console.log("isoDep isExtendedApduSupported err: " + err); + } else { + console.log("isoDep isExtendedApduSupported data: " + data); + } +}); ``` ## NdefTag9+ @@ -374,7 +381,7 @@ The following describes the unique interfaces of **NdefTag**. ### NdefTag.createNdefMessage9+ -createNdefMessage(data: string): [NdefMessage](#ndefmessage9) +createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) Creates an NDEF message using raw bytes. @@ -386,28 +393,30 @@ Creates an NDEF message using raw bytes. | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| data | string | Yes| Raw bytes of the string type.| +| data | number[] | Yes| Raw bytes used to create the message. Each number is a hexadecimal number ranging from **0x00** to **0xFF**.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(data); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let rawData = [0x00, 0xa4, 0x04, ......]; // change the raw data bytes tobe correct. +let ndefMessage = ndef.createNdefMessage(rawData); +console.log("ndef ndefMessage: " + ndefMessage); ``` ## NdefMessage9+ ### NdefMessage.getNdefRecords9+ -getNdefRecords(): [NdefRecord](#ndefrecord9)[ ] +getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] Obtains all NDEF records. @@ -419,33 +428,18 @@ Obtains all NDEF records. | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefRecord](#ndefrecord9)[ ] | All records obtained.| +| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefRecord = tag.NdefTag(taginfo).getNdefRecords(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefRecords = ndef.getNdefRecords(); +console.log("ndef ndefRecords number: " + ndefRecords.length); ``` -## NdefRecord9+ - -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| tnf | number | UID of the tag.| -| [rtdType](#rtdtype9) | string | NFC Record Type Definition (RTD) supported by the tag.| -| id | string | Additional information about the tag.| -| payload | string | RF discovery ID of the tag.| - -## RtdType9+ - -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| RTD_TEXT | 'T' | Text information.| -| RTD_URI | 'U' | Network address, email, or phone number.| - ### NdefTag.createNdefMessage9+ createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) @@ -459,21 +453,32 @@ Creates an NDEF message using the NDEF records. **Parameters** | **Name**| **Type**| **Mandatory**| **Description**| | -------- | -------- | -------- | -------- | -| ndefRecords | [NdefRecord](#ndefrecord9)[] | Yes| A list of NDEF records.| +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF records used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefMessage = tag.NdefTag(taginfo).createNdefMessage(ndefRecords); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefRecords = [ + // record format: tnf, rtdType, id, payload + // 1st record: + {tnf: 0x01, rtdType: [0x54], id: [0x01, 0x02, ...], payload: [0x00, 0xa4, 0x04, ...]}, + + // 2nd record: + {tnf: 0x02, rtdType: [0x55], id: [0x03, 0x04, ...], payload: [0x00, 0xa4, 0x04, ...]}, + + // other record if has one ... +]; +let ndefMessage = ndef.createNdefMessage(ndefRecords); +console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.getNdefTagType9+ @@ -490,22 +495,23 @@ Obtains the type of this NDEF tag. | **Type**| **Description** | | ------------------ | --------------------------| -| [NfcForumType](#nfcforumtype9) | NDEF tag type obtained.| +| [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NfcForumType = tag.NdefTag(taginfo).getNdefTagType(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefTagType = ndef.getNdefTagType(); +console.log("ndef ndefTagType: " + ndefTagType); ``` ### NdefTag.getNdefMessage9+ getNdefMessage(): NdefMessage -Obtains the NDEF message from the tag discovered. +Obtains the NDEF message. **Required permissions**: ohos.permission.NFC_TAG @@ -515,15 +521,16 @@ Obtains the NDEF message from the tag discovered. | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message created.| +| [NdefMessage](#ndefmessage9) | NDEF message obtained. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let NdefMessage = tag.NdefTag(taginfo).getNdefMessage(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefMessage = ndef.getNdefMessage(); +console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ @@ -547,10 +554,13 @@ Checks whether the NDEF tag is writable. This API uses a promise to return the r ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).isNdefWritable().then(function (has) { - console.log(JSON.stringify(has)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.isNdefWritable() + .then((data) => { + console.log("ndef isNdefWritable data: " + data); + }).catch((err)=> { + console.log("ndef isNdefWritable err: " + err); + }); ``` ### NdefTag.isNdefWritable9+ @@ -574,11 +584,14 @@ Checks whether the NDEF tag is writable. This API uses an asynchronous callback ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).isNdefWritable(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.isNdefWritable((err, data)=> { + if (err) { + console.log("ndef isNdefWritable err: " + err); + } else { + console.log("ndef isNdefWritable data: " + data); + } +}); ``` ### NdefTag.readNdef9+ @@ -595,17 +608,20 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the NDEF message read.| +| Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).readNdef().then(function (ndefMessage) { - console.log(JSON.stringify(ndefMessage)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.readNdef() + .then((data) => { + console.log("ndef readNdef data: " + data); + }).catch((err)=> { + console.log("ndef readNdef err: " + err); + }); ``` ### NdefTag.readNdef9+ @@ -629,11 +645,14 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).readNdef(function (error, ndefMessage) { - console.log(JSON.stringify(error)) - console.log('ndefMessage: ' + ndefMessage) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.readNdef((err, data)=> { + if (err) { + console.log("ndef readNdef err: " + err); + } else { + console.log("ndef readNdef data: " + data); + } +}); ``` ### NdefTag.writeNdef9+ @@ -663,10 +682,15 @@ Writes an NDEF message to this tag. This API uses a promise to return the result ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -NdefTag.writeNdef(msg).then(function (netHandle) { - console.log(JSON.stringify(netHandle)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. + +ndef.writeNdef(ndefMessage) + .then((data) => { + console.log("ndef writeNdef data: " + data); + }).catch((err)=> { + console.log("ndef writeNdef err: " + err); + }); ``` ### NdefTag.writeNdef9+ @@ -691,18 +715,22 @@ Writes an NDEF message to this tag. This API uses an asynchronous callback to re ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).write(msg, function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefMessage = ndef.createNdefMessage([0x01, 0x02, ...]); // change the raw data to be correct. +ndef.writeNdef(ndefMessage, (err, data)=> { + if (err) { + console.log("ndef writeNdef err: " + err); + } else { + console.log("ndef writeNdef data: " + data); + } +}); ``` ### NdefTag.canSetReadOnly9+ -canSetReadOnly(): Promise\ +canSetReadOnly(): boolean -Checks whether this NDEF tag can be set to read-only. This API uses a promise to return the result. +Checks whether this NDEF tag can be set to read-only. **Required permissions**: ohos.permission.NFC_TAG @@ -712,45 +740,16 @@ Checks whether this NDEF tag can be set to read-only. This API uses a promise to | **Type**| **Description** | | ------------------ | --------------------------| -| Promise<boolean> | Promise used to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| +| boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).canSetReadOnly().then(function (has) { - console.log(JSON.stringify(has)) -}) -``` - -### NdefTag.canSetReadOnly9+ - -canSetReadOnly(callback: AsyncCallback<boolean>): void; - -Checks whether this NDEF tag can be set to read-only. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the tag can be set to read-only, **true** is returned; otherwise, **false** is returned.| - -**Example** - -```js -import tag from '@ohos.nfc.tag'; - -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).canSetReadOnly(function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +var canSetReadOnly = ndef.canSetReadOnly(); +console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ @@ -774,15 +773,18 @@ Sets this NDEF tag to read-only. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).setReadOnly().then(function (errcode) { - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.setReadOnly() + .then((data) => { + console.log("ndef setReadOnly data: " + data); + }).catch((err)=> { + console.log("ndef setReadOnly err: " + err); + }); ``` ### NdefTag.setReadOnly9+ -setReadOnly(callback: AsyncCallback): void +setReadOnly(callback: AsyncCallback\): void Sets this NDEF tag to read-only. This API uses an asynchronous callback to return the result. @@ -801,18 +803,21 @@ Sets this NDEF tag to read-only. This API uses an asynchronous callback to retur ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefTag(taginfo).setReadOnly(function (error, errcode) { - console.log(JSON.stringify(error)) - console.log('has: ' + errcode) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +ndef.setReadOnly((err, data)=> { + if (err) { + console.log("ndef setReadOnly err: " + err); + } else { + console.log("ndef setReadOnly data: " + data); + } +}); ``` ### NdefTag.getNdefTagTypeString9+ -getNdefTagTypeString(type: [NfcForumType](#nfcforumtype9)): string +getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -Converts an NFC Forum Type to a byte array defined in the NFC Forum. +Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. **Required permissions**: ohos.permission.NFC_TAG @@ -822,7 +827,7 @@ Converts an NFC Forum Type to a byte array defined in the NFC Forum. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| type | [NfcForumType](#nfcforumtype9) | Yes | NFC Forum Type.| +| type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| **Return value** @@ -835,21 +840,12 @@ Converts an NFC Forum Type to a byte array defined in the NFC Forum. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let ndefTypeString= tag.NdefTag(taginfo).getNdefTagTypeString(type); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let ndefTypeString = ndef.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); +console.log("ndef ndefTypeString: " + ndefTypeString); ``` -## NfcForumType9+ - -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| NFC_FORUM_TYPE_1 | 1 | NFC Forum Type 1.| -| NFC_FORUM_TYPE_2 | 2 | NFC Forum Type 2.| -| NFC_FORUM_TYPE_3 | 3 | NFC Forum Type 3.| -| NFC_FORUM_TYPE_4 | 4 | NFC Forum Type 4.| -| MIFARE_CLASSIC | 101 | MIFARE Classic.| - -## MifareClassicTag 9+ +## MifareClassicTag9+ Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**. @@ -886,15 +882,20 @@ Authenticates a sector using the key. The sector can be accessed only after the ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key).then(function (isKeyA) { - console.log(JSON.stringify(isKeyA)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorIndex = 1; // change it to be correct index. +let key = [0x04, 0x05, ....]; // change it to be correct key. +mifareClassic.authenticateSector(sectorIndex, key, true); + .then((data) => { + console.log("mifareClassic authenticateSector data: " + data); + }).catch((err)=> { + console.log("mifareClassic authenticateSector err: " + err); + }); ``` ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback): void +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean, callback: AsyncCallback\): void Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. @@ -916,16 +917,21 @@ Authenticates a sector using the key. The sector can be accessed only after the ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).authenticateSector(sectorIndex, key, function (error, has) { - console.log(JSON.stringify(error)) - console.log('has: ' + has) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorIndex = 1; // change it to be correct index. +let key = [0x04, 0x05, ....]; // change it to be correct key. +mifareClassic.authenticateSector(sectorIndex, key, true, (err, data)=> { + if (err) { + console.log("mifareClassic authenticateSector err: " + err); + } else { + console.log("mifareClassic authenticateSector data: " + data); + } +}); ``` ### MifareClassicTag.readSingleBlock9+ -readSingleBlock(blockIndex: number): Promise\ +readSingleBlock(blockIndex: number): Promise\ Reads a block (16 bytes) on the tag. This API uses a promise to return the result. @@ -943,23 +949,27 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the block data read.| +| Promise\ | Promise used to return the block data read.| **Example** ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex).then(function (data){ - console.log('data: ' + data) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock err: " + err); + } else { + console.log("mifareClassic readSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.readSingleBlock9+ -readSingleBlock(blockIndex: number, callback: AsyncCallback\): void +readSingleBlock(blockIndex: number, callback: AsyncCallback\): void Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. @@ -972,24 +982,27 @@ Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | blockIndex | number | Yes | Index of the block to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| **Example** ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).readSingleBlock(blockIndex, function (error, data) { - console.log(JSON.stringify(error)) - console.log('data: ' + data) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock err: " + err); + } else { + console.log("mifareClassic readSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: string): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ Writes data to a block on the tag. This API uses a promise to return the result. @@ -1002,7 +1015,7 @@ Writes data to a block on the tag. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | blockIndex | number | Yes | Index of the target block.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| **Return value** @@ -1015,16 +1028,21 @@ Writes data to a block on the tag. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let rawData = [0x0a, 0x14, ...]; // change it to be correct data. +mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { + if (err) { + console.log("mifareClassic writeSingleBlock err: " + err); + } else { + console.log("mifareClassic writeSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: string, callback: AsyncCallback\): void +writeSingleBlock(blockIndex: number, data: number[], callback: AsyncCallback\): void Writes data to a block on the tag. This API uses an asynchronous callback to return the result. @@ -1037,7 +1055,7 @@ Writes data to a block on the tag. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | blockIndex | number | Yes | Index of the target block.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** @@ -1045,12 +1063,16 @@ Writes data to a block on the tag. This API uses an asynchronous callback to ret ```js import tag from '@ohos.nfc.tag'; -let data = "xxx"; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).writeSingleBlock(blockIndex, data, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let rawData = [0x0a, 0x14, ...]; // change it to be correct data. +mifareClassic.writeSingleBlock(blockIndex, rawData, (err, data)=> { + if (err) { + console.log("mifareClassic writeSingleBlock err: " + err); + } else { + console.log("mifareClassic writeSingleBlock data: " + data); + } +}); ``` ### MifareClassicTag.incrementBlock9+ @@ -1081,10 +1103,16 @@ Increments a block with data. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic incrementBlock err: " + err); + } else { + console.log("mifareClassic incrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.incrementBlock9+ @@ -1110,11 +1138,16 @@ Increments a block with data. This API uses an asynchronous callback to return t ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).incrementBlock(blockIndex, value, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.incrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic incrementBlock err: " + err); + } else { + console.log("mifareClassic incrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.decrementBlock9+ @@ -1145,10 +1178,16 @@ Decrements a block with data. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic decrementBlock err: " + err); + } else { + console.log("mifareClassic decrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.decrementBlock9+ @@ -1174,11 +1213,16 @@ Decrements a block with data. This API uses an asynchronous callback to return t ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).decrementBlock(blockIndex, value, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let value = 0x20; // change it to be correct data. +mifareClassic.decrementBlock(blockIndex, value, (err, data)=> { + if (err) { + console.log("mifareClassic decrementBlock err: " + err); + } else { + console.log("mifareClassic decrementBlock data: " + data); + } +}); ``` ### MifareClassicTag.transferToBlock9+ @@ -1209,13 +1253,18 @@ Copies data from the register to a block. This API uses a promise to return the import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).transferToBlock(blockIndex).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.transferToBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic transferToBlock err: " + err); + } else { + console.log("mifareClassic transferToBlock data: " + data); + } +}); ``` -### MifareClassicTag.transferToBlock +### MifareClassicTag.transferToBlock9+ transferToBlock(blockIndex: number, callback: AsyncCallback\): void @@ -1237,11 +1286,15 @@ Copies data from the register to a block. This API uses an asynchronous callback ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).transferToBlock(blockIndex, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.transferToBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic transferToBlock err: " + err); + } else { + console.log("mifareClassic transferToBlock data: " + data); + } +}); ``` ### MifareClassicTag.restoreFromBlock9+ @@ -1272,10 +1325,14 @@ Copies data from a block to the register. This API uses a promise to return the import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.restoreFromBlock(blockIndex) + .then((data) => { + console.log("mifareClassic restoreFromBlock data: " + data); + }).catch((err)=> { + console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + }); ``` ### MifareClassicTag.restoreFromBlock9+ @@ -1300,11 +1357,15 @@ Copies data from a block to the register. This API uses an asynchronous callback ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareClassicTag(taginfo).restoreFromBlock(blockIndex, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +mifareClassic.restoreFromBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic restoreFromBlock err: " + err); + } else { + console.log("mifareClassic restoreFromBlock data: " + data); + } +}); ``` ### MifareClassicTag.getSectorCount9+ @@ -1328,8 +1389,9 @@ Obtains the number of sectors in this MIFARE Classic tag. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let setorCount = tag.MifareClassicTag(taginfo).getSectorCount(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorCount = mifareClassic.getSectorCount(); +console.log("mifareClassic sectorCount: " + sectorCount); ``` ### MifareClassicTag.getBlockCountInSector9+ @@ -1359,13 +1421,14 @@ Obtains the number of blocks in a sector. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let blockNumber = tag.MifareClassicTag(taginfo).getBlockCountInSector(sectorIndex); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockCountInSector = mifareClassic.getBlockCountInSector(); +console.log("mifareClassic blockCountInSector: " + blockCountInSector); ``` ### MifareClassicTag.getType9+ -getType(): [MifareClassicType](#mifareclassictype9) +getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) Obtains the type of this MIFARE Classic tag. @@ -1377,22 +1440,23 @@ Obtains the type of this MIFARE Classic tag. | **Type**| **Description** | | ------------------ | --------------------------| -| [MifareClassicType](#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| +| [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let type = tag.MifareClassicTag(taginfo).getType(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let getType = mifareClassic.getType(); +console.log("mifareClassic getType: " + getType); ``` ### MifareClassicTag.getTagSize9+ getTagSize(): number -Obtains the tag size (in bytes). For details, see [MifareTagSize](#mifaretagsize9). +Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). **Required permissions**: ohos.permission.NFC_TAG @@ -1402,35 +1466,18 @@ Obtains the tag size (in bytes). For details, see [MifareTagSize](#mifaretagsize | **Type**| **Description** | | ------------------ | --------------------------| -| number | Tag size obtained, in bytes. For details, see [MifareTagSize](#mifaretagsize9).| +| number | Tag size obtained, in bytes. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9).| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let size = tag.MifareClassicTag(taginfo).getTagSize(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let tagSize = mifareClassic.getTagSize(); +console.log("mifareClassic tagSize: " + tagSize); ``` -## MifareClassicType9+ - -| **Name**| **Value**| **Description**| -| -------- | -------- | -------- | -| TYPE_UNKNOWN | -1 | Unknown type.| -| TYPE_CLASSIC | 0 | MIFARE Classic.| -| TYPE_PLUS | 1 | MIFARE Plus.| -| TYPE_PRO | 2 | MIFARE Pro.| - -## MifareTagSize9+ - -| **Name**| **Value**| **Description**| -| -------- | -------- | -------- | -| MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| -| MC_SIZE_1K | 1024 | Each tag has 16 sectors, and each sector has 4 blocks.| -| MC_SIZE_2K | 2048 | Each tag has 32 sectors, and each sector has 4 blocks.| -| MC_SIZE_4K | 4096 | Each tag has 40 sectors, and each sector has 4 blocks.| - ### MifareClassicTag.isEmulatedTag9+ isEmulatedTag(): boolean @@ -1452,8 +1499,9 @@ Checks whether the tag is an emulated tag. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isEmulated = tag.MifareClassicTag(taginfo).isEmulatedTag(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let isEmulatedTag = mifareClassic.isEmulatedTag(); +console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` ### MifareClassicTag.getBlockIndex9+ @@ -1483,8 +1531,10 @@ Obtains the first block of a sector. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let index = tag.MifareClassicTag(taginfo).getBlockIndex(sectorIndex); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let sectorIndex = 1; // change it to be correct index. +let blockIndex = mifareClassic.getBlockIndex(sectorIndex); +console.log("mifareClassic blockIndex: " + blockIndex); ``` ### MifareClassicTag.getSectorIndex9+ @@ -1514,8 +1564,10 @@ Obtains the index of a sector that contains the specified block. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let index = tag.MifareClassicTag(taginfo).getSectorIndex(blockIndex); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +let blockIndex = 1; // change it to be correct index. +let sectorIndex = mifareClassic.getSectorIndex(blockIndex); +console.log("mifareClassic sectorIndex: " + sectorIndex); ``` ## MifareUltralightTag9+ @@ -1528,7 +1580,7 @@ The following describes the unique interfaces of **MifareUltralightTag**. ### MifareUltralightTag.readMultiplePages9+ -readMultiplePages(pageIndex: number): Promise\ +readMultiplePages(pageIndex: number): Promise\ Reads multiple pages (4 bytes per page). This API uses a promise to return the result. @@ -1546,7 +1598,7 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the data read.| +| Promise\ | Promise used to return the data read.| **Example** @@ -1554,15 +1606,19 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex).then(function (data){ - console.log("data: " + data) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +mifareUltralight.readMultiplePages(pageIndex) + .then((data) => { + console.log("mifareUltralight readMultiplePages data: " + data); + }).catch((err)=> { + console.log("mifareUltralight readMultiplePages err: " + err); + }); ``` ### MifareUltralightTag.readMultiplePages9+ -readMultiplePages(pageIndex: number, callback: AsyncCallback\): void +readMultiplePages(pageIndex: number, callback: AsyncCallback\): void Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. @@ -1575,23 +1631,27 @@ Reads multiple pages (4 bytes per page). This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | pageIndex | number | Yes | Indexes of the pages to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the data read.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).readMultiplePages(pageIndex, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages err: " + err); + } else { + console.log("mifareUltralight readMultiplePages data: " + data); + } +}); ``` ### MifareUltralightTag.writeSinglePages9+ -writeSinglePages(pageIndex: number, data: string): Promise\ +writeSinglePages(pageIndex: number, data: number[]): Promise\ Writes a page of data. This API uses a promise to return the result. @@ -1604,7 +1664,7 @@ Writes a page of data. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | | pageIndex | number | Yes | Index of the page.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| **Return value** @@ -1617,15 +1677,20 @@ Writes a page of data. This API uses a promise to return the result. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +mifareUltralight.writeSinglePages(pageIndex, data) + .then((data) => { + console.log("mifareUltralight writeSinglePages data: " + data); + }).catch((err)=> { + console.log("mifareUltralight writeSinglePages err: " + err); + }); ``` ### MifareUltralightTag.writeSinglePages9+ -writeSinglePages(pageIndex: number, data: string, callback: AsyncCallback\): void +writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void Writes a page of data. This API uses an asynchronous callback to return the result. @@ -1638,7 +1703,7 @@ Writes a page of data. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------ | | pageIndex | number | Yes | Index of the page.| -| data | string | Yes | Data to write.| +| data | number[] | Yes | Data to write.| | callback|AsyncCallback\ |Yes| Callback invoked to return the result.| **Example** @@ -1646,18 +1711,23 @@ Writes a page of data. This API uses an asynchronous callback to return the resu ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.MifareUltralightTag(taginfo).writeSinglePages(pageIndex, data, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let pageIndex = 1; // change it to be correct index. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +mifareUltralight.writeSinglePages(pageIndex, data, (err, data)=> { + if (err) { + console.log("mifareUltralight writeSinglePages err: " + err); + } else { + console.log("mifareUltralight writeSinglePages data: " + data); + } +}); ``` ### MifareUltralightTag.getType9+ getType(): MifareUltralightType -Obtains the MIFARE Ultralight tag type, in bytes. +Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9). **Required permissions**: ohos.permission.NFC_TAG @@ -1667,25 +1737,18 @@ Obtains the MIFARE Ultralight tag type, in bytes. | **Type**| **Description** | | ------------------ | --------------------------| -| MifareUltralightType | Type of the MIFARE Ultralight tag. For details, see [MifareUltralightType](#mifareultralighttype9).| +| MifareUltralightType | MIFARE Ultralight tag type obtained. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let type = tag.MifareUltralightType(taginfo).getType(); +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +let getType = mifareClassic.getType(); +console.log("mifareUltralight getType: " + getType); ``` -### MifareUltralightType9+ - -| **Name**| **Value**| **Description**| -| -------- | -------- | -------- | -| TYPE_UNKOWN | -1 | Unknown type.| -| TYPE_ULTRALIGHT | 1 | MIFARE Ultralight.| -| TYPE_ULTRALIGHT_C | 2 | MIFARE Ultralight C.| - ## NdefFormatableTag9+ Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**. @@ -1721,10 +1784,18 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).format(message).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.format(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable format err: " + err); + } else { + console.log("ndefFormatable format data: " + data); + } +}); ``` ### NdefFormatableTag.format9+ @@ -1741,19 +1812,32 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.| -| callback | AsyncCallback\ |Yes|Callback invoked to return the result.| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| callback: AsyncCallback\ | Callback invoked to return the result.| + **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).format(message, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.format(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable format err: " + err); + } else { + console.log("ndefFormatable format data: " + data); + } +}); ``` ### NdefFormatableTag.formatReadOnly9+ @@ -1783,10 +1867,18 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).formatReadOnly(message).then(function (errcode){ - console.log(JSON.stringify(errcode)) - }) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable formatReadOnly err: " + err); + } else { + console.log("ndefFormatable formatReadOnly data: " + data); + } +}); ``` ### NdefFormatableTag.formatReadOnly9+ @@ -1803,17 +1895,30 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only.| -| callback | AsyncCallback\ |Yes|Callback invoked to return the result.| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write when the formatting is successful. If this parameter is **null**, the tag is formatted only (no data will be written).| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| callback: AsyncCallback\ | Callback invoked to return the result.| + **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -tag.NdefFormatableTag(taginfo).formatReadOnly(message, function (error, errcode) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(errcode)) -}) +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. +let data = [0x01, 0x02, ...]; // change it to be correct raw data. +let ndefmessage = ndef.createNdefMessage(data); + +// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndefFormatable' correctly. +ndefFormatable.formatReadOnly(ndefmessage, (err, data)=> { + if (err) { + console.log("ndefFormatable formatReadOnly err: " + err); + } else { + console.log("ndefFormatable formatReadOnly data: " + data); + } +}); ``` diff --git a/en/application-dev/reference/apis/js-apis-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-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index e88c899e36745869e6009616b1c8581c3fa37b49..1fd0357783d6cf3ead6913cfc07a0e4b4e1c3c82 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -4,6 +4,8 @@ The **Prompt** module provides APIs for creating and showing toasts, dialog boxe > **NOTE** > +> The APIs of this module are deprecated since API Version 9. You are advised to use [@ohos.promptAction](js-apis-promptAction.md) instead. +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -35,6 +37,8 @@ prompt.showToast({ }); ``` +![en-us_image_0001](figures/en-us_image_0001.gif) + ## ShowToastOptions Describes the options for showing the toast. @@ -43,9 +47,9 @@ Describes the options for showing the toast. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text to display. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text to display. | | duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| -| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. It does not have an upper limit. The default unit is vp. | ## prompt.showDialog @@ -92,6 +96,8 @@ prompt.showDialog({ }) ``` +![en-us_image_0002](figures/en-us_image_0002.gif) + ## prompt.showDialog showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void @@ -132,6 +138,8 @@ prompt.showDialog({ }); ``` +![en-us_image_0004](figures/en-us_image_0004.gif) + ## ShowDialogOptions Describes the options for showing the dialog box. @@ -140,8 +148,8 @@ Describes the options for showing the dialog box. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the dialog box. | -| message | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Text body. | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Text body. | | buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| ## ShowDialogSuccessResponse @@ -170,7 +178,6 @@ Shows an action menu. This API uses a callback to return the result asynchronous | options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | | callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| - **Example** ```js @@ -195,6 +202,8 @@ prompt.showActionMenu({ }) ``` +![en-us_image_0005](figures/en-us_image_0005.gif) + ## prompt.showActionMenu showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> @@ -238,6 +247,8 @@ prompt.showActionMenu({ console.info('showActionMenu error: ' + err); }) ``` +![en-us_image_0006](figures/en-us_image_0006.gif) + ## ActionMenuOptions Describes the options for showing the action menu. @@ -246,7 +257,7 @@ Describes the options for showing the action menu. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------------------------------- | -| title | string\| [Resource](../../ui/ts-types.md#resource-type)9+| No | Title of the text to display. | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the text to display. | | buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| ## ActionMenuSuccessResponse @@ -267,5 +278,5 @@ Describes the menu item button in the action menu. | Name | Type | Mandatory | Description | | ----- | ---------------------------------------- | ---- | ------- | -| text | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Button text.| -| color | string\| [Resource](../../ui/ts-types.md#resource-type)9+| Yes | Text color of the button.| +| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Button text.| +| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md new file mode 100644 index 0000000000000000000000000000000000000000..268673b046bbb5f775dfffe3986105718319d009 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -0,0 +1,341 @@ +# Prompt + +The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus. + +> **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 promptAction from '@ohos.promptAction' +``` + +## promptAction.showToast + +showToast(options: ShowToastOptions): void + +Shows a toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------- | ---- | ------- | +| options | [ShowToastOptions](#showtoastoptions) | Yes | Toast options.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showToast({ + message: 'Message Info', + duration: 2000, + }); +} catch (error) { + console.error(`showToast args error code is ${error.code}, message is ${error.message}`); +}; + +``` + +![en-us_image_0001](figures/en-us_image_0001.gif) + +## ShowToastOptions + +Describes the options for showing the toast. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ---------------------------------------- | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Text to display. | +| duration | number | No | Duration that the toast will remain on the screen. The default value is 1500 ms. The value range is 1500 ms to 10000 ms. If a value less than 1500 ms is set, the default value is used. If the value greater than 10000 ms is set, the upper limit 10000 ms is used.| +| bottom | string\| number | No | Distance between the toast border and the bottom of the screen. | + +## promptAction.showDialog + +showDialog(options: ShowDialogOptions): Promise<ShowDialogSuccessResponse> + +Shows a dialog box. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | -------- | +| Promise<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Promise used to return the dialog box response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showDialog({ + title: 'Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ], + }) + .then(data => { + console.info('showDialog success, click button: ' + data.index); + }) + .catch(err => { + console.info('showDialog error: ' + err); + }) +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0002](figures/en-us_image_0002.gif) + +## promptAction.showDialog + +showDialog(options: ShowDialogOptions, callback: AsyncCallback<ShowDialogSuccessResponse>):void + +Shows a dialog box. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------ | +| options | [ShowDialogOptions](#showdialogoptions) | Yes | Dialog box options.| +| callback | AsyncCallback<[ShowDialogSuccessResponse](#showdialogsuccessresponse)> | Yes | Callback used to return the dialog box response result. | + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showDialog({ + title: 'showDialog Title Info', + message: 'Message Info', + buttons: [ + { + text: 'button1', + color: '#000000', + }, + { + text: 'button2', + color: '#000000', + } + ] + }, (err, data) => { + if (err) { + console.info('showDialog err: ' + err); + return; + } + console.info('showDialog success callback, click button: ' + data.index); + }); +} catch (error) { + console.error(`showDialog args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0002](figures/en-us_image_0002.gif) + +## ShowDialogOptions + +Describes the options for showing the dialog box. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| message | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Text body. | +| buttons | Array | No | Array of buttons in the dialog box. The array structure is **{text:'button', color: '\#666666'}**. Up to three buttons are supported. The first button is of the **positiveButton** type, the second is of the **negativeButton** type, and the third is of the **neutralButton** type.| + +## ShowDialogSuccessResponse + +Describes the dialog box response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Description | +| ----- | ------ | ------------------- | +| index | number | Index of the selected button in the **buttons** array.| + +## promptAction.showActionMenu + +showActionMenu(options: ActionMenuOptions, callback: AsyncCallback<ActionMenuSuccessResponse>):void + +Shows an action menu. This API uses a callback to return the result asynchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options. | +| callback | AsyncCallback<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Yes | Callback used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showActionMenu({ + title: 'Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }, (err, data) => { + if (err) { + console.info('showActionMenu err: ' + err); + return; + } + console.info('showActionMenu success callback, click button: ' + data.index); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0005](figures/en-us_image_0005.gif) + +## promptAction.showActionMenu + +showActionMenu(options: ActionMenuOptions): Promise<ActionMenuSuccessResponse> + +Shows an action menu. This API uses a promise to return the result synchronously. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | --------------------------------------- | ---- | ------- | +| options | [ActionMenuOptions](#actionmenuoptions) | Yes | Action menu options.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise<[ActionMenuSuccessResponse](#actionmenusuccessresponse)> | Promise used to return the action menu response result.| + +**Error codes** + +For details about the error codes, see [promptAction Error Codes](../errorcodes/errorcode-promptAction.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + +**Example** + +```js +try { + promptAction.showActionMenu({ + title: 'showActionMenu Title Info', + buttons: [ + { + text: 'item1', + color: '#666666', + }, + { + text: 'item2', + color: '#000000', + }, + ] + }) + .then(data => { + console.info('showActionMenu success, click button: ' + data.index); + }) + .catch(err => { + console.info('showActionMenu error: ' + err); + }) +} catch (error) { + console.error(`showActionMenu args error code is ${error.code}, message is ${error.message}`); +}; +``` + +![en-us_image_0005](figures/en-us_image_0005.gif) + +## ActionMenuOptions + +Describes the options for showing the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | ---------------------------------------- | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| buttons | Array<[Button](#button)> | Yes | Array of menu item buttons. The array structure is **{text:'button', color: '\#666666'}**. Up to six buttons are supported. If there are more than six buttons, extra buttons will not be displayed.| + +## ActionMenuSuccessResponse + +Describes the action menu response result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------------------------ | +| index | number | No | Index of the selected button in the **buttons** array, starting from **0**.| + +## Button + +Describes the menu item button in the action menu. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +| Name | Type | Mandatory | Description | +| ----- | ---------------------------------------- | ---- | ------- | +| text | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Button text.| +| color | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| Yes | Text color of the button.| diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index ec920f58cab6825ce1dd286f42d1eb24e759f10b..ad01b50bc77d167a58eff666777c2d383cec8922 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1840,10 +1840,10 @@ Defines the network status. | Name | Value | Description | | ----------------------------- | ---- | -------------------------- | -| REG_STATE_NO_SERVICE | 0 | The device cannot use any service. | -| REG_STATE_IN_SERVICE | 1 | The device can use services normally. | -| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service.| -| REG_STATE_POWER_OFF | 3 | The cellular radio service is disabled. | +| REG_STATE_NO_SERVICE | 0 | The device cannot use any services, including data, SMS, and call services. | +| REG_STATE_IN_SERVICE | 1 | The device can use services properly, including data, SMS, and call services. | +| REG_STATE_EMERGENCY_CALL_ONLY | 2 | The device can use only the emergency call service. | +| REG_STATE_POWER_OFF | 3 | The device cannot communicate with the network because the cellular radio service is disabled or the modem is powered off. | ## NsaState diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 2609d848a83392c8b0630015b2f135894fde0a61..27e794f1f636971f637b4cfe3bda4eff9fbb0852 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -14,108 +14,404 @@ The **Router** module provides APIs to access pages through URLs. You can use th import router from '@ohos.router' ``` -## router.push +## router.pushUrl9+ -push(options: RouterOptions): void +pushUrl(options: RouterOptions): Promise<void> Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | --------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | **Example** + ```js -router.push({ - url: 'pages/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, }, - }, -}); + }) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` -## router.push9+ -push(options: RouterOptions, mode: RouterMode): void +## router.pushUrl9+ + +pushUrl(options: RouterOptions, callback: AsyncCallback<void>): void + +Navigates to a specified page in the application. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | + +**Example** + +```js +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); + }); +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` +## router.pushUrl9+ + +pushUrl(options: RouterOptions, mode: RouterMode): Promise<void> Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | **Example** + ```js -router.push({ - url: 'pages/routerpage2/routerpage2', - params: { - data1: 'message', - data2: { - data3: [123, 456, 789] +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, }, - }, -},router.RouterMode.Standard); + }, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` -## router.replace +## router.pushUrl9+ -replace(options: RouterOptions): void +pushUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void -Replaces the current page with another one in the application and destroys the current page. +Navigates to a specified page in the application. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 100002 | Uri error. The uri of router is not exist. | +| 100003 | Page stack error. The pages are pushed too much. | + +**Example** + +```js +try { + router.pushUrl({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, + }, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('pushUrl success'); + }); +} catch (error) { + console.error(`pushUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------ | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + **Example** ```js -router.replace({ - url: 'pages/detail', - params: { - data1: 'message', - }, -}); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` - ## router.replace9+ +## router.replaceUrl9+ -replace(options: RouterOptions, mode: RouterMode): void +replaceUrl(options: RouterOptions, callback: AsyncCallback<void>): void Replaces the current page with another one in the application and destroys the current page. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + +**Example** + +```js +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); + }); +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions, mode: RouterMode): Promise<void> + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------------------------------- | ---- | ---------- | | options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | | mode | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Return value** + +| Type | Description | +| ------------------- | --------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + **Example** ```js -router.replace({ - url: 'pages/detail/detail', - params: { - data1: 'message', - }, -}, router.RouterMode.Standard); +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, router.RouterMode.Standard) + .then(() => { + // success + }) + .catch(err => { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + }) +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; +``` + +## router.replaceUrl9+ + +replaceUrl(options: RouterOptions, mode: RouterMode, callback: AsyncCallback<void>): void + +Replaces the current page with another one in the application and destroys the current page. + +**System capability**: SystemCapability.ArkUI.ArkUI.Lite + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | +| 200002 | Uri error. The uri of router is not exist. | + +**Example** + +```js +try { + router.replaceUrl({ + url: 'pages/detail', + params: { + data1: 'message', + }, + }, router.RouterMode.Standard, (err) => { + if (err) { + console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); + return; + } + console.info('replaceUrl success'); + }); +} catch (error) { + console.error(`replaceUrl args error code is ${error.code}, message is ${error.message}`); +}; ``` ## router.back @@ -127,6 +423,7 @@ Returns to the previous page or a specified page. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------- | ---- | ------------------------------------------------------------ | | options | [RouterOptions](#routeroptions) | No | Description of the page. The **url** parameter indicates the URL of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If no URL is set, the previous page is returned, and the page in the page stack is not reclaimed. It will be reclaimed after being popped up.| @@ -160,11 +457,13 @@ Obtains the number of pages in the current stack. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Return value** + | Type | Description | | ------ | ------------------ | | string | Number of pages in the stack. The maximum value is **32**.| **Example** + ```js var size = router.getLength(); console.log('pages stack size = ' + size); @@ -205,25 +504,38 @@ Describes the page routing state. | name | string | Name of the current page, that is, the file name. | | path | string | Path of the current page. | -## router.enableAlertBeforeBackPage +## router.enableBackPageAlert9+ -enableAlertBeforeBackPage(options: EnableAlertOptions): void +enableBackPageAlert(options: EnableAlertOptions): void Enables the display of a confirm dialog box before returning to the previous page. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | --------- | | options | [EnableAlertOptions](#enablealertoptions) | Yes | Description of the dialog box.| +**Error codes** + +For details about the error codes, see [Router Error Codes](../errorcodes/errorcode-router.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | Internal error. | + **Example** - ```js - router.enableAlertBeforeBackPage({ + ```js +try { + router.enableBackPageAlert({ message: 'Message Info' - }); + }); +} catch(error) { + console.error(`enableBackPageAlert failed, code is ${error.code}, message is ${error.message}`); +} ``` ## EnableAlertOptions @@ -244,6 +556,7 @@ Disables the display of a confirm dialog box before returning to the previous pa **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** + ```js router.disableAlertBeforeBackPage(); ``` @@ -274,10 +587,10 @@ Describes the page routing options. **System capability**: SystemCapability.ArkUI.ArkUI.Lite -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| url | string | Yes | URI of the destination page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URI is a slash (/), the home page is displayed.| -| params | Object | No | Data that needs to be passed to the destination page during redirection. After the destination page is displayed, it can use the passed data, for example, **this.data1** (**data1** is a key in **params**). If there is the same key (for example, **data1**) on the destination page, the passed **data1** value will replace the original value on the destination page.| +| Name | Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| url | string | Yes | URL of the target page, in either of the following formats:
- Absolute path of the page. The value is available in the pages list in the **config.json** file, for example:
- pages/index/index
- pages/detail/detail
- Particular path. If the URL is a slash (/), the home page is displayed.| +| params | Object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is a key in **params**). In the web-like paradigm, these parameters can be directly used on the target page. If the field specified by **key** already exists on the target page, the passed value of the key will be displayed.| > **NOTE** @@ -291,7 +604,7 @@ Enumerates the routing modes. | Name | Description | | -------- | ---------------------------------------- | -| Standard | Standard mode. | +| Standard | Standard mode.
The target page is added to the top of the page stack, regardless of whether a page with the same URL exists in the stack. | | Single | Singleton mode.
If the URL of the target page already exists in the page stack, the page closest to the top of the stack is moved as a new page to the top of the stack.
If the URL of the target page does not exist in the page stack, the page is redirected to in standard mode.| ## Examples @@ -401,3 +714,144 @@ struct Second { } } ``` + +## router.push(deprecated) + +push(options: RouterOptions): void + +Navigates to a specified page in the application. + +This API is deprecated since API version 9. You are advised to use [pushUrl9+](#routerpushurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | --------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters.| + + +**Example** + +```js +router.push({ + url: 'pages/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, +}); +``` +## router.push(deprecated) + +push(options: RouterOptions, mode: RouterMode): void + +Navigates to a specified page in the application. + +This API is deprecated since API version 9. You are advised to use [pushUrl9+](#routerpushurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Page routing parameters. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + + +**Example** + +```js +router.push({ + url: 'pages/routerpage2/routerpage2', + params: { + data1: 'message', + data2: { + data3: [123, 456, 789] + }, + }, +},router.RouterMode.Standard); +``` + +## router.replace(deprecated) + +replace(options: RouterOptions): void + +Replaces the current page with another one in the application and destroys the current page. + +This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------- | ---- | ------------------ | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page.| + +**Example** + +```js +router.replace({ + url: 'pages/detail', + params: { + data1: 'message', + }, +}); +``` + + ## router.replace(deprecated) + +replace(options: RouterOptions, mode: RouterMode): void + +Replaces the current page with another one in the application and destroys the current page. + +This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------------------------------- | ---- | ---------- | +| options | [RouterOptions](#routeroptions) | Yes | Description of the new page. | +| mode | [RouterMode](#routermode9) | Yes | Routing mode.| + +**Example** + +```js +router.replace({ + url: 'pages/detail/detail', + params: { + data1: 'message', + }, +}, router.RouterMode.Standard); +``` + +## router.enableAlertBeforeBackPage(deprecated) + +enableAlertBeforeBackPage(options: EnableAlertOptions): void + +Enables the display of a confirm dialog box before returning to the previous page. + +This API is deprecated since API version 9. You are advised to use [enableBackPageAlert9+](#routerenablebackpagealert9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | ---- | --------- | +| options | [EnableAlertOptions](#enablealertoptions) | Yes | Description of the dialog box.| + +**Example** + + ```js + router.enableAlertBeforeBackPage({ + message: 'Message Info' + }); + ``` diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 73ea5d3c915d2ba91c129ed8d7c8ed80efe8170d..47cb10179c1d12d9bd7d010b9db08dc316b57f7f 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -1,4 +1,5 @@ # Screen + The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens. > **NOTE** @@ -6,6 +7,7 @@ The **Screen** module implements basic screen management. You can use the APIs o > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > > The APIs provided by this module are system APIs. + ## Modules to Import ```js @@ -26,19 +28,28 @@ Obtains all screens. This API uses an asynchronous callback to return the result | -------- | --------------------------------------------------- | ---- | -------------------------------------- | | callback | AsyncCallback<Array<[Screen](#screen)>> | Yes | Callback used to return all the **Screen** objects obtained.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var screenClass = null; +let screenClass = null; screen.getAllScreens((err, data) => { if (err.code) { - console.error('Failed to get all screens . Cause: ' + JSON.stringify(err)); + console.error('Failed to get all screens. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in getting all screens . Data:' + JSON.stringify(data)); + console.info('Succeeded in getting all screens. Data:' + JSON.stringify(data)); screenClass = data[0]; }); ``` + ## screen.getAllScreens getAllScreens(): Promise<Array<Screen>> @@ -48,22 +59,34 @@ Obtains all screens. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** + | Type | Description | | --------------------------------------------- | ----------------------------------------- | | Promise<Array<[Screen](#screen)>> | Promise used to return all the **Screen** objects obtained.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenClass = null; +let screenClass = null; let promise = screen.getAllScreens(); promise.then((data) => { screenClass = data[0]; - console.log('Succeeded in getting all screens . Data:'+ JSON.stringify(data)); + console.log('Succeeded in getting all screens. Data:'+ JSON.stringify(data)); }).catch((err) => { - console.log('Failed to get all screens . Cause: ' + JSON.stringify(err)); + console.log('Failed to get all screens. Cause: ' + JSON.stringify(err)); }); ``` + ## screen.on('connect' | 'disconnect' | 'change') + on(eventType: 'connect' | 'disconnect' | 'change', callback: Callback<number>): void Subscribes to events related to the screen state. @@ -71,19 +94,27 @@ Subscribes to events related to the screen state. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | --------- | ---------------------- | ---- | ------------------------------------------------------------ | | eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| | callback | Callback<number> | Yes | Callback used to return the screen ID. | **Example** + ```js -var callback = (data) => { - console.info('Register the callback for screen changes. Data: ' + JSON.stringify(data)) +try { + let callback = (data) => { + console.info('Succeeded in registering the callback for screen changes. Data: ' + JSON.stringify(data)) + }; + screen.on('connect', callback); +} catch (exception) { + console.error('Failed to register the callback for screen changes. Code: ' + JSON.stringify(exception)); }; -screen.on("connect", callback); ``` + ## screen.off('connect' | 'disconnect' | 'change') + off(eventType: 'connect' | 'disconnect' | 'change', callback?: Callback<number>): void Unsubscribes from events related to the screen state. @@ -91,20 +122,27 @@ Unsubscribes from events related to the screen state. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | --------- | ---------------------- | ---- | ------------------------------------------------------------ | | eventType | string | Yes | Event type.
- **connect**: an event indicating that the screen is connected.
- **disconnect**: an event indicating that the screen is disconnected.
- **change**: an event indicating that the screen state changes.| | callback | Callback<number> | No | Callback used to return the screen ID. | **Example** + ```js -var callback = (data) => { - console.info('Unregister the callback for screen changes. Data: ' + JSON.stringify(data)) +try { + let callback = (data) => { + console.info('Succeeded in unregistering the callback for screen changes. Data: ' + JSON.stringify(data)) + }; + screen.off('connect', callback); +} catch (exception) { + console.error('Failed to register the callback for screen changes. Code: ' + JSON.stringify(exception)); }; -screen.off("connect", callback); ``` ## screen.makeExpand + makeExpand(options:Array<ExpandOption>, callback: AsyncCallback<number>): void Sets the screen to the expanded mode. This API uses an asynchronous callback to return the result. @@ -112,26 +150,40 @@ Sets the screen to the expanded mode. This API uses an asynchronous callback to **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------------ | ---- | -------------------------------- | | options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen. | | callback | Callback<number> | Yes | Callback used to return the group ID of the expanded screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var groupId = null; -screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}], (err, data) => { - if (err.code) { - console.error('Failed to make screens as expand-screen. Cause:' + JSON.stringify(err)); - return; - } - groupId = data; - console.info('Succeeded in making screens as expand-screen.Data:' + JSON.stringify(data)); -}); +try { + let groupId = null; + screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}], (err, data) => { + if (err.code) { + console.error('Failed to expand the screen. Code:' + JSON.stringify(err)); + return; + } + groupId = data; + console.info('Succeeded in expanding the screen. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to expand the screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.makeExpand + makeExpand(options:Array<ExpandOption>): Promise<number> Sets the screen to the expanded mode. This API uses a promise to return the result. @@ -145,20 +197,35 @@ Sets the screen to the expanded mode. This API uses a promise to return the resu | options | Array<[ExpandOption](#expandoption)> | Yes | Parameters for expanding the screen.| **Return value** + | Type | Description | | --------------------- | ----------------------------------- | | Promise<number> | Promise used to return the group ID of the expanded screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}]).then((data) => { - console.info('Succeeded in making screens as expand-screen.Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to make screens as expand-screen. Cause:' + JSON.stringify(err)); -}); +try { + screen.makeExpand([{screenId: 0, startX: 0, startY: 0}, {screenId: 1, startX: 1080, startY: 0}]).then((data) => { + console.info('Succeeded in expanding the screen. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to expand the screen. Code:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to expand the screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.makeMirror + makeMirror(mainScreen:number, mirrorScreen:Array<number>, callback: AsyncCallback<number>): void Sets screen mirroring. This API uses an asynchronous callback to return the result. @@ -173,20 +240,34 @@ Sets screen mirroring. This API uses an asynchronous callback to return the resu | mirrorScreen | Array<number> | Yes | IDs of secondary screens. | | callback | AsyncCallback<number> | Yes | Callback used to return the group ID of the secondary screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var mainScreenId = 0; -var mirrorScreenIds = [1, 2, 3]; -screen.makeMirror(mainScreenId, mirrorScreenIds, (err, data) => { - if (err.code) { - console.error('Failed to make screens as mirror-screen.Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in making screens as mirror-screen.Data:' + JSON.stringify(data)); -}); +let mainScreenId = 0; +let mirrorScreenIds = [1, 2, 3]; +try { + screen.makeMirror(mainScreenId, mirrorScreenIds, (err, data) => { + if (err.code) { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting screen mirroring. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.makeMirror + makeMirror(mainScreen:number, mirrorScreen:Array<number>): Promise<number> Sets screen mirroring. This API uses a promise to return the result. @@ -201,22 +282,37 @@ Sets screen mirroring. This API uses a promise to return the result. | mirrorScreen | Array<number> | Yes | IDs of secondary screens.| **Return value** + | Type | Description | | --------------------- | ----------------------------------- | | Promise<number> | Promise used to return the group ID of the secondary screens.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var mainScreenId = 0; -var mirrorScreenIds = [1, 2, 3]; -screen.makeMirror(mainScreenId, mirrorScreenIds).then((data) => { - console.info('Succeeded in making screens as mirror-screen.Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to make screens as mirror-screen.Cause:' + JSON.stringify(err)); -}); +let mainScreenId = 0; +let mirrorScreenIds = [1, 2, 3]; +try { + screen.makeMirror(mainScreenId, mirrorScreenIds).then((data) => { + console.info('Succeeded in setting screen mirroring. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set screen mirroring. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.createVirtualScreen + createVirtualScreen(options:VirtualScreenOption, callback: AsyncCallback<Screen>): void Creates a virtual screen. This API uses an asynchronous callback to return the result. @@ -232,35 +328,50 @@ Creates a virtual screen. This API uses an asynchronous callback to return the r | options | [VirtualScreenOption](#virtualscreenoption) | Yes | Virtual screen parameters. | | callback | AsyncCallback<[Screen](#screen)> | Yes | Callback used to return the created virtual screen.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenClass = null; -screen.createVirtualScreen({ - name: 'screen01', - width: 1080, - height: 2340, - density: 2, - surfaceId: '' -}, (err, data) => { - if (err.code) { - console.error('Failed to create virtual screen.Cause:' + JSON.stringify(err)); - return; - } - screenClass = data; - console.info('Succeeded in creating virtual screen.Data:' + JSON.stringify(data)); -}); +let screenClass = null; +try { + screen.createVirtualScreen({ + name: 'screen01', + width: 1080, + height: 2340, + density: 2, + surfaceId: '' + }, (err, data) => { + if (err.code) { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(err)); + return; + } + screenClass = data; + console.info('Succeeded in creating the virtual screen. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.createVirtualScreen + createVirtualScreen(options:VirtualScreenOption): Promise<Screen> Creates a virtual screen. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid available only to system applications) +**Required permissions**: ohos.permission.CAPTURE_SCREEN (mandatory when **VirtualScreenOption.surfaceId** is valid; available only to system applications) **Parameters** + | Name | Type | Mandatory| Description | | ------- | ------------------------------------------- | ---- | ------------------------ | | options | [VirtualScreenOption](#virtualscreenoption) | Yes | Virtual screen parameters.| @@ -271,24 +382,38 @@ Creates a virtual screen. This API uses a promise to return the result. | -------------------------------- | ------------------------------------- | | Promise<[Screen](#screen)> | Promise used to return the created virtual screen.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenClass = null; -screen.createVirtualScreen({ - name: 'screen01', - width: 1080, - height: 2340, - density: 2, - surfaceId: '' -}).then((data) => { - screenClass = data; - console.info('Succeeded in creating virtual screen.Data:' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to create virtual screen.Cause:' + JSON.stringify(err)); -}); +let screenClass = null; +try { + screen.createVirtualScreen({ + name: 'screen01', + width: 1080, + height: 2340, + density: 2, + surfaceId: '' + }).then((data) => { + screenClass = data; + console.info('Succeeded in creating the virtual screen. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to create the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.destroyVirtualScreen + destroyVirtualScreen(screenId:number, callback: AsyncCallback<void>): void Destroys a virtual screen. This API uses an asynchronous callback to return the result. @@ -296,24 +421,39 @@ Destroys a virtual screen. This API uses an asynchronous callback to return the **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | screenId | number | Yes | Screen ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------------- | +| 1400002 | Unauthorized operation. | + **Example** + ```js -var screenId = 1; -screen.destroyVirtualScreen(screenId, (err,data) => { - if (err.code) { - console.error('Failed to destroy virtual screen.Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in destroying virtual screen.'); -}); +let screenId = 1; +try { + screen.destroyVirtualScreen(screenId, (err,data) => { + if (err.code) { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the virtual screen.'); + }); +} catch (exception) { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.destroyVirtualScreen + destroyVirtualScreen(screenId:number): Promise<void> Destroys a virtual screen. This API uses a promise to return the result. @@ -321,26 +461,42 @@ Destroys a virtual screen. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------- | | screenId | number | Yes | Screen ID.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------------- | +| 1400002 | Unauthorized operation. | + **Example** + ```js -var screenId = 1; -screen.destroyVirtualScreen(screenId).then((data) => { - console.info('Succeeded in destroying virtual screen.'); -}).catch((err) => { - console.error('Failed to destroy virtual screen.Cause:' + JSON.stringify(err)); -}); +let screenId = 1; +try { + screen.destroyVirtualScreen(screenId).then((data) => { + console.info('Succeeded in destroying the virtual screen.'); + }).catch((err) => { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to destroy the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.setVirtualScreenSurface + setVirtualScreenSurface(screenId:number, surfaceId: string, callback: AsyncCallback<void>): void Sets the surface for a virtual screen. This API uses an asynchronous callback to return the result. @@ -357,21 +513,34 @@ Sets the surface for a virtual screen. This API uses an asynchronous callback to | surfaceId | string | Yes | Surface ID. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the virtual screen surface is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** ```js -var screenId = 1; -var surfaceId = '2048'; -screen.setVirtualScreenSurface(screenId, surfaceId, (err,data) => { - if (err.code) { - console.error('Failed to set surface for the virtual screen. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting surface for the virtual screen.'); -}); +let screenId = 1; +let surfaceId = '2048'; +try { + screen.setVirtualScreenSurface(screenId, surfaceId, (err,data) => { + if (err.code) { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the surface for the virtual screen.'); + }); +} catch (exception) { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.setVirtualScreenSurface + setVirtualScreenSurface(screenId:number, surfaceId: string): Promise<void> Sets the surface for a virtual screen. This API uses a promise to return the result. @@ -381,28 +550,44 @@ Sets the surface for a virtual screen. This API uses a promise to return the res **Required permissions**: ohos.permission.CAPTURE_SCREEN (available only to system applications) **Parameters** + | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------- | | screenId | number | Yes | Screen ID. | | surfaceId | string | Yes | Surface ID.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | ----------------------- | +| 1400001 | Invalid display or screen. | + **Example** + ```js -var screenId = 1; -var surfaceId = '2048'; -screen.setVirtualScreenSurface(screenId, surfaceId).then((data) => { - console.info('Succeeded in setting surface for the virtual screen.'); -}).catch((err) => { - console.error('Failed to set surface for the virtual screen. Cause:' + JSON.stringify(err)); -}); +let screenId = 1; +let surfaceId = '2048'; +try { + screen.setVirtualScreenSurface(screenId, surfaceId).then((data) => { + console.info('Succeeded in setting the surface for the virtual screen.'); + }).catch((err) => { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the surface for the virtual screen. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.isScreenRotationLocked + isScreenRotationLocked(): Promise<boolean> Checks whether auto rotate is locked. This API uses a promise to return the result. @@ -410,20 +595,23 @@ Checks whether auto rotate is locked. This API uses a promise to return the resu **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** + | Type | Description | | ---------------------- | ------------------------------------- | | Promise<boolean> | Promise used to return the result. If **true** is returned, auto rotate is locked. If **false** is returned, auto rotate is unlocked.| **Example** + ```js screen.isScreenRotationLocked().then((isLocked) => { - console.info('Succeeded in getting screen rotation lock status. isLocked:'+ JSON.stringify(isLocked)); + console.info('Succeeded in getting the screen rotation lock status. isLocked:'+ JSON.stringify(isLocked)); }).catch((err) => { - console.error('Failed to get screen rotation lock status. Cause:' + JSON.stringify(err)); + console.error('Failed to get the screen rotation lock status. Cause:' + JSON.stringify(err)); }); ``` ## screen.isScreenRotationLocked + isScreenRotationLocked(callback: AsyncCallback<boolean>): void Checks whether auto rotate is locked. This API uses an asynchronous callback to return the result. @@ -441,14 +629,15 @@ Checks whether auto rotate is locked. This API uses an asynchronous callback to ```js screen.isScreenRotationLocked((err, isLocked) => { if (err.code) { - console.error('Failed to get screen rotation lock status. Cause:' + JSON.stringify(err)); + console.error('Failed to get the screen rotation lock status. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in getting screen rotation lock status. isLocked:' + JSON.stringify(isLocked)); + console.info('Succeeded in getting the screen rotation lock status. isLocked:' + JSON.stringify(isLocked)); }); ``` ## screen.setScreenRotationLocked + setScreenRotationLocked(isLocked: boolean): Promise<void> Sets whether to lock auto rotate. This API uses a promise to return the result. @@ -456,26 +645,34 @@ Sets whether to lock auto rotate. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** + | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------- | | isLocked | boolean | Yes | Whether to lock auto rotate. The value **true** means to lock auto rotate, and **false** means the opposite.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js -var isLocked = false; -screen.setScreenRotationLocked(isLocked).then((data) => { - console.info('Succeeded in setting whether to lock screen rotation'); -}).catch((err) => { - console.error('Failed to set whether to lock screen rotation. Cause:' + JSON.stringify(err)); -}); +let isLocked = false; +try { + screen.setScreenRotationLocked(isLocked).then((data) => { + console.info('Succeeded in unlocking auto rotate'); + }).catch((err) => { + console.error('Failed to unlock auto rotate. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to unlock auto rotate. Code: ' + JSON.stringify(exception)); +}; ``` ## screen.setScreenRotationLocked + setScreenRotationLocked(isLocked: boolean, callback: AsyncCallback<void>): void Sets whether to lock auto rotate. This API uses an asynchronous callback to return the result. @@ -492,17 +689,22 @@ Sets whether to lock auto rotate. This API uses an asynchronous callback to retu **Example** ```js -var isLocked = false; -screen.setScreenRotationLocked(isLocked, (err, data) => { - if (err.code) { - console.error('Failed to set whether to lock screen rotation. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting whether to lock screen rotation.'); -}); +let isLocked = false; +try { + screen.setScreenRotationLocked(isLocked, (err, data) => { + if (err.code) { + console.error('Failed to unlock auto rotate. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in unlocking auto rotate.'); + }); +} catch (exception) { + console.error('Failed to unlock auto rotate. Code: ' + JSON.stringify(exception)); +}; ``` ## ExpandOption + Defines the parameters for expanding a screen. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -514,6 +716,7 @@ Defines the parameters for expanding a screen. | startY | number | Yes | Yes | Start Y coordinate of the screen.| ## VirtualScreenOption + Defines virtual screen parameters. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -527,6 +730,7 @@ Defines virtual screen parameters. | surfaceId | string | Yes | Yes | Surface ID of the virtual screen.| ## Screen + Implements a **Screen** instance. Before calling any API in **Screen**, you must use **[getAllScreens()](#screengetallscreens)** or **[createVirtualScreen()](#screencreatevirtualscreen)** to obtain a **Screen** instance. @@ -542,6 +746,7 @@ Before calling any API in **Screen**, you must use **[getAllScreens()](#screenge | orientation | [Orientation](#orientation) | Yes | No | Screen orientation. | ### setOrientation + setOrientation(orientation: Orientation, callback: AsyncCallback<void>): void Sets the screen orientation. This API uses an asynchronous callback to return the result. @@ -553,17 +758,32 @@ Sets the screen orientation. This API uses an asynchronous callback to return th | orientation | [Orientation](#orientation) | Yes | Screen orientation. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the screen orientation is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -screenClass.setOrientation(screen.Orientation.VERTICAL, (err, data) => { - if (err.code) { - console.error('Failed to setOrientation VERTICAL. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting Orientation VERTICAL. data: ' + JSON.stringify(data)); -}) +try { + screenClass.setOrientation(screen.Orientation.VERTICAL, (err, data) => { + if (err.code) { + console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the vertical orientation. data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(exception)); +}; ``` + ### setOrientation + setOrientation(orientation: Orientation): Promise<void> Sets the screen orientation. This API uses a promise to return the result. @@ -575,20 +795,36 @@ Sets the screen orientation. This API uses a promise to return the result. | orientation | [Orientation](#orientation) | Yes | Screen orientation.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -let promise = screenClass.setOrientation(screen.Orientation.VERTICAL); -promise.then((data) => { - console.info('Succeeded in setting Orientation VERTICAL. Data: ' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to set Orientation VERTICAL. Cause: ' + JSON.stringify(err)); -}) +try { + let promise = screenClass.setOrientation(screen.Orientation.VERTICAL); + promise.then((data) => { + console.info('Succeeded in setting the vertical orientation. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set the vertical orientation. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the vertical orientation. Code: ' + JSON.stringify(exception)); +}; ``` + ### setScreenActiveMode + setScreenActiveMode(modeIndex: number, callback: AsyncCallback<void>): void Sets the active mode of the screen. This API uses an asynchronous callback to return the result. @@ -600,19 +836,33 @@ Sets the active mode of the screen. This API uses an asynchronous callback to re | modeIndex | number | Yes | Index of the mode to set. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the active mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** ```js -var modeIndex = 0; -screenClass.setScreenActiveMode(modeIndex, (err, data) => { - if (err.code) { - console.error('Failed to set ScreenActiveMode 0. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting ScreenActiveMode 0. data: ' + JSON.stringify(data)); -}) +let modeIndex = 0; +try { + screenClass.setScreenActiveMode(modeIndex, (err, data) => { + if (err.code) { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting screen active mode 0. data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(exception)); +}; ``` + ### setScreenActiveMode + setScreenActiveMode(modeIndex: number): Promise<void> Sets the active mode of the screen. This API uses a promise to return the result. @@ -629,18 +879,32 @@ Sets the active mode of the screen. This API uses a promise to return the result | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -var modeIndex = 0; -let promise = screenClass.setScreenActiveMode(modeIndex); -promise.then((data) => { - console.info('Succeeded in setting ScreenActiveMode 0. Data: ' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to set ScreenActiveMode 0. Cause: ' + JSON.stringify(err)); -}) +let modeIndex = 0; +try { + let promise = screenClass.setScreenActiveMode(modeIndex); + promise.then((data) => { + console.info('Succeeded in setting screen active mode 0. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set screen active mode 0. Code: ' + JSON.stringify(exception)); +}; ``` ### setDensityDpi + setDensityDpi(densityDpi: number, callback: AsyncCallback<void>): void; Sets the pixel density of the screen. This API uses an asynchronous callback to return the result. @@ -652,19 +916,33 @@ Sets the pixel density of the screen. This API uses an asynchronous callback to | densityDpi | number | Yes | Pixel density. The value ranges from 80 to 640. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. If the pixel density is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -var densityDpi = 320; -screenClass.setDensityDpi(densityDpi, (err, data) => { - if (err.code) { - console.error('Failed to set DensityDpi 320. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeed in setting DensityDpi 320. data: ' + JSON.stringify(data)); -}) +let densityDpi = 320; +try { + screenClass.setDensityDpi(densityDpi, (err, data) => { + if (err.code) { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeed in setting the pixel density of the screen to 320. data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(exception)); +}; ``` ### setDensityDpi + setDensityDpi(densityDpi: number): Promise<void> Sets the pixel density of the screen. This API uses a promise to return the result. @@ -681,18 +959,32 @@ Sets the pixel density of the screen. This API uses a promise to return the resu | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Display Error Codes](../errorcodes/errorcode-display.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1400003 | This display manager service works abnormally. | + **Example** + ```js -var densityDpi = 320; -var promise = screenClass.setDensityDpi(densityDpi); -promise.then((data) => { - console.info('Succeeded in setting DensityDpi 320. Data: ' + JSON.stringify(data)); -}).catch((err) => { - console.error('Failed to set DensityDpi 320. Cause: ' + JSON.stringify(err)); -}) +let densityDpi = 320; +try { + let promise = screenClass.setDensityDpi(densityDpi); + promise.then((data) => { + console.info('Succeeded in setting the pixel density of the screen to 320. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the pixel density of the screen to 320. Code: ' + JSON.stringify(exception)); +}; ``` ## Orientation + Enumerates the screen orientations. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -706,6 +998,7 @@ Enumerates the screen orientations. | REVERSE_HORIZONTAL | 4 | Reverse horizontal. | ## ScreenModeInfo + Defines the screen mode information. **System capability**: SystemCapability.WindowManager.WindowManager.Core diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 550b62ed355d0a09eb57d17c5473c37cd7e45899..0e8b04295567caf1a018a9f9d3c8122b7f89e41d 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -73,7 +73,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async **Example** ```js - var screenshotOptions = { + let screenshotOptions = { "screenRect": { "left": 200, "top": 100, @@ -85,14 +85,18 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async "rotation": 0, "displayId": 0 }; - screenshot.save(screenshotOptions, (err, pixelMap) => { - if (err) { - console.log('Failed to save screenshot: ' + JSON.stringify(err)); - return; - } - console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. - }); + try { + screenshot.save(screenshotOptions, (err, pixelMap) => { + if (err) { + console.log('Failed to save screenshot. Code: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. + }); + } catch (exception) { + console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception)); + }; ``` ## screenshot.save @@ -114,14 +118,18 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses an async **Example** ```js - screenshot.save((err, pixelMap) => { - if (err) { - console.log('Failed to save screenshot: ' + JSON.stringify(err)); - return; - } - console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. - }); + try { + screenshot.save((err, pixelMap) => { + if (err) { + console.log('Failed to save screenshot. Code: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. + }); + } catch (exception) { + console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception)); + }; ``` ## screenshot.save @@ -149,7 +157,7 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis **Example** ```js - var screenshotOptions = { + let screenshotOptions = { "screenRect": { "left": 200, "top": 100, @@ -161,11 +169,15 @@ Takes a screenshot and saves it as a **PixelMap** object. This API uses a promis "rotation": 0, "displayId": 0 }; - let promise = screenshot.save(screenshotOptions); - promise.then((pixelMap) => { - console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. - }).catch((err) => { - console.log('Failed to save screenshot: ' + JSON.stringify(err)); - }); + try { + let promise = screenshot.save(screenshotOptions); + promise.then((pixelMap) => { + console.log('Succeeded in saving sreenshot. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. + }).catch((err) => { + console.log('Failed to save screenshot. Code: ' + JSON.stringify(err)); + }); + } catch (exception) { + console.error('Failed to save screenshot. Code: ' + JSON.stringify(exception)); + }; ``` diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 7df95d23175b36a0e4aefa65ea0b04c1862a2c94..dd9d9e38aeaf04f38f38b12db89bc48888b70d7f 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -44,7 +44,7 @@ Subscribes to data of the acceleration sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -84,7 +84,7 @@ Subscribes to data of the uncalibrated acceleration sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -125,7 +125,7 @@ Subscribes to data of the ambient light sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -161,7 +161,7 @@ Subscribes to data of the ambient temperature sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -197,7 +197,7 @@ Subscribes to data of the barometer sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -233,7 +233,7 @@ Subscribes to data of the gravity sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -273,7 +273,7 @@ Subscribes to data of the gyroscope sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -314,7 +314,7 @@ Subscribes to data of the uncalibrated gyroscope sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -355,7 +355,7 @@ Subscribes to data of the Hall effect sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -393,7 +393,7 @@ Subscribes to data of the heart rate sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -429,7 +429,7 @@ Subscribes to data of the humidity sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -447,7 +447,7 @@ try { } ``` -### LINEAR_ACCELERATION9+ +### LINEAR_ACCELEROMETER9+ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>, options?: Options): void @@ -468,7 +468,7 @@ Subscribes to data of the linear acceleration sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -506,7 +506,7 @@ Subscribes to data of the magnetic field sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -544,7 +544,7 @@ Subscribes to data of the uncalibrated magnetic field sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -577,7 +577,7 @@ Subscribes to data of the orientation sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -617,7 +617,7 @@ Subscribes to data of the pedometer sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -664,7 +664,7 @@ Subscribe to data of the pedometer detection sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -700,7 +700,7 @@ Subscribes to data of the proximity sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -737,7 +737,7 @@ Subscribes to data of the rotation vector sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -777,7 +777,7 @@ Subscribes to data of the significant motion sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -814,7 +814,7 @@ Subscribes to data of the wear detection sensor. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -853,7 +853,7 @@ Subscribes to data of the acceleration sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -893,7 +893,7 @@ Subscribes to data of the uncalibrated acceleration sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -934,7 +934,7 @@ Subscribes to data of the ambient light sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -970,7 +970,7 @@ Subscribes to data of the ambient temperature sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1006,7 +1006,7 @@ Subscribes to data of the barometer sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1042,7 +1042,7 @@ Subscribes to data of the gravity sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1082,7 +1082,7 @@ Subscribes to data of the gyroscope sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1122,7 +1122,7 @@ Subscribes to data of the uncalibrated gyroscope sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1163,7 +1163,7 @@ Subscribes to data of the Hall effect sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1201,7 +1201,7 @@ Subscribes to data of the heart rate sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1237,7 +1237,7 @@ Subscribes to data of the humidity sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1256,7 +1256,7 @@ try { } ``` -### LINEAR_ACCELERATION9+ +### LINEAR_ACCELEROMETER9+ once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>): void @@ -1275,7 +1275,7 @@ Subscribes to data of the linear acceleration sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1313,7 +1313,7 @@ Subscribes to data of the magnetic field sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1351,7 +1351,7 @@ Subscribes to data of the uncalibrated magnetic field sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1392,7 +1392,7 @@ Subscribes to data of the orientation sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1432,7 +1432,7 @@ Subscribes to data of the pedometer sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1470,7 +1470,7 @@ Subscribe to data of the pedometer detection sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1506,7 +1506,7 @@ Subscribes to data of the proximity sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1542,7 +1542,7 @@ Subscribes to data of the rotation vector sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1581,7 +1581,7 @@ Subscribes to data of the significant motion sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -1617,7 +1617,7 @@ Subscribes to data of the wear detection sensor once. **Error code** -For details about the following error codes, see [Error Codes of ohos.sensor](../errorcodes/errorcode-sensor.md). +For details about the following error codes, see [Sensor Error Codes](../errorcodes/errorcode-sensor.md). | Error Code ID| Error Message | | -------- | ------------------ | @@ -3652,37 +3652,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.LI | 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 @@ -3704,7 +3673,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.AC | 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); @@ -3737,7 +3705,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GR | 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); @@ -3769,7 +3736,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GY | 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); @@ -3801,7 +3767,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.GY | 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); @@ -3834,7 +3799,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.SI | 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); @@ -3864,7 +3828,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PE | 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); @@ -3894,7 +3857,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PE | 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); @@ -3929,7 +3891,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.AM }, {interval: 10000000} ); - ``` ### MAGNETIC_FIELD(deprecated) @@ -3960,7 +3921,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA }, {interval: 10000000} ); - ``` ### MAGNETIC_FIELD_UNCALIBRATED(deprecated) @@ -3982,7 +3942,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA | 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); @@ -3994,7 +3953,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.MA }, {interval: 10000000} ); - ``` ### PROXIMITY(deprecated) @@ -4016,14 +3974,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.PR | 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) @@ -4052,7 +4008,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HU }, {interval: 10000000} ); - ``` ### BAROMETER(deprecated) @@ -4081,7 +4036,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.BA }, {interval: 10000000} ); - ``` ### HALL(deprecated) @@ -4103,14 +4057,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HA | 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) @@ -4160,7 +4112,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.OR | 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); @@ -4169,7 +4120,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.OR }, {interval: 10000000} ); - ``` ### HEART_RATE(deprecated) @@ -4178,7 +4128,7 @@ on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateRe 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. +This API is deprecated since API version 9. You are advised to use [sensor.on.HEART_RATE](#heart_rate9) instead. **Required permissions**: ohos.permission.HEALTH_DATA @@ -4191,35 +4141,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.HE | 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 @@ -4239,7 +4160,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.RO | 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); @@ -4270,14 +4190,12 @@ This API is deprecated since API version 9. You are advised to use [sensor.on.WE | 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) @@ -4302,7 +4220,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4310,7 +4227,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Z-coordinate component: ' + data.z); } ); - ``` ### LINEAR_ACCELERATION(deprecated) @@ -4319,7 +4235,7 @@ once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Li 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. +This API is deprecated since API version 9. You are advised to use [sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9-1) instead. **Required permissions**: ohos.permission.ACCELERATION @@ -4332,35 +4248,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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 @@ -4381,7 +4268,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4392,7 +4278,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Z-coordinate bias: ' + data.biasZ); } ); - ``` ### GRAVITY(deprecated) @@ -4413,7 +4298,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4421,7 +4305,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Z-coordinate component: ' + data.z); } ); - ``` ### GYROSCOPE(deprecated) @@ -4444,7 +4327,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4452,7 +4334,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Z-coordinate component: ' + data.z); } ); - ``` ### GYROSCOPE_UNCALIBRATED(deprecated) @@ -4475,7 +4356,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4486,7 +4366,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Z-coordinate bias: ' + data.biasZ); } ); - ``` ### SIGNIFICANT_MOTION(deprecated) @@ -4507,13 +4386,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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) @@ -4536,13 +4413,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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) @@ -4565,7 +4440,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4591,13 +4465,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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) @@ -4618,7 +4490,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4626,7 +4497,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Z-coordinate component: ' + data.z); } ); - ``` ### MAGNETIC_FIELD_UNCALIBRATED(deprecated) @@ -4647,7 +4517,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4658,7 +4527,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Z-coordinate bias: ' + data.biasZ); } ); - ``` ### PROXIMITY(deprecated) @@ -4679,7 +4547,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4705,13 +4572,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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) @@ -4732,13 +4597,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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) @@ -4759,13 +4622,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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) @@ -4792,7 +4653,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info(' Illumination: ' + data.intensity); } ); - ``` ### ORIENTATION(deprecated) @@ -4813,7 +4673,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4821,7 +4680,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('The device rotates at an angle around the Z axis: ' + data.alpha); } ); - ``` ### ROTATION_VECTOR(deprecated) @@ -4842,7 +4700,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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); @@ -4851,7 +4708,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. console.info('Scalar quantity: ' + data.w); } ); - ``` ### HEART_RATE(deprecated) @@ -4860,7 +4716,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRate 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. +This API is deprecated since API version 9. You are advised to use [sensor.once.HEART_RATE](#heart_rate9-1) instead. **Required permissions**: ohos.permission.HEART_RATE @@ -4873,33 +4729,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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 @@ -4918,13 +4747,11 @@ This API is deprecated since API version 9. You are advised to use [sensor.once. | 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) @@ -4957,7 +4784,6 @@ function callback(data) { console.info('Z-coordinate component: ' + data.z); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER, callback); - ``` ### ACCELEROMETER_UNCALIBRATED(deprecated) @@ -4991,7 +4817,6 @@ function callback(data) { console.info('Z-coordinate bias: ' + data.biasZ); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED, callback); - ``` ### AMBIENT_LIGHT(deprecated) @@ -5018,7 +4843,6 @@ function callback(data) { console.info(' Illumination: ' + data.intensity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_LIGHT, callback); - ``` ### AMBIENT_TEMPERATURE(deprecated) @@ -5045,7 +4869,6 @@ function callback(data) { console.info('Temperature: ' + data.temperature); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_AMBIENT_TEMPERATURE, callback); - ``` ### BAROMETER(deprecated) @@ -5130,7 +4953,6 @@ function callback(data) { console.info('Z-coordinate component: ' + data.z); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE, callback); - ``` ### GYROSCOPE_UNCALIBRATED(deprecated) @@ -5161,7 +4983,6 @@ function callback(data) { console.info('Z-coordinate component: ' + data.z); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_GYROSCOPE_UNCALIBRATED, callback); - ``` ### HALL(deprecated) @@ -5188,7 +5009,6 @@ function callback(data) { console.info('Status: ' + data.status); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HALL, callback); - ``` ### HEART_RATE(deprecated) @@ -5197,7 +5017,7 @@ off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRate 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. +This API is deprecated since API version 9. You are advised to use [sensor.off.HEART_RATE](#heart_rate9-2) instead. **Required permissions**: ohos.permission.HEALTH_DATA @@ -5210,33 +5030,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.off.H | 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 @@ -5261,7 +5054,6 @@ function callback(data) { console.info('Humidity: ' + data.humidity); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HUMIDITY, callback); - ``` ### LINEAR_ACCELERATION(deprecated) @@ -5270,7 +5062,7 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback< 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. +This API is deprecated since API version 9. You are advised to use [sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9-2) instead. **Required permissions**: ohos.permission.ACCELEROMETER @@ -5283,35 +5075,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.off.L | 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 @@ -5338,7 +5101,6 @@ function callback(data) { console.info('Z-coordinate component: ' + data.z); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback); - ``` ### MAGNETIC_FIELD_UNCALIBRATED(deprecated) @@ -5370,7 +5132,6 @@ function callback(data) { console.info('Z-coordinate bias: ' + data.biasZ); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD_UNCALIBRATED, callback); - ``` ### ORIENTATION(deprecated) @@ -5399,7 +5160,6 @@ function callback(data) { 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) @@ -5428,7 +5188,6 @@ function callback(data) { console.info('Steps: ' + data.steps); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_PEDOMETER, callback); - ``` ### PEDOMETER_DETECTION(deprecated) @@ -5512,7 +5271,6 @@ function callback(data) { console.info('Scalar quantity: ' + data.w); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR, callback); - ``` ### SIGNIFICANT_MOTION(deprecated) @@ -5539,7 +5297,6 @@ function callback(data) { console.info('Scalar data: ' + data.scalar); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_SIGNIFICANT_MOTION, callback); - ``` ### WEAR_DETECTION(deprecated) @@ -5566,7 +5323,6 @@ function accCallback(data) { console.info('Wear status: ' + data.value); } sensor.off(sensor.SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, accCallback); - ``` ## sensor.transformCoordinateSystem(deprecated) @@ -5600,9 +5356,7 @@ sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x:2, y:3}, functi console.info("transformCoordinateSystem data[ " + i + "] = " + data[i]); } }) - ``` - ## sensor.transformCoordinateSystem(deprecated) transformCoordinateSystem(inRotationVector: Array<number>, coordinates: CoordinatesOptions): Promise<Array<number>> @@ -5638,7 +5392,6 @@ const promise = sensor.transformCoordinateSystem([1, 0, 0, 0, 1, 0, 0, 0, 1], {x }).catch((err) => { console.info("Operation failed"); }) - ``` ## sensor.getGeomagneticField(deprecated) @@ -5660,7 +5413,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe | 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) { @@ -5671,9 +5423,7 @@ sensor.getGeomagneticField({latitude:80, longitude:0, altitude:0}, 1580486400000 data.z + ',geomagneticDip: ' + data.geomagneticDip + ',deflectionAngle: ' + data.deflectionAngle + ',levelIntensity: ' + data.levelIntensity + ',totalIntensity: ' + data.totalIntensity); }); - ``` - ## sensor.getGeomagneticField(deprecated) getGeomagneticField(locationOptions: LocationOptions, timeMillis: number): Promise<GeomagneticResponse> @@ -5698,7 +5448,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe | 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) => { @@ -5708,7 +5457,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getGe }).catch((reason) => { console.info('Operation failed.'); }) - ``` ## sensor.getAltitude(deprecated) @@ -5740,7 +5488,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getDe } console.info("Successed to get getAltitude interface get data: " + data); }); - ``` ## sensor.getAltitude(deprecated) @@ -5775,7 +5522,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getDe }).catch((err) => { console.error("Operation failed"); }) - ``` @@ -5873,7 +5619,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getAn console.info("data[" + i + "]: " + data[i]); } }) - ``` @@ -5945,7 +5690,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo console.info("data[" + i + "]: " + data[i]); } }) - ``` @@ -5983,7 +5727,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo }).catch((reason) => { console.info("promise::catch", reason); }) - ``` @@ -6017,7 +5760,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getQu console.info("data[" + i + "]: " + data[i]); } }) - ``` @@ -6089,7 +5831,6 @@ This API is deprecated since API version 9. You are advised to use [sensor.getOr console.info("sensor_getDirection_callback" + data[i]); } }) - ``` @@ -6194,5 +5935,3 @@ This API is deprecated since API version 9. You are advised to use [sensor.getRo 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 6622b4b719e95f2c87af19653fbf8a89905239f2..206ad668b6dbdaf8f12d74423a92c5d6ebaf2853 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -689,7 +689,7 @@ promise.then(data => { ## sim.**setShowName**8+ -setShowName\(slotId: number, name: string,callback: AsyncCallback\): void +setShowName\(slotId: number, name: string, callback: AsyncCallback\): void Sets a display name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -710,7 +710,7 @@ Sets a display name for the SIM card in the specified slot. This API uses an asy **Example** ```js -let name = 'China Mobile'; +let name = "China Mobile"; sim.setShowName(0, name, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); @@ -744,7 +744,7 @@ Sets a display name for the SIM card in the specified slot. This API uses a prom **Example** ```js -let name = 'China Mobile'; +let name = "China Mobile"; let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); @@ -818,7 +818,7 @@ promise.then(data => { ## sim.**setShowNumber**8+ -setShowNumber\(slotId: number, number: string,callback: AsyncCallback\): void +setShowNumber\(slotId: number, number: string, callback: AsyncCallback\): void Sets a display number for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -848,7 +848,7 @@ sim.setShowNumber(0, number, (err, data) => { ## sim.**setShowNumber**8+ -setShowNumber\(slotId: number,number: string\): Promise\ +setShowNumber\(slotId: number, number: string\): Promise\ Sets a display number for the SIM card in the specified slot. This API uses a promise to return the result. @@ -885,7 +885,7 @@ promise.then(data => { ## sim.**getShowNumber**8+ -getShowNumber(slotId: number,callback: AsyncCallback): void +getShowNumber(slotId: number, callback: AsyncCallback): void Obtains the display number of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1097,7 +1097,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses an asy ```js let lockInfo = { lockType: sim.LockType.PIN_LOCK, - password = "1234", + password: "1234", state: sim.LockState.LOCK_OFF }; sim.setLockState(0, lockInfo, (err, data) => { @@ -1136,7 +1136,7 @@ Sets the lock status of the SIM card in the specified slot. This API uses a prom ```js let lockInfo = { lockType: sim.LockType.PIN_LOCK, - password = "1234", + password: "1234", state: sim.LockState.LOCK_OFF }; let promise = sim.setLockState(0, lockInfo); @@ -1344,7 +1344,7 @@ promise.then(data => { ## sim.**unlockPin**7+ -unlockPin(slotId: number,pin: string ,callback: AsyncCallback): void +unlockPin(slotId: number, pin: string, callback: AsyncCallback): void Unlocks PIN of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1374,7 +1374,7 @@ sim.unlockPin(0, pin, (err, data) => { ## sim.**unlockPin**7+ -unlockPin(slotId: number,pin: string): Promise<LockStatusResponse\> +unlockPin(slotId: number, pin: string): Promise<LockStatusResponse\> Unlocks the PIN of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1411,7 +1411,7 @@ promise.then(data => { ## sim.**unlockPuk**7+ -unlockPuk(slotId: number,newPin: string,puk: string ,callback: AsyncCallback): void +unlockPuk(slotId: number, newPin: string, puk: string ,callback: AsyncCallback): void Unlocks the PUK of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1443,7 +1443,7 @@ sim.unlockPuk(0, newPin, puk, (err, data) => { ## sim.**unlockPuk**7+ -unlockPuk(slotId: number,newPin: string,puk: string): Promise<LockStatusResponse\> +unlockPuk(slotId: number, newPin: string, puk: string): Promise<LockStatusResponse\> Unlocks the PUK of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1482,7 +1482,7 @@ promise.then(data => { ## sim.**unlockPin**28+ -unlockPin2(slotId: number,pin2: string ,callback: AsyncCallback): void +unlockPin2(slotId: number, pin2: string, callback: AsyncCallback): void Unlocks PIN 2 of the SIM card in the specified slot. This API uses an asynchronous callback to return the result. @@ -1512,7 +1512,7 @@ sim.unlockPin2(0, pin2, (err, data) => { ## sim.**unlockPin**28+ -unlockPin2(slotId: number,pin2: string): Promise<LockStatusResponse\> +unlockPin2(slotId: number, pin2: string): Promise<LockStatusResponse\> Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to return the result. @@ -1539,7 +1539,7 @@ Unlocks PIN 2 of the SIM card in the specified slot. This API uses a promise to ```js let pin2='1234'; -let promise = sim.unlockPin2(0,pin2); +let promise = sim.unlockPin2(0, pin2); promise.then(data => { console.log(`unlockPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1851,7 +1851,7 @@ Sets voice mailbox information for the SIM card in the specified slot. This API **Example** ```js -sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com" , (err, data) => { +sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com", (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -2602,8 +2602,8 @@ Unlocks the SIM card in the specified slot. This API uses an asynchronous callba ```js let persoLockInfo = { - lockType = sim.PersoLockType.PN_PIN_LOCK, - password = "1234" + lockType: sim.PersoLockType.PN_PIN_LOCK, + password: "1234" }; sim.unlockSimLock(0, persoLockInfo, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -2640,8 +2640,8 @@ Unlocks the SIM card in the specified slot. This API uses a promise to return th ```js let persoLockInfo = { - lockType = sim.PersoLockType.PN_PIN_LOCK, - password = "1234" + lockType: sim.PersoLockType.PN_PIN_LOCK, + password: "1234" }; let promise = sim.unlockSimLock(0, persoLockInfo); promise.then(data => { diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 6920c9dbf3aea204efb78c292e949a7ec0e4a053..7d372978202503f6ed0a0517fa69f85ae5dfcf44 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -160,7 +160,7 @@ promise.then(data => { ## sms.setDefaultSmsSlotId7+ -setDefaultSmsSlotId\(slotId: number,callback: AsyncCallback<void>\): void +setDefaultSmsSlotId\(slotId: number, callback: AsyncCallback<void>\): void Sets the default slot of the SIM card used to send SMS messages. This API uses an asynchronous callback to return the result. @@ -180,7 +180,7 @@ Sets the default slot of the SIM card used to send SMS messages. This API uses a **Example** ```js -sms.setDefaultSmsSlotId(0,(err, data) => { +sms.setDefaultSmsSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -610,8 +610,8 @@ let updateSimMessageOptions = { slotId: 0, msgIndex: 1, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, - pdu = "xxxxxxx", - smsc = "test" + pdu: "xxxxxxx", + smsc: "test" }; sms.updateSimMessage(updateSimMessageOptions, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -650,8 +650,8 @@ let updateSimMessageOptions = { slotId: 0, msgIndex: 1, newStatus: sms.SimMessageStatus.SIM_MESSAGE_STATUS_FREE, - pdu = "xxxxxxx", - smsc = "test" + pdu: "xxxxxxx", + smsc: "test" }; let promise = sms.updateSimMessage(updateSimMessageOptions); promise.then(data => { @@ -1054,13 +1054,13 @@ Encodes MMS messages. This API uses an asynchronous callback to return the resul ```js let mmsAcknowledgeInd = { - transactionId = "100", - version = 0x10, - reportAllowed = 128 + transactionId: "100", + version: sms.MmsVersionType.MMS_VERSION_1_0, + reportAllowed: sms.ReportType.MMS_YES }; let mmsInformation = { - messageType = 133, - mmsType = mmsAcknowledgeInd + messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, + mmsType: mmsAcknowledgeInd }; sms.encodeMms(mmsInformation, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -1096,10 +1096,10 @@ Encodes MMS messages. This API uses a promise to return the result. let mmsAcknowledgeInd = { transactionId: "100", version: sms.MmsVersionType.MMS_VERSION_1_0, - reportAllowed = sms.ReportType.MMS_YES + reportAllowed: sms.ReportType.MMS_YES }; let mmsInformation = { - messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, + messageType: sms.MessageType.TYPE_MMS_ACKNOWLEDGE_IND, mmsType: mmsAcknowledgeInd }; let promise = sms.encodeMms(mmsInformation); 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 10f08e3b588e7c03d44ef3eac6ade39a42a5febe..d646fd424d8f7fa6c431a388879e9cf63678a632 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** @@ -52,7 +52,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getTotalSizeOfVolume -getTotalSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void +getTotalSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): void Asynchronously obtains the total size of the specified volume. This API uses a callback to return the result. @@ -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** @@ -121,7 +121,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getFreeSizeOfVolume -getFreeSizeOfVolume(volumeUuid: string, callback:AsyncCallback<number>):void +getFreeSizeOfVolume(volumeUuid: string, callback: AsyncCallback<number>): void Asynchronously obtains the available space of the specified volume. This API uses a callback to return the result. @@ -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** @@ -424,7 +424,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getSystemSize9+ -getSystemSize(callback:AsyncCallback<number>):void +getSystemSize(callback: AsyncCallback<number>): void Asynchronously obtains the system space. This API uses a callback to return the result. @@ -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](#storagestats9)> | Promise used to return the information obtained.| + | Type | Description | + | --------------------- | ---------------- | + | Promise<[StorageStats](#storagestats)> | Promise used to return the information obtained.| **Example** @@ -490,7 +490,7 @@ This is a system API and cannot be called by third-party applications. ## storageStatistics.getUserStorageStats9+ -getUserStorageStats(userId: number, callback:AsyncCallback<StorageStats>):void +getUserStorageStats(userId: number, callback: AsyncCallback<StorageStats>): void Asynchronously obtains the space occupied by each type of user data. This API uses a callback to return the result. @@ -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](#storagestats9)> | 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](#storagestats)> | Yes | Callback invoked to return the information obtained.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md index 82be7501dfcef800ba7bd6db6fc9e3759ac05bfa..6812d87828d55851d375eadba9dab6b2de55560a 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -9,13 +9,57 @@ ```js -import cipher from '@system.cipher' +import cipher from '@system.cipher'; ``` +## CipherResponse + +Defines the response to the cipher interface called. + +**System capability**: SystemCapability.Security.Cipher + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| text | string | Yes | Response content.| + +## CipherRsaOptions + +Defines the input parameters of **cipher.rsa()**. + +**System capability**: SystemCapability.Security.Cipher + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.| +| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes | RSA key. It is a public key in encryption and a private key in decryption. | +| transformation | string | No | RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| +| success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. | +| fail | (data: string, code: number) => void | No | Called when data fails to be encrypted or decrypted. | +| complete | () => void | No | Called when the execution is complete. | + +## CipherAesOptions + +Defines the input parameters of **cipher.aes()**. + +**System capability**: SystemCapability.Security.Cipher + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.| +| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.| +| key | string | Yes | Key used for encryption or decryption. It is a Base64 encoded string.| +| transformation | string | No | Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**. | +| iv | string | No | Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| +| ivOffset | string | No | Offset of the IV for AES-based encryption and decryption. The default value is **0**, which is the only value supported. | +| ivLen | string | No | Length of the IV, in bytes. This field is reserved. The default value is **16**, which is the only value supported.| +| success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. | +| fail | (data: string, code: number) => void | No | Called when data fails to be encrypted or decrypted. | +| complete | () => void | No | Called when the execution is complete. | ## cipher.rsa -rsa(Object): void +rsa(options: CipherRsaOptions): void Encrypts or decrypts data using RSA. @@ -25,13 +69,7 @@ Encrypts or decrypts data using RSA. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt | -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text that meets the following requirement:
Maximum text length = Key length/8 - 66
For example, if the key is of 1024 bytes, the text to be encrypted cannot exceed 62 bytes (1024/8 -66 = 62).
The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| -| key | string | Yes| RSA key. The key is used as a public key in encryption and a private key in decryption.| -| transformation | string | No| RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.| -| success | Function | No| Called when data is encrypted or decrypted successfully.| -| fail | Function | No| Called when data fails to be encrypted or decrypted.| -| complete | Function | No| Called when the execution is complete.| +| options | [CipherRsaOptions](#cipherrsaoptions) | Yes| Parameters set for RSA encryption or decryption.| **Example** @@ -53,7 +91,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); @@ -86,7 +124,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); @@ -99,7 +137,7 @@ export default { ## cipher.aes -aes(Object): void +aes(options: CipherAesOptions): void Encrypts or decrypts data using AES. @@ -109,16 +147,7 @@ Encrypts or decrypts data using AES. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | string | Yes| Action to perform. The options are as follows:
- encrypt
- decrypt | -| text | string | Yes| Text to be encrypted or decrypted.
The text to be encrypted must be common text. The text to be decrypted must be binary text encoded in Base64. The default format is used for Base64 encoding.| -| key | string | Yes| Key used for encryption or decryption. It is a string encoded in Base64.| -| transformation | string | No| Encryption mode and padding of the AES algorithm. The default value is **AES/CBC/PKCS5Padding**.| -| iv | string | No| Initialization vector (IV) for AES-based encryption and decryption. The value is a string encoded in Base64. The default value is the key value.| -| ivOffset | string | No| Offset of the IV for AES-based encryption and decryption. The default value is **0**, which is the only value supported.| -| ivLen | string | No| Length of the IV, in bytes. This field is reserved. The default value is **16**, which is the only value supported.| -| success | Function | No| Called when data is encrypted or decrypted successfully.| -| fail | Function | No| Called when data fails to be encrypted or decrypted.| -| complete | Function | No| Called when the execution is complete.| +| options | [CipherAesOptions](#cipheraesoptions) | Yes| Parameters set for AES encryption or decryption.| **Example** @@ -139,7 +168,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to encrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.rsa encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); @@ -159,7 +188,7 @@ export default { console.log(`Handling successful:${data.text}`); }, fail: function(data, code) { - console.log(`### Failed to decrypt cipher.rsa ### ${code}:${data}`); + console.log(`### cipher.aes encryption failed ### ${code}:${data}`); }, complete: function() { console.log(`operation complete!`); diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md index f3a29a9cc683fecc38b4c935af7607bd2a5415b8..a8ea022b24881bd1def701d3c59433270b0da762 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -88,7 +88,7 @@ console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) ## data.setDefaultCellularDataSlotId -setDefaultCellularDataSlotId(slotId: number,callback: AsyncCallback\): void +setDefaultCellularDataSlotId(slotId: number, callback: AsyncCallback\): void Sets the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result. @@ -108,7 +108,7 @@ This is a system API. **Example** ```js -data.setDefaultCellularDataSlotId(0,(err, data) => { +data.setDefaultCellularDataSlotId(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -313,7 +313,7 @@ Checks whether the cellular data roaming service is enabled. This API uses an as **Example** ```js -data.isCellularDataRoamingEnabled(0,(err, data) => { +data.isCellularDataRoamingEnabled(0, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` 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-userfilemanager.md b/en/application-dev/reference/apis/js-apis-userfilemanager.md new file mode 100644 index 0000000000000000000000000000000000000000..77805c1c54764ae6c9fdc2498fbead88db696a84 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-userfilemanager.md @@ -0,0 +1,2520 @@ +# User Data Management + +> **NOTE**
+> This module is supported since API Version 9. Updates will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import userFileManager from '@ohos.filemanagement.userfile_manager'; +``` + +## userFileManager.getUserFileMgr + +getUserFileMgr(context: Context): UserFileManager + +Obtains a **UserFileManager** instance. This instance can be used to access and modify user media data (such as audio and video files, images, and documents). + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | -------------------------- | +| context | [Context](#../apis/js-apis-Context.md) | Yes | Context of the ability instance.| + +**Return value** + +| Type | Description | +| ----------------------------- | :---- | +| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| + +**Example** + +```ts +const context = getContext(this); +let userFileMgr = userfilemanager.getUserFileMgr(context); +``` + +## userFileManager.getUserFileMgr + +getUserFileMgr(): UserFileManager + +Obtains a **UserFileManager** instance.This instance can be used to access and modify user media data (such as audio and video clips, images, and documents). + +**Model restriction**: This API can be used only in the FA model. + +> **NOTE**
You are advised to use [UserFileManager.getUserFileMgr](#userfilemanagergetuserfilemgr), the API used in the stage model. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ----------------------------- | :--------- | +| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| + +**Example** + +```js +let userFileMgr = userfilemanager.getUserFileMgr(); +``` + +## UserFileManager + +### getPublicDirectory + +getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): void; + +Obtains the preset public directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [DirectoryType](#directorytype) | Yes | Type of the public directory. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the public directory.| + +**Example** + +```ts +async function getPublicDirectoryDemoCallback() { + console.info('getPublicDirectoryDemo'); + let DIR_CAMERA = directoryType.DIR_CAMERA; + console.info('DIR_CAMERA', DIR_CAMERA); + userFileMgr.getPublicDirectory(DIR_CAMERA, (err, dicResult) => { + if (dicResult == 'Camera/') { + console.info('mediaLibraryTest : getPublicDirectory passed'); + } else { + console.info('mediaLibraryTest : getPublicDirectory failed'); + } + }); +} +``` + +### getPublicDirectory + +getPublicDirectory(type: DirectoryType): Promise<string>; + +Obtains the preset public directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------ | +| type | [DirectoryType](#directorytype) | Yes | Type of the public directory.| + +**Return value** + +| Type | Description | +| ---------------- | ---------------- | +| Promise\ | Promise used to return the public directory.| + +**Example** + +```ts +async function getPublicDirectoryDemoPromise() { + console.info('getPublicDirectoryDemo'); + let DIR_CAMERA = directoryType.DIR_CAMERA; + try { + let dicResult = await userFileMgr.getPublicDirectory(DIR_CAMERA); + console.info('mediaLibraryTest : getPublicDirectory passed, result = ', dicResult); + } catch (err) { + console.info('mediaLibraryTest : getPublicDirectory failed, message = ', err); + } +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; + +Obtains file assets. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function getFileAssetsDemoCallback() { + console.info('getFileAssets'); + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE + let fetchOp = { + selections: '', + selectionArgs: [], + }; + + userFileMgr.getFileAssets([imageType, ], fetchOp, async (err, fetchFileResult) => { + if (fetchFileResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchFileResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + }; + } + }) +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; + +Obtains file assets. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ---------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media type to obtain.| +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| + +**Example** + +```ts +async function getFileAssetsDemoPromise() { + console.info('getFileAssets'); + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE + let fetchOp = { + selections: '', + selectionArgs: [], + }; + try { + var fetchFileResult = await userFileMgr.getFileAssets([imageType, ], fetchOp) + } catch (err) { + console.info('getFileAssets failed, message = ', err); + } + + if (fetchFileResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchFileResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + }; + } +} +``` + +### on + +on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void + +Subscribes to changes of the file management library. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Media type to subscribe to.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**fileChange** indicates the file change.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | Yes | Callback that returns no value. | + +**Example** + +```ts +async function onDemo() { + console.info('onDemo') + userFileMgr.on('imageChange', () => { + // Image file changes. Do something. + }); +} +``` + +### off + +off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void + +Unsubscribes from changes of the file management library. This API uses a callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Media type to unsubscribe from.
**deviceChange** indicates the device change.
**albumChange** indicates the album change.
**imageChange** indicates the image change.
**audioChange** indicates the audio file change.
**videoChange** indicates the video file change.
**fileChange** indicates the file change.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | No | Callback that returns no value. | + +**Example** + +```ts +async function offDemo() { + console.info('offDemo') + userFileMgr.off('imageChange', () => { + // stop listening success + }); +} +``` + +### createAsset + +createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void + +Creates a file asset. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------- | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype) | Yes | Media type. | +| displayName | string | Yes | File name to display. | +| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.| +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset created. | + +**Example** + +```ts +async function createAssetDemoCallback() { + console.info('createAssetDemo') + let mediaType = userfile_manager.MediaType.FILE; + let DIR_DOC = directoryType.DIR_DOCUMENTS; + const path = await userFileMgr.getPublicDirectory(DIR_DOC); + userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/', (err, fileAsset) => { + if (err == undefined) { + console.info('createAsset successfully'); + } else { + console.info('createAsset failed, message = ', err); + } + }) +} +``` + +### createAsset + +createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise<FileAsset>; + +Creates a file asset. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------- | ---- | ------------------------------------------------------------ | +| mediaType | [MediaType](#mediatype) | Yes | Media type. | +| displayName | string | Yes | File name to display. | +| relativePath | string | Yes | File path. You can use **getPublicDirectory()** to obtain the paths for different types of files.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset created.| + +**Example** + +```ts +async function createAssetDemoPromise() { + console.info('createAssetDemo') + let mediaType = userfile_manager.MediaType.FILE; + let DIR_DOC = directoryType.DIR_DOCUMENTS; + const path = await userFileMgr.getPublicDirectory(DIR_DOC); + try { + let fileAsset = await userFileMgr.createAsset(mediaType, 'tesfFile.txt', path + 'myDirectory/') + console.info('createAsset successfully'); + } catch (err) { + console.info('createAsset failed, message = ', err); + } +} +``` + +### deleteAsset + +deleteAsset(uri: string, callback: AsyncCallback<void>): void; + +Deletes a file asset. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ---------------------- | +| uri | string | Yes | URI of the file to delete. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the result.| + +**Example** + +```ts +async function deleteAssetDemoCallback() { + console.info('deleteAssetDemo') + let fileKeyObj = userfile_manager.FileKey + let fileType = userfile_manager.MediaType.FILE + let option = { + selections: '', + selectionArgs: [], + }; + try { + const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); + var asset = await fetchFileResult.getFirstObject(); + } catch(err) { + console.info('fetch failed, message =', err) + } + + if (asset == undefined) { + console.error('asset not exist') + return + } + userFileMgr.deleteAsset(asset.uri, (err) => { + if (err == undefined) { + console.info("deleteAsset successfully"); + } else { + console.info("deleteAsset failed with error:"+ err); + } + }); +} +``` + +### deleteAsset + +deleteAsset(uri: string): Promise<void>; + +Deletes a file asset. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| uri | string | Yes | URI of the file to delete.| + +**Return value** + +| Type | Description | +| ---------------- | --------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```ts +async function deleteAssetDemoPromise() { + console.info('deleteAssetDemo') + let fileKeyObj = userfile_manager.FileKey + let fileType = userfile_manager.MediaType.FILE + let option = { + selections: '', + selectionArgs: [], + }; + try { + const fetchFileResult = await userFileMgr.getFileAssets([fileType, ], option); + var asset = await fetchFileResult.getFirstObject(); + } catch(err) { + console.info('fetch failed, message =', err) + } + if (asset == undefined) { + console.error('asset not exist') + return + } + try { + await userFileMgr.deleteAsset(asset.uri); + console.info("deleteAsset successfully"); + } catch (err) { + console.info("deleteAsset failed with error:"+ err); + } +} +``` + +### getAlbums + +getAlbums(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. | +| callback | AsyncCallback<Array<[Album](#album)>> | Yes | Callback invoked to return the album list.| + +**Example** + +```ts +async function getAlbumsDemoCallback() { + console.info('getAlbumsDemo') + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp, (err, albumList) => { + if (albumList != undefined) { + const album = albumList[0]; + console.info('first album.albumName = ' + album.albumName); + console.info('album.count = ' + albumList.length); + } else { + console.info('getAlbum fail, message = ' + err); + } + }) +} +``` + +### getAlbums + +getAlbums(type: Array<MediaType>, options: MediaFetchOptions): Promise>; + +Obtains albums. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | -------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain.| +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the albums. | + +**Return value** + +| Type | Description | +| ------------------------ | -------------------------- | +| Promise> | Promise used to return the album list.| + +**Example** + +```ts +async function getAlbumsDemoPromise() { + console.info('getAlbumsDemo') + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + try { + let albumList = await userFileMgr.getAlbums([userfile_manager.MediaType.IMAGE], AlbumNoArgsfetchOp); + const album = albumList[0]; + console.info('first album.albumName = ' + album.albumName); + console.info('album.count = ' + albumList.length); + } catch (err) { + console.info('getAlbum fail, message = ' + err); + } +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback): void + +Obtains the system album. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------- | +| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain. | +| callback | AsyncCallback> | Yes | Callback invoked to return the system album obtained.| + +**Example** + +```ts +async function getPrivateAlbumDemoCallback() { + console.info('getPrivateAlbumDemo') + userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH, async (err, albumArray) => { + if (err == undefined) { + console.info('getPrivateAlbum ok'); + try { + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); + } catch (err) { + console.info('getFileAssets failed. message = ', err); + } + // Get file count in trash album + let count = fetchResult.getCount(); + console.info('fetchResult count = ', count) + // Get fileAssets in trash album + let trashAsset = await fetchResult.getFirstObject(); + // Get file trashed date + let isTrash = trashAsset.isTrash(); + console.info('is trashed', isTrash) + } else { + console.info('getPrivateAlbum failed. message = ', err); + } + }); +} +``` + +### getPrivateAlbum + +getPrivateAlbum(type: VirtualAlbumType): Promise + +Obtains the system album. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------- | ---- | ------------ | +| type | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain.| + +**Return value** + +| Type | Description | +| ------------------------------- | --------------------------------- | +| Promise> | Promise used to return the system album obtained.| + +**Example** + +```ts +async function getPrivateAlbumDemoPromise() { + console.info('getPrivateAlbumDemo'); + try { + var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); + } catch(err) { + console.info('getPrivateAlbum failed. message = ', err); + } + try { + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + var fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); + } catch (err) { + console.info('getFileAssets failed. message = ', err); + } + // Get file count in trash album + let count = fetchResult.getCount(); + console.info('fetchResult count = ', count) + // Get fileAssets in trash album + let trashAsset = await fetchResult.getFirstObject(); + + // Get file trashed date + let isTrash = trashAsset.isTrash(); + console.info('is trashed', isTrash) +} +``` + +### getActivePeers + +getActivePeers(callback: AsyncCallback>): void; + +Obtains information about online peer devices. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| callback | AsyncCallback> | Yes | Callback invoked to return the online device list.| + +**Example** + +```ts +async function getActivePeersDemoCallback() { + console.info('getActivePeersDemo') + var devicesInfo = userFileMgr.getActivePeers((err, devicesInfo) => { + if (err == undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getActivePeers failed. message = ', err) + } + }); +} +``` + +### getActivePeers + +getActivePeers(): Promise>; + +Obtains information about online peer devices. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Return value** + +| Type | Description | +| --------------------------- | ----------------------------- | +| Promise> | Promise used to return the online device list.| + +**Example** + +```ts +async function getActivePeersDemoPromise() { + console.info('getActivePeersDemo') + try { + var devicesInfo = await userFileMgr.getActivePeers(); + } catch (err) { + console.info('getActivePeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getActivePeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail') + } +} +``` + +### getAllPeers + +getAllPeers(callback: AsyncCallback>): void; + +Obtains information about all peer devices. This API uses an asynchronous callback to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------ | +| callback | AsyncCallback> | Yes | Callback invoked to return the peer device list.| + +**Example** + +```ts +async function getAllPeersDemoCallback() { + console.info('getAllPeersDemo') + var devicesInfo = await userFileMgr.getAllPeers((err, devicesInfo) => { + if (err == undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('getAllPeers failed. message = ', err) + } + }); +} +``` + +### getAllPeers + +getAllPeers(): Promise>; + +Obtains information about all peer devices. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +**Return value** + +| Type | Description | +| --------------------------- | ----------------------------- | +| Promise> | Promise used to return the peer device list.| + +**Example** + +```ts +async function getAllPeersDemoPromise() { + console.info('getAllPeersDemo') + try { + var devicesInfo = await userFileMgr.getAllPeers(); + } catch (err) { + console.info('getAllPeers failed. message = ', err) + } + if (devicesInfo != undefined) { + console.log('getAllPeers succeed.') + for (let i = 0; i < devicesInfo.length; i++) { + console.info('get distributed info ' + devicesInfo[i].deviceName + devicesInfo[i].networkId); + } + } else { + console.info('get distributed fail') + } +} +``` + +### release + +release(callback: AsyncCallback<void>): void + +Releases this **UserFileManager** instance. This API uses an asynchronous callback to return the result. +Call this API when the APIs in the **UserFileManager** instance are no longer used. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | -------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```ts +async function releaseDemoCallback() { + console.info('releaseDemo'); + userFileMgr.release((err) => { + if (err != undefined) { + console.info('release failed. message = ', err); + } else { + console.info('release ok.'); + } + }) +} +``` + +### release + +release(): Promise<void> + +Releases this **UserFileManager** instance. This API uses a promise to return the result. +Call this API when the APIs in the **UserFileManager** instance are no longer used. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | --------------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```ts +async function releaseDemoPromise() { + console.info('releaseDemo'); + try { + await userFileMgr.release(); + console.info('release ok.'); + } catch (err) { + console.info('release failed. message = ', err); + } +} +``` + +## FileAsset + +Provides APIs for encapsulating file asset attributes. + +### Attributes + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------------------------ | ---- | ---- | ------------------------------------------------------ | +| uri | string | Yes | No | File asset URI, for example, **dataability:///media/image/2**. | +| mediaType | [MediaType](#mediatype) | Yes | No | Media type. | +| displayName | string | Yes | Yes | File name, including the file name extension, to display. | + + +### isDirectory + +isDirectory(callback: AsyncCallback<boolean>): void + +Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isDirectory((err, isDirectory) => { + // do something + }); +} +``` + +### isDirectory + +isDirectory():Promise<boolean> + +Checks whether this file asset is a directory. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ---------------------- | ---------------------------- | +| Promise<boolean> | Promise used to return the result. If the file asset is a directory, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isDirectory().then(function(isDirectory){ + console.info("isDirectory result:"+ isDirectory); + }).catch(function(err){ + console.info("isDirectory failed with error:"+ err); + }); +} +``` + +### commitModify + +commitModify(callback: AsyncCallback<void>): void + +Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.title = 'newtitle'; + asset.commitModify(() => { + console.info('commitModify success'); + }); +} +``` + +### commitModify + +commitModify(): Promise<void> + +Commits the modification on the file metadata to the database. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.title = 'newtitle'; + asset.commitModify(); +} +``` + +### open + +open(mode: string, callback: AsyncCallback<number>): void + +Opens this file asset. This API uses an asynchronous callback to return the result. + +**NOTE**
Currently, the write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------------------------- | +| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| +| callback | AsyncCallback<number> | Yes | Callback used to return the file handle. | + +**Example** + +```js +async function example() { + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); + const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); + asset.open('rw', (openError, fd) => { + if(fd > 0){ + asset.close(fd); + }else{ + console.info('File Open Failed!' + openError); + } + }); +} +``` + +### open + +open(mode: string): Promise<number> + +Opens this file asset. This API uses a promise to return the result. + +**NOTE**
Currently, the write operations are mutually exclusive. After a write operation is complete, you must call **close** to release the resource. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.READ_DOCUMENT, ohos.permission.WRITE_MEDIA, ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------------------- | +| mode | string | Yes | File open mode, which can be **r** (read-only), **w** (write-only), or **rw** (read-write).| + +**Return value** + +| Type | Description | +| --------------------- | ------------- | +| Promise<number> | Promise used to return the file handle.| + +**Example** + +```js +async function example() { + let mediaType = mediaLibrary.MediaType.IMAGE; + let DIR_IMAGE = mediaLibrary.DirectoryType.DIR_IMAGE; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const path = await userFileMgr.getPublicDirectory(DIR_IMAGE); + const asset = await userFileMgr.createAsset(mediaType, "image00003.jpg", path); + asset.open('rw') + .then((fd) => { + console.info('File fd!' + fd); + }) + .catch((err) => { + console.info('File err!' + err); + }); +} +``` + +### close + +close(fd: number, callback: AsyncCallback<void>): void + +Closes this file asset. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| fd | number | Yes | File descriptor.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd, (closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); + }); +} +``` + +### close + +close(fd: number): Promise<void> + +Closes this file asset. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----- | +| fd | number | Yes | File descriptor.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.open('rw').then((fd) => { + console.info('File fd!' + fd); + asset.close(fd).then((closeErr) => { + if (closeErr != undefined) { + console.info('mediaLibraryTest : close : FAIL ' + closeErr); + console.info('mediaLibraryTest : ASSET_CALLBACK : FAIL'); + + } else { + console.info("=======asset.close success====>"); + } + }); + }) + .catch((err) => { + console.info('File err!' + err); + }); +} +``` + +### getThumbnail + +getThumbnail(callback: AsyncCallback<image.PixelMap>): void + +Obtains the thumbnail of this file asset. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------- | +| callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail((err, pixelmap) => { + console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }); +} +``` + +### getThumbnail + +getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void + +Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------- | +| size | [Size](#size) | Yes | Size of the thumbnail to obtain. | +| callback | AsyncCallback<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let size = { width: 720, height: 720 }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail(size, (err, pixelmap) => { + console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }); +} +``` + +### getThumbnail + +getThumbnail(size?: Size): Promise<image.PixelMap> + +Obtains the file thumbnail of the given size. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------- | ---- | ----- | +| size | [Size](#size) | No | Size of the thumbnail to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------- | --------------------- | +| Promise<[image.PixelMap](#../apis/js-apis-image.md#pixelmap7)> | Promise used to return the pixel map of the thumbnail.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let size = { width: 720, height: 720 }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.getThumbnail(size) + .then((pixelmap) => { + console.info('mediaLibraryTest : getThumbnail Successfull '+ pixelmap); + }) + .catch((err) => { + console.info('mediaLibraryTest : getThumbnail fail'+ err); + }); +} +``` + +### favorite + +favorite(isFavorite: boolean, callback: AsyncCallback<void>): void + +Favorites or unfavorites this file asset. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ---------------------------------- | +| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.favorite(true,function(err){ + // Do something. + }); +} +``` + +### favorite + +favorite(isFavorite: boolean): Promise<void> + +Favorites or unfavorites this file asset. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ---------------------------------- | +| isFavorite | boolean | Yes | Operation to perform. The value **true** means to favorite the file asset, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.favorite(true).then(function() { + console.info("favorite successfully"); + }).catch(function(err){ + console.info("favorite failed with error:"+ err); + }); +} +``` + +### isFavorite + +isFavorite(callback: AsyncCallback<boolean>): void + +Checks whether this file asset is favorited. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | ----------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isFavorite((err, isFavorite) => { + if (isFavorite) { + console.info('FileAsset is favorite'); + }else{ + console.info('FileAsset is not favorite'); + } + }); +} +``` + +### isFavorite + +isFavorite():Promise<boolean> + +Checks whether this file asset is favorited. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ---------------------- | ------------------ | +| Promise<boolean> | Promise used to return the result. If the file asset is favorited, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isFavorite().then(function(isFavorite){ + console.info("isFavorite result:"+ isFavorite); + }).catch(function(err){ + console.info("isFavorite failed with error:"+ err); + }); +} +``` + +### trash + +trash(isTrash: boolean, callback: AsyncCallback<void>): void + +Moves this file asset to the trash. This API uses an asynchronous callback to return the result. + +Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | --------- | +| isTrash | boolean | Yes | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.trash(true, trashCallBack); + function trashCallBack(err, trash) { + console.info('mediaLibraryTest : ASSET_CALLBACK ASSET_CALLBACK trash'); + } +} +``` + +### trash + +trash(isTrash: boolean): Promise<void> + +Moves this file asset to the trash. This API uses a promise to return the result. + +Files in the trash are not actually deleted. You can set **isTrash** to **false** to restore the files from the trash. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------- | ---- | --------- | +| isTrash | boolean | Yes | Whether to move the file asset to the trash. The value **true** means to move the file asset to the trash, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ---------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.trash(true).then(function() { + console.info("trash successfully"); + }).catch(function(err){ + console.info("trash failed with error:"+ err); + }); +} +``` + +### isTrash + +isTrash(callback: AsyncCallback<boolean>): void + +Checks whether this file asset is in the trash. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | --------------- | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isTrash((err, isTrash) => { + if (isTrash == undefined) { + console.error('Failed to get trash state: ' + err); + return; + } + console.info('Get trash state success: ' + isTrash); + }); +} +``` + +### isTrash + +isTrash():Promise<boolean> + +Checks whether this file asset is in the trash. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise used to return the result. If the file asset is in the trash, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const asset = await fetchFileResult.getFirstObject(); + asset.isTrash().then(function(isTrash){ + console.info("isTrash result: " + isTrash); + }).catch(function(err){ + console.error("isTrash failed with error: " + err); + }); +} +``` + +## FetchFileResult + +Provides APIs to manage the file retrieval result. + +### getCount + +getCount(): number + +Obtains the total number of files in the result set. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------ | -------- | +| number | Total number of files.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let fileType = mediaLibrary.MediaType.FILE; + let getFileCountOneOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [fileType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getFileCountOneOp); + const fetchCount = fetchFileResult.getCount(); +} +``` + +### isAfterLast + +isAfterLast(): boolean + +Checks whether the cursor is in the last row of the result set. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------- | ---------------------------------- | +| boolean | Returns **true** if the cursor is in the last row of the result set; returns **false** otherwise.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const fetchCount = fetchFileResult.getCount(); + console.info('mediaLibraryTest : count:' + fetchCount); + let fileAsset = await fetchFileResult.getFirstObject(); + for (var i = 1; i < fetchCount; i++) { + fileAsset = await fetchFileResult.getNextObject(); + if(i == fetchCount - 1) { + console.info('mediaLibraryTest : isLast'); + var result = fetchFileResult.isAfterLast(); + console.info('mediaLibraryTest : isAfterLast:' + result); + console.info('mediaLibraryTest : isAfterLast end'); + fetchFileResult.close(); + } + } +} +``` + +### close + +close(): void + +Releases and invalidates this **FetchFileResult** instance. After this instance is released, the APIs in this instance cannot be invoked. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.close(); +} +``` + +### getFirstObject + +getFirstObject(callback: AsyncCallback<FileAsset>): void + +Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the first file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getFirstObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getFirstObject + +getFirstObject(): Promise<FileAsset> + +Obtains the first file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the first file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getFirstObject().then(function(fileAsset){ + console.info("getFirstObject successfully:"+ JSON.stringify(fileAsset)); + }).catch(function(err){ + console.info("getFirstObject failed with error:"+ err); + }); +} +``` + +### getNextObject + + getNextObject(callback: AsyncCallback<FileAsset>): void + +Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ----------------------------------------- | +| callbacke | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the next file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getNextObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getNextObject + + getNextObject(): Promise<FileAsset> + +Obtains the next file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the next file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + const fetchCount = fetchFileResult.getCount(); + console.info('mediaLibraryTest : count:' + fetchCount); + let fileAsset = await fetchFileResult.getNextObject(); +} +``` + +### getLastObject + +getLastObject(callback: AsyncCallback<FileAsset>): void + +Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | --------------------------- | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the last file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getLastObject((err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getLastObject + +getLastObject(): Promise<FileAsset> + +Obtains the last file asset in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the last file asset.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + let lastObject = await fetchFileResult.getLastObject(); +} +``` + +### getPositionObject + +getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void + +Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------ | +| index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset obtained.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getPositionObject(0, (err, fileAsset) => { + if (err) { + console.error('Failed '); + return; + } + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }) +} +``` + +### getPositionObject + +getPositionObject(index: number): Promise<FileAsset> + +Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | -------------- | +| index | number | Yes | Index of the file asset to obtain. The value starts from **0**.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset obtained.| + +**Example** + +```js +async function example() { + let fileKeyObj = mediaLibrary.FileKey; + let imageType = mediaLibrary.MediaType.IMAGE; + let getImageOp = { + selections: fileKeyObj.MEDIA_TYPE + '= ?', + selectionArgs: [imageType.toString()], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let userFileMgr = userfile_manager.getUserFileMgr(context); + let fetchFileResult = await userFileMgr.getFileAssets(getImageOp); + fetchFileResult.getPositionObject(1) .then(function (fileAsset){ + console.log('fileAsset.displayName : ' + fileAsset.displayName); + }).catch(function (err) { + console.info("getFileAssets failed with error:" + err); + }); +} +``` + +## Album + +Provides APIs to manage albums. + +### Attributes + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable | Writable | Description | +| ------------ | ------ | ---- | ---- | ------- | +| albumName | string | Yes | Yes | Album name. | +| albumUri | string | Yes | No | Album URI. | +| dateModified | number | Yes | No | Date when the album was last modified. | +| count | number | Yes | No | Number of files in the album.| +| relativePath | string | Yes | No | Relative path of the album. | +| coverUri | string | Yes | No | URI of the cover file of the album. + +### commitModify + +commitModify(callback: AsyncCallback<void>): void; + +Commits the modification on the album attributes to the database. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| + +**Example** + +```ts +async function commitModifyDemoCallback() { + console.info('commitModifyDemo') + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE; + let getImageOp = { + selections: '', + selectionArgs: [], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); + let asset = await fetchFileResult.getFirstObject(); + console.info('old displayName:', asset.displayName) + asset.displayName = 'newDisplayName'; + console.info('new displayName:', asset.displayName) + asset.commitModify((err) => { + if (err == undefined) { + console.info('commitModify succeed.') + } else { + console.info('commitModify failed, message =', err); + } + }); +} +``` + +### commitModify + +commitModify(): Promise<void>; + +Commits the modification on the album attributes to the database. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------ | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +async function commitModifyDemoPromise() { + console.info('commitModifyDemo') + let fileKeyObj = userfile_manager.FileKey + let imageType = userfile_manager.MediaType.IMAGE; + let getImageOp = { + selections: '', + selectionArgs: [], + order: fileKeyObj.DATE_ADDED + " DESC", + extendArgs: "", + }; + let fetchFileResult = await userFileMgr.getFileAssets([imageType], getImageOp); + let asset = await fetchFileResult.getFirstObject(); + console.info('old displayName:', asset.displayName) + asset.displayName = 'newDisplayName'; + console.info('new displayName:', asset.displayName) + try { + await asset.commitModify(); + console.info('commitModify succeed.') + } catch (err) { + console.info('commitModify failed, message =', err); + } +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, callback: AsyncCallback<FetchFileResult>): void; + +Obtains the file assets in this album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function albumGetFileAssetsDemoCallback() { + console.info('albumGetFileAssetsDemoCallback2') + let imageType = userfile_manager.MediaType.IMAGE; + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); + const album = albumList[0]; + album.getFileAssets([imageType], (err, albumFetchFileResult) => { + if (err == undefined) { + console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + } else { + console.info("getFileAssets failed with error:"+ err); + } + }); +} +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; + +Obtains the file assets in this album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the media data. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function albumGetFileAssetsDemoCallback() { + console.info('albumGetFileAssetsDemoCallback') + let imageType = userfile_manager.MediaType.IMAGE; + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } + const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); + const album = albumList[0]; + album.getFileAssets([imageType], fileNoArgsfetchOp, (err, albumFetchFileResult) => { + if (err == undefined) { + console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + } else { + console.info("getFileAssets failed with error:"+ err); + } + }); + } +``` + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options?: MediaFetchOptions): Promise<FetchFileResult>; + +Obtains the file assets in this album. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the media data.| + +**Return value** + +| Type | Description | +| --------------------------------------------- | ------------------------- | +| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| + +**Example** + +```ts +async function albumGetFileAssetsDemoPromise() { + console.info('albumGetFileAssetsDemoPromise') + let imageType = userfile_manager.MediaType.IMAGE; + let AlbumNoArgsfetchOp = { + selections: '', + selectionArgs: [], + }; + let fileNoArgsfetchOp = { + selections: '', + selectionArgs: [], + } + const albumList = await userFileMgr.getAlbums([imageType], AlbumNoArgsfetchOp); + const album = albumList[0]; + album.getFileAssets([imageType], fileNoArgsfetchOp).then(function(albumFetchFileResult){ + console.info("getFileAssets successfully:"+ JSON.stringify(albumFetchFileResult)); + }).catch(function(err){ + console.info("getFileAssets failed with error:"+ err); + }); +} +``` +## VirtualAlbum +Provides APIs for managing a virtual album. + +### getFileAssets + +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; + +Obtains file assets in the virtual album. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +> **NOTE**
+> The ability privilege level (APL) of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the Access Control List (ACL). For details, see [ACL](../../security/accesstoken-overview.md#acl). +> +> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ----------------------------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +| options | [MediaFetchOptions](#mediafetchoptions) | Yes | Options for fetching the files. | +| callback | AsyncCallback<[FetchFileResult](#fetchfileresult)> | Yes | Callback invoked to return the file assets obtained.| + +**Example** + +```ts +async function virtualAlbumGetFileAssetsDemoCallback() { + console.info('virtualAlbumGetFileAssetsDemoCallback') + try { + var albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); + } catch (err) { + console.info('getPrivateAlbum failed, message = ', err); + } + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + + trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt, (err, fetchResult) => { + if (err == undefined) { + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); + } else { + console.info('getFileAssets failed, message = ', err); + } + }); +} +``` + +### getFileAssets +getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; + +Obtains file assets in the virtual album. This API uses a promise to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT + +> **NOTE**
+> The APL of the permissions required by this API is **system_basic**. Applications of the **normal** APL need to apply for these permissions through the ACL. For details, see [ACL](../../security/accesstoken-overview.md#acl). +> +> You are advised to use the **options** parameter to explicitly specify the type of the file access. If the file type cannot be determined, the file asset result set is returned based on the permissions of the application. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------------- | ---- | -------------- | +| type | Array<[MediaType](#mediatype)> | Yes | Type of the media data to obtain. | +|options | [MediaFetchOptions](#mediafetchoptions) | No | Options for fetching the files.| + +**Return value** + +| Type | Description | +| --------------------------------------------- | ------------------------- | +| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| + +**Example** + +```ts +async function virtualAlbumGetFileAssetsDemoPromise() { + console.info('virtualAlbumGetFileAssetsDemoPromise') + let albumArray = await userFileMgr.getPrivateAlbum(userfile_manager.VirtualAlbumType.TYPE_TRASH); + let fetchOpt = { + selections: '', + selectionArgs: [], + }; + let trashAlbum = albumArray[0]; + + let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); +} +``` + +## PeerInfo + +Describes information about a registered device. +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore + +| Name | Type | Readable| Writable| Description | +| ---------- | -------------------------- | ---- | ---- | ---------------- | +| deviceName | string | Yes | No | Name of the registered device. | +| networkId | string | Yes | No | Network ID of the registered device.| +| isOnline | boolean | Yes | No | Whether the registered device is online. | + +## MediaType + +Enumerates the media types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Description| +| ----- | ---- | +| FILE | File.| +| IMAGE | Image.| +| VIDEO | Video.| +| AUDIO | Audio.| + +## FileKey + +Defines the key file information. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | File URI. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | File name displayed. | +| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | +| TITLE | title | Title in the file. | + +## AudioKey + +Defines the key information about an audio file. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | Promise used to return the URI of the file created. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | File name displayed. | +| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | +| TITLE | title | Title in the file. | +| ARTIST | artist | Author of the file. | +| AUDIOALBUM | audio_album | Audio album. | +| DURATION | duration | Duration, in ms. | + +## ImageVideoKey + +Defines the key information about an image or video file. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | File URI. | +| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| DISPLAY_NAME | display_name | File name displayed. | +| DATE_ADDED | date_added | Date when the file was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the file was last modified. The value is the number of seconds elapsed since the Epoch time. | +| DURATION | duration | Duration, in ms. | +| WIDTH | width | Image width, in pixels. | +| HEIGHT | height | Image height, in pixels. | +| DATE_TAKEN | date_taken | Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time. | + +## AlbumKey + +Defines the key album information. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Default Value | Description | +| ------------- | ------------------- | ---------------------------------------------------------- | +| URI | uri | Album URI. | +| RELATIVE_PATH | relative_path | Relative public directory of the album. | +| DISPLAY_NAME | display_name | Album name displayed. | +| DATE_ADDED | date_added | Date when the album was added. The value is the number of seconds elapsed since the Epoch time. | +| DATE_MODIFIED | date_modified | Date when the album was last modified. The value is the number of seconds elapsed since the Epoch time. | + +## DirectoryType + +Enumerates directory types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Description | +| ------------- | ------------------ | +| DIR_CAMERA | Directory of camera files.| +| DIR_VIDEO | Directory of video files. | +| DIR_IMAGE | Directory of image files. | +| DIR_AUDIO | Directory of audio files. | +| DIR_DOCUMENTS | Directory of documents. | +| DIR_DOWNLOAD | Download directory. | + +## MediaFetchOptions + +Defines the options for fetching media files. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable| Writable| Mandatory| Description | +| ----------------------- | ------------------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| selections | string | Yes | Yes | Yes | Conditions for fetching files. The values in [FileKey](#filekey) are used as the column names of the conditions. Example:
selections: mediaLibrary.FileKey.MEDIA_TYPE + '= ? OR' +mediaLibrary.FileKey.MEDIA_TYPE + '= ?',| +| selectionArgs | Array<string> | Yes | Yes | Yes | Values of the conditions specified in **selections**.
Example:
selectionArgs: [mediaLibrary.MediaType.IMAGE.toString(), mediaLibrary.MediaType.VIDEO.toString()], | + +## Size + +Defines the image size. +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | -------- | +| width | number | Yes | Yes | Image width, in pixels.| +| height | number | Yes | Yes | Image height, in pixels.| + +## VirtualAlbumType +Enumerates the system or virtual album types. + +This is a system API. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Description | +| ------------- | ------------------ | +| TYPE_FAVORITE | Favorites album.
This is a system API.| +| TYPE_TRASH | Trash album.
This is a system API.| diff --git a/en/application-dev/reference/apis/js-apis-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-volumemanager.md b/en/application-dev/reference/apis/js-apis-volumemanager.md index 87cfad2f83ba3c25d4ab90a874777d86bb2cd473..79cbf5db12746acc8e18d293c03fe3aa48bdc86a 100644 --- a/en/application-dev/reference/apis/js-apis-volumemanager.md +++ b/en/application-dev/reference/apis/js-apis-volumemanager.md @@ -52,7 +52,7 @@ Asynchronously obtains information about all available volumes. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------- | ---- | ------------------------------------ | - | callback | callback:AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| + | callback | callback: AsyncCallback<[Volume](#volume)[]> | Yes | Callback invoked to return the volume information obtained.| **Example** @@ -110,7 +110,7 @@ Asynchronously obtains the available space of the specified volume. This API use | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | callback: AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| **Example** @@ -154,7 +154,7 @@ Asynchronously unmounts a volume. This API uses a promise to return the result. ## volumemanager.unmount -unmount(volumeId: string, callback:AsyncCallback<boolean>):void +unmount(volumeId: string, callback: AsyncCallback<boolean>): void Asynchronously unmounts a volume. This API uses a callback to return the result. @@ -167,7 +167,7 @@ Asynchronously unmounts a volume. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------- | | volumeId | string | Yes | Volume ID. | - | callback | callback:AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| + | callback | callback: AsyncCallback<boolean> | Yes | Callback invoked to return the execution result.| **Example** @@ -226,7 +226,7 @@ Asynchronously obtains volume information based on the UUID. This API uses a cal | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------- | | uuid | string | Yes | UUID of the volume. | - | callback | callback:AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| + | callback | callback: AsyncCallback<[Volume](#volume)> | Yes | Callback invoked to return the volume information obtained.| **Example** @@ -347,7 +347,7 @@ Asynchronously sets the volume description based on the UUID. This API uses a ca | ---------- | --------------------------------------- | ---- | ---------------- | | uuid | string | Yes | UUID of the volume. | | description | string | Yes | Volume description. | - | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result.| + | callback | callback: AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** @@ -410,7 +410,7 @@ Asynchronously formats a volume. This API uses a callback to return the result. | -------- | ------------------------- | ---- | ----------------------------- | | volumeId | string | Yes | Volume ID. | | fsType | string | Yes | File system type.| - | callback | callback:AsyncCallback<void> | Yes | Called after the volume is formatted. | + | callback | callback: AsyncCallback<void> | Yes | Called after the volume is formatted. | **Example** @@ -473,7 +473,7 @@ Asynchronously partitions a disk. This API uses a callback to return the result. | -------- | --------------------------------------- | ---- | ---------------- | | diskId | string | Yes | ID of the disk to which the volume belongs. | | type | number | Yes | Partition type. | - | callback | callback:AsyncCallback<void> | Yes | Callback invoked to return the result. | + | callback | callback: AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 91c284004f4b1e2f22d46ba27c3249d9b05dd5bb..e88c24874ded38ec76625957039617147d5664b6 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -1,6 +1,6 @@ # Window -The `Window` module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. +The **Window** module provides basic window management capabilities, such as creating and destroying the current window, setting properties for the current window, and managing and scheduling windows. This module provides the following common window-related functions: @@ -44,18 +44,34 @@ Enumerates the window types. | TYPE_DIALOG9+ | 16 | Modal window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| | TYPE_SCREENSHOT9+ | 17 | Screenshot window.
**Model restriction**: This API can be used only in the stage model.
**System API**: This is a system API.| +## Configuration9+ + +Defines the parameters used for creating a subwindow. + +An asynchronous callback is used when a system window is created in the case that [ServiceExtensionContext](js-apis-service-extension-context.md) is used as the context. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +| Name| Type| Mandatory| Description| +| ---------- | -------------------------- | -- | ----------------------------------- | +| name | string | Yes| Name of the subwindow. | +| windowType | [WindowType](#windowtype7) | Yes| Type of the subwindow. | +| ctx | BaseContext | No| Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).
If this parameter is not set, no context is used. | +| displayId | number | No| ID of the current physical screen. If this parameter is not set, the default value **-1** is used.| +| parentId | number | No| ID of the parent window. If this parameter is not set, the default value **-1** is used. | + ## AvoidAreaType7+ Enumerates the types of the area where the window cannot be displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Value | Description | -|----------------------------------|-----| ----------------- | -| TYPE_SYSTEM | 0 | Default area of the system.| -| TYPE_CUTOUT | 1 | Notch. | -| TYPE_SYSTEM_GESTURE9+ | 2 | Gesture area. | -| TYPE_KEYBOARD9+ | 3 | Soft keyboard area. | +| Name | Value | Description | +| -------------------------------- | ---- | ------------------------------------------------------------ | +| TYPE_SYSTEM | 0 | Default area of the system. Generally, the status bar, navigation bar, and Dock bar are included. The default area may vary according to the device in use.| +| TYPE_CUTOUT | 1 | Notch. | +| TYPE_SYSTEM_GESTURE9+ | 2 | Gesture area. | +| TYPE_KEYBOARD9+ | 3 | Soft keyboard area. | ## WindowMode7+ @@ -92,14 +108,14 @@ Describes the properties of the status bar and navigation bar. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type| Readable| Writable| Description | -| -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| statusBarColor | string | No | Yes | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| isStatusBarLightIcon7+ | boolean | No | Yes | Whether any icon on the status bar is highlighted. | -| statusBarContentColor8+ | string | No | Yes | Color of the text on the status bar. | -| navigationBarColor | string | No | Yes | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| isNavigationBarLightIcon7+ | boolean | No | Yes | Whether any icon on the navigation bar is highlighted. | -| navigationBarContentColor8+ | string | No | Yes | Color of the text on the navigation bar. | +| Name | Type| Readable| Writable| Mandatory| Description | +| -------------------------------------- | -------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| statusBarColor | string | No | Yes | No | Background color of the status bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.| +| isStatusBarLightIcon7+ | boolean | No | Yes | No | Whether any icon on the status bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.| +| statusBarContentColor8+ | string | No | Yes | No | Color of the text on the status bar. After this property is set, the setting of **isStatusBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.| +| navigationBarColor | string | No | Yes | No | Background color of the navigation bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**. The default value is **#0x66000000**.| +| isNavigationBarLightIcon7+ | boolean | No | Yes | No | Whether any icon on the navigation bar is highlighted. The value **true** means that the icon is highlighted, and **false** means the opposite. The default value is **false**.| +| navigationBarContentColor8+ | string | No | Yes | No | Color of the text on the navigation bar. After this property is set, the setting of **isNavigationBarLightIcon** is invalid. The default value is **0xE5FFFFFF**.| ## Orientation9+ @@ -147,10 +163,10 @@ Describes the callback for a single system bar. | Name | Type | Readable| Writable| Description | | --------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| type | [WindowType](#windowtype) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| -| isEnable | boolean | Yes | No | Whether the system bar is displayed. | -| region | [Rect](#rect) | Yes | No | Current position and size of the system bar. | -| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| type | [WindowType](#windowtype7) | Yes | No | Type of the system bar whose properties are changed. Only the status bar and navigation bar are supported.| +| isEnable | boolean | Yes | No | Whether the system bar is displayed. The value **true** means that the system bar is displayed, and **false** means the opposite.| +| region | [Rect](#rect7) | Yes | No | Current position and size of the system bar. | +| backgroundColor | string | Yes | No | Background color of the system bar. The value is a hexadecimal RGB or aRGB color value and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| | contentColor | string | Yes | No | Color of the text on the system bar. | ## SystemBarTintState8+ @@ -187,11 +203,11 @@ Describes the area where the window cannot be displayed. | Name | Type | Readable| Writable| Description | | ---------- | ------------- | ---- | ---- | ------------------ | -| visible9+ | boolean | Yes | Yes | Whether the window can be displayed in the area.| -| leftRect | [Rect](#rect) | Yes | Yes | Rectangle on the left of the screen.| -| topRect | [Rect](#rect) | Yes | Yes | Rectangle at the top of the screen.| -| rightRect | [Rect](#rect) | Yes | Yes | Rectangle on the right of the screen.| -| bottomRect | [Rect](#rect) | Yes | Yes | Rectangle at the bottom of the screen.| +| visible9+ | boolean | Yes | Yes | Whether the window can be displayed in the area. The value **true** means that the window can be displayed in the area, and **false** means the opposite.| +| leftRect | [Rect](#rect7) | Yes | Yes | Rectangle on the left of the screen.| +| topRect | [Rect](#rect7) | Yes | Yes | Rectangle at the top of the screen.| +| rightRect | [Rect](#rect7) | Yes | Yes | Rectangle on the right of the screen.| +| bottomRect | [Rect](#rect7) | Yes | Yes | Rectangle at the bottom of the screen.| ## Size7+ @@ -212,30 +228,30 @@ Describes the window properties. | Name | Type | Readable| Writable| Description | | ------------------------------------- | ------------------------- | ---- | ---- | ------------------------------------------------------------ | -| windowRect7+ | [Rect](#rect) | Yes | Yes | Window size. | -| type7+ | [WindowType](#windowtype) | Yes | Yes | Window type. | -| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is `false`. | -| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is `false`. | -| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is `true`. | -| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is `true`. | -| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value `1` indicates the maximum brightness. | -| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value `1` indicates the maximum dimness.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| -| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is `false`. | -| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is `false`. | -| isRoundCorner(deprecated) | boolean | Yes | Yes | Whether the window has rounded corners. The default value is `false`.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| -| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is `false`. | -| id9+ | number | Yes | No | Window ID. The default value is `0.0`. | +| windowRect7+ | [Rect](#rect7) | Yes | Yes | Window size. | +| type7+ | [WindowType](#windowtype7) | Yes | Yes | Window type. | +| isFullScreen | boolean | Yes | Yes | Whether the window is displayed in full screen mode. The default value is **false**. The value **true** means that the window is displayed in full screen mode, and **false** means the opposite.| +| isLayoutFullScreen7+ | boolean | Yes | Yes | Whether the window layout is in full-screen mode (whether the window is immersive). The default value is **false**. The value **true** means that the window is immersive, and **false** means the opposite.| +| focusable7+ | boolean | Yes | No | Whether the window can gain focus. The default value is **true**. The value **true** means that the window can gain focus, and **false** means the opposite.| +| touchable7+ | boolean | Yes | No | Whether the window is touchable. The default value is **true**. The value **true** means that the window is touchable, and **false** means the opposite.| +| brightness | number | Yes | Yes | Screen brightness. The value ranges from 0 to 1. The value **1** indicates the maximum brightness. | +| dimBehindValue(deprecated) | number | Yes | Yes | Dimness of the window that is not on top. The value ranges from 0 to 1. The value **1** indicates the maximum dimness.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| +| isKeepScreenOn | boolean | Yes | Yes | Whether the screen is always on. The default value is **false**. The value **true** means that the screen is always on, and **false** means the opposite.| +| isPrivacyMode7+ | boolean | Yes | Yes | Whether the window is in privacy mode. The default value is **false**. The value **true** means that the window is in privacy mode, and **false** means the opposite.| +| isRoundCorner(deprecated) | boolean | Yes | Yes | Whether the window has rounded corners. The default value is **false**. The value **true** means that the window has rounded corners, and **false** means the opposite.
**NOTE**
This property is supported since API version 7 and deprecated since API version 9.
| +| isTransparent7+ | boolean | Yes | Yes | Whether the window is transparent. The default value is **false**. The value **true** means that the window is transparent, and **false** means the opposite.| +| id9+ | number | Yes | No | Window ID. The default value is **0.0**. | ## ColorSpace8+ -Describes the color gamut mode. +Enumerates the color spaces. **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name | Default Value | Description | | ---------- | ------ | -------------- | -| DEFAULT | 0 | Default color gamut mode.| -| WIDE_GAMUT | 1 | Wide color gamut mode. | +| DEFAULT | 0 | Default gamut.| +| WIDE_GAMUT | 1 | Wide-gamut. | ## ScaleOptions9+ @@ -247,10 +263,10 @@ Describes the scale parameters. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | -------------------------------------------------- | -| x | number | No | Yes | Scale factor along the x-axis. The default value is `1.0`. | -| y | number | No | Yes | Scale factor along the y-axis. The default value is `1.0`. | -| pivotX | number | No | Yes | X coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| -| pivotY | number | No | Yes | Y coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| x | number | No | Yes | Scale factor along the x-axis. The default value is **1.0**. | +| y | number | No | Yes | Scale factor along the y-axis. The default value is **1.0**. | +| pivotX | number | No | Yes | X coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| +| pivotY | number | No | Yes | Y coordinate of the scale center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| ## RotateOptions9+ @@ -262,11 +278,11 @@ Describes the rotation parameters. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | -------------------------------------------------- | -| x | number | No | Yes | Rotation angle around the x-axis. The default value is `0.0`. | -| y | number | No | Yes | Rotation angle around the y-axis. The default value is `0.0`. | -| z | number | No | Yes | Rotation angle around the z-xis. The default value is `0.0`. | -| pivotX | number | No | Yes | X coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| -| pivotY | number | No | Yes | Y coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is `0.5`.| +| x | number | No | Yes | Rotation angle around the x-axis. The default value is **0.0**. | +| y | number | No | Yes | Rotation angle around the y-axis. The default value is **0.0**. | +| z | number | No | Yes | Rotation angle around the z-xis. The default value is **0.0**. | +| pivotX | number | No | Yes | X coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| +| pivotY | number | No | Yes | Y coordinate of the rotation center. The value ranges from 0.0 to 1.0, and the default value is **0.5**.| ## TranslateOptions9+ @@ -278,179 +294,106 @@ Describes the translation parameters. | Name| Type| Readable| Writable| Description | | ---- | -------- | ---- | ---- | ---------------------------- | -| x | number | No | Yes | Distance to translate along the x-axis. The default value is `0.0`.| -| y | number | No | Yes | Distance to translate along the y-axis. The default value is `0.0`.| -| z | number | No | Yes | Distance to translate along the z-axis. The default value is `0.0`.| +| x | number | No | Yes | Distance to translate along the x-axis. The default value is **0.0**.| +| y | number | No | Yes | Distance to translate along the y-axis. The default value is **0.0**.| +| z | number | No | Yes | Distance to translate along the z-axis. The default value is **0.0**.| -## window.create7+ +## window.createWindow9+ -create(id: string, type: WindowType, callback: AsyncCallback<Window>): void +createWindow(config: Configuration, callback: AsyncCallback<Window>): void Creates a subwindow. This API uses an asynchronous callback to return the result. -**Model restriction**: This API can be used only in the FA model. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------ | -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created.| - -**Example** - -```js -let windowClass = null; -window.create('first', window.WindowType.TYPE_APP,(err,data) => { - if(err.code){ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); -}); -``` - -## window.create7+ - -create(id: string, type: WindowType): Promise<Window> - -Creates a subwindow. This API uses a promise to return the result. - -**Model restriction**: This API can be used only in the FA model. - **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ---------- | -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type.| - -**Return value** - -| Type | Description | -| -------------------------------- | --------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the subwindow created.| - -**Example** - -```js -let windowClass = null; -let promise = window.create('first', window.WindowType.TYPE_APP); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); -}); -``` - -## window.create8+ - -create(ctx: Context, id: string, type: WindowType, callback: AsyncCallback<Window>): void - -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses an asynchronous callback to return the result. +| Name| Type| Mandatory| Description| +| -------- | -------------------------------------- | -- | --------------------------------- | +| config | [Configuration](#configuration9) | Yes| Current application context. | +| callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the subwindow created.| -**System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** -**Parameters** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | +| ID| Error Message| +| ------- | -------------------------------- | +| 1300001 | Repeated operation. | +| 1300006 | This window context is abnormal. | **Example** ```js let windowClass = null; - window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { - if (err.code) { - console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); - windowClass.resetSize(500, 1000); -}); +let config = {name: "alertWindow", windowType: window.WindowType.TYPE_SYSTEM_ALERT, ctx: this.context}; +try { + window.createWindow(config, (err, data) => { + if (err.code) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); + }); +} catch (exception) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.create8+ +## window.createWindow9+ -create(ctx: Context, id: string, type: WindowType): Promise<Window> +createWindow(config: Configuration): Promise<Window> -Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses a promise to return the result. +Creates a subwindow. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [ServiceExtensionContext](js-apis-service-extension-context.md).| -| id | string | Yes | Window ID. | -| type | [WindowType](#windowtype) | Yes | Window type. | +| Name| Type| Mandatory| Description| +| ------ | -------------------------------- | -- | ------------------ | +| config | [Configuration](#configuration9) | Yes| Current application context.| **Return value** -| Type | Description | -| -------------------------------- | --------------------------------------- | +| Type| Description| +| -------------------------------- | ------------------------------------ | | Promise<[Window](#window)> | Promise used to return the subwindow created.| -**Example** - -```js -let windowClass = null; -let promise = window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); -}); -``` - -## window.find7+ - -find(id: string, callback: AsyncCallback<Window>): void - -Finds a window based on the ID. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** -**Parameters** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------ | -| id | string | Yes | Window ID. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window found.| +| ID| Error Message| +| ------- | -------------------------------- | +| 1300001 | Repeated operation. | +| 1300006 | This window context is abnormal. | **Example** ```js let windowClass = null; - window.find('alertWindow', (err, data) => { - if (err.code) { - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); -}); +let config = {name: "alertWindow", windowType: window.WindowType.TYPE_SYSTEM_ALERT, ctx: this.context}; +try { + let promise = window.createWindow(config); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to create the window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.find7+ +## window.findWindow9+ -find(id: string): Promise<Window> +findWindow(name: string): Window -Finds a window based on the ID. This API uses a promise to return the result. +Finds a window based on the ID. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -458,118 +401,69 @@ Finds a window based on the ID. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------- | -| id | string | Yes | Window ID.| +| name | string | Yes | Window ID.| **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the window found.| +| Type| Description| +| ----------------- | ------------------- | +| [Window](#window) | Window found.| **Example** ```js -let windowClass = null; -let promise = window.find('alertWindow'); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); -}); +try { + let windowClass = window.findWindow('alertWindow'); +} catch (exception) { + console.error('Failed to find the Window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.getTopWindow +## window.getLastWindow9+ -getTopWindow(callback: AsyncCallback<Window>): void +getLastWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void Obtains the top window of the current application. This API uses an asynchronous callback to return the result. -**Model restriction**: This API can be used only in the FA model. - **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | -------------------------------------------- | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained.| - -**Example** - -```js -let windowClass = null; -window.getTopWindow((err, data) => { - if (err.code) { - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}); -``` - -## window.getTopWindow - -getTopWindow(): Promise<Window> - -Obtains the top window of the current application. This API uses a promise to return the result. - -**Model restriction**: This API can be used only in the FA model. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Return value** - -| Type | Description | -| -------------------------------- | ----------------------------------------------- | -| Promise<[Window](#window)> | Promise used to return the top window obtained.| - -**Example** - -```js -let windowClass = null; -let promise = window.getTopWindow(); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); -}) -``` +| Name| Type| Mandatory| Description| +| -------- | -------------------------------------- | -- | ---------------------------------------- | +| ctx | BaseContext | Yes| Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the top window obtained.| -## window.getTopWindow8+ +**Error codes** -getTopWindow(ctx: Context, callback: AsyncCallback<Window>): void +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -Obtains the top window of the current application. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | +| ID| Error Message| +| ------- | -------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300006 | This window context is abnormal. | **Example** ```js let windowClass = null; -window.getTopWindow(this.context, (err, data) => { - if (err.code) { - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}); +try { + window.getLastWindow(this.context, (err, data) => { + if (err.code) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); +}; ``` -## window.getTopWindow8+ +## window.getLastWindow9+ -getTopWindow(ctx: Context): Promise<Window> +getLastWindow(ctx: BaseContext): Promise<Window> Obtains the top window of the current application. This API uses a promise to return the result. @@ -577,27 +471,40 @@ Obtains the top window of the current application. This API uses a promise to re **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| ctx | Context | Yes | Current application context.
For the definition of `Context` of API version 8, see [Context](js-apis-Context.md).
For the definition of `Context` of API version 9, see [AbilityContext](js-apis-ability-context.md).| +| Name| Type| Mandatory| Description| +| ------ | ----------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| **Return value** -| Type | Description | -| -------------------------------- | ----------------------------------------------- | +| Type| Description| +| -------------------------------- | ------------------------------------------- | | Promise<[Window](#window)> | Promise used to return the top window obtained.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300006 | This window context is abnormal. | + **Example** ```js let windowClass = null; -let promise = window.getTopWindow(this.context); -promise.then((data)=> { - windowClass = data; - console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); -}) +try { + let promise = window.getLastWindow(this.context); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.minimizeAll9+ @@ -616,26 +523,38 @@ Minimizes all windows on a display. This API uses an asynchronous callback to re | id | number | Yes | ID of the [display](js-apis-display.md#display).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js import display from '@ohos.display' import window from '@ohos.window' -let displayClass = null; -display.getDefaultDisplay((err, data) => { - if(err.code) { - return; - } - displayClass = data; - window.minimizeAll(displayClass.id, (err, data) => { +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); + return; +}; + +try { + window.minimizeAll(displayClass.id, (err) => { if(err.code) { console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); return; } console.info('Succeeded in minimizing all windows.'); }); -}); +} catch (exception) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.minimizeAll9+ @@ -659,6 +578,14 @@ Minimizes all windows on a display. This API uses a promise to return the result | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -666,18 +593,23 @@ import display from '@ohos.display' import window from '@ohos.window' let displayClass = null; -display.getDefaultDisplay((err, data) => { - if(err.code) { - return; - } - displayClass = data; +try { + displayClass = display.getDefaultDisplaySync(); +} catch (exception) { + console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); + return; +}; + +try { let promise = window.minimizeAll(displayClass.id); - promise.then((data)=> { + promise.then(()=> { console.info('Succeeded in minimizing all windows.'); }).catch((err)=>{ console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(err)); - }) -}); + }); +} catch (exception) { + console.error('Failed to minimize all windows. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.toggleShownStateForAllAppWindows9+ @@ -695,10 +627,18 @@ Hides or restores the application's windows during quick multi-window switching. | -------- | ------------------------- | ---- | -------------- | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -window.toggleShownStateForAllAppWindows((err, data) => { +window.toggleShownStateForAllAppWindows((err) => { if (err.code) { console.error('Failed to toggle shown state for all app windows. Cause: ' + JSON.stringify(err)); return; @@ -722,12 +662,20 @@ Hides or restores the application's windows during quick multi-window switching. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let promise = window.toggleShownStateForAllAppWindows(); -promise.then((data)=> { - console.info('Succeeded in toggling shown state for all app windows. Data: ' + JSON.stringify(data)); +promise.then(()=> { + console.info('Succeeded in toggling shown state for all app windows.'); }).catch((err)=>{ console.error('Failed to toggle shown state for all app windows. Cause: ' + JSON.stringify(err)); }) @@ -749,12 +697,28 @@ Sets the window layout mode. This API uses an asynchronous callback to return th | mode | [WindowLayoutMode](#windowlayoutmode9) | Yes | Window layout mode to set.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Example** +**Error codes** -```js -window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE, (data) => { - console.info('Succeeded in setting window layout mode. Data: ' + JSON.stringify(data)); -}); +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +try { + window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE, (err) => { + if(err.code) { + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window layout mode.'); + }); +} catch (exception) { + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(exception)); +}; ``` ## window.setWindowLayoutMode9+ @@ -778,18 +742,30 @@ Sets the window layout mode. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -let promise = window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE); -promise.then((data)=> { - console.info('Succeeded in setting window layout mode. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(err)); -}) +try { + let promise = window.setWindowLayoutMode(window.WindowLayoutMode.WINDOW_LAYOUT_MODE_CASCADE); + promise.then(()=> { + console.info('Succeeded in setting window layout mode.'); + }).catch((err)=>{ + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set window layout mode. Cause: ' + JSON.stringify(exception)); +}; ``` -## on('systemBarTintChange')8+ +## window.on('systemBarTintChange')8+ on(type: 'systemBarTintChange', callback: Callback<SystemBarTintState>): void @@ -803,18 +779,22 @@ Enables listening for properties changes of the status bar and navigation bar. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| type | string | Yes | Event type. The value is fixed at **'systemBarTintChange'**, indicating the property change event of the status bar and navigation bar.| | callback | Callback<[SystemBarTintState](#systembartintstate)> | Yes | Callback used to return the properties of the status bar and navigation bar. | **Example** ```js -window.on('systemBarTintChange', (data) => { - console.info('Succeeded in enabling the listener for systemBarTint changes. Data: ' + JSON.stringify(data)); -}); +try { + window.on('systemBarTintChange', (data) => { + console.info('Succeeded in enabling the listener for systemBarTint changes. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to enable the listener for systemBarTint changes. Cause: ' + JSON.stringify(exception)); +}; ``` -## off('systemBarTintChange')8+ +## window.off('systemBarTintChange')8+ off(type: 'systemBarTintChange', callback?: Callback<SystemBarTintState >): void @@ -828,331 +808,432 @@ Disables listening for properties changes of the status bar and navigation bar. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `systemBarTintChange`, indicating the property change event of the status bar and navigation bar.| +| type | string | Yes | Event type. The value is fixed at **'systemBarTintChange'**, indicating the property change event of the status bar and navigation bar.| | callback | Callback<[SystemBarTintState](#systembartintstate)> | No | Callback used to return the properties of the status bar and navigation bar. | **Example** ```js -window.off('systemBarTintChange'); +try { + window.off('systemBarTintChange'); +} catch (exception) { + console.error('Failed to disable the listener for systemBarTint changes. Cause: ' + JSON.stringify(exception)); +}; ``` -## Window - -Represents the current window instance, which is the basic unit managed by the window manager. - -In the following API examples, you must use [getTopWindow()](#windowgettopwindow), [create()](#windowcreate7), or [find()](#windowfind7) to obtain a `Window` instance and then call a method in this instance. +## window.create(deprecated) -### hide7+ +create(id: string, type: WindowType, callback: AsyncCallback<Window>): void -hide (callback: AsyncCallback<void>): void +Creates a subwindow. This API uses an asynchronous callback to return the result. -Hides this window. 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 [createWindow()](#windowcreatewindow9) instead. -**System API**: This is a system API. +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------ | +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created.| **Example** ```js -windowClass.hide((err, data) => { - if (err.code) { - console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); +let windowClass = null; +window.create('first', window.WindowType.TYPE_APP,(err,data) => { + if(err.code){ + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); +}); ``` -### hide7+ +## window.create(deprecated) -hide(): Promise<void> +create(id: string, type: WindowType): Promise<Window> -Hides this window. This API uses a promise to return the result. +Creates a subwindow. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [createWindow()](#windowcreatewindow9-1) instead. + +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ---------- | +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type.| + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** ```js -let promise = windowClass.hide(); +let windowClass = null; +let promise = window.create('first', window.WindowType.TYPE_APP); promise.then((data)=> { - console.info('Succeeded in hiding the window. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in creating the subWindow. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); -}) + console.error('Failed to create the subWindow. Cause: ' + JSON.stringify(err)); +}); ``` -### hideWithAnimation9+ +## window.create(deprecated) -hideWithAnimation(callback: AsyncCallback<void>): void +create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Hides this window and plays an animation during the process. This API uses an asynchronous callback to return the result. +Creates a subwindow in the FA model -**System API**: This is a system API. +or a system window in the stage model. 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 [createWindow()](#windowcreatewindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).| +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | **Example** ```js -windowClass.hideWithAnimation((err, data) => { +let windowClass = null; +window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, (err, data) => { if (err.code) { - console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); + console.error('Failed to create the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in hiding the window with animation. data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in creating the window. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); +}); ``` -### hideWithAnimation9+ +## window.create(deprecated) -hideWithAnimation(): Promise<void> +create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> -Hides this window and plays an animation during the process. This API uses a promise to return the result. +Creates a subwindow in the FA model -**System API**: This is a system API. +or a system window in the stage model. 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 [createWindow()](#windowcreatewindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-service-extension-context.md).| +| id | string | Yes | Window ID. | +| type | [WindowType](#windowtype7) | Yes | Window type. | + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the subwindow created.| **Example** ```js -let promise = windowClass.hideWithAnimation(); +let windowClass = null; +let promise = window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT); promise.then((data)=> { - console.info('Succeeded in hiding the window with animation. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in creating the window. Data:' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); -}) + console.error('Failed to create the Window. Cause:' + JSON.stringify(err)); +}); ``` -### show7+ +## window.find(deprecated) -show(callback: AsyncCallback<void>): void +find(id: string, callback: AsyncCallback<Window>): void -Shows this window. This API uses an asynchronous callback to return the result. +Finds a window based on the ID. 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 [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------ | +| id | string | Yes | Window ID. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the window found.| **Example** ```js -windowClass.show((err, data) => { +let windowClass = null; +window.find('alertWindow', (err, data) => { if (err.code) { - console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); +}); ``` -### show7+ +## window.find(deprecated) -show(): Promise<void> +find(id: string): Promise<Window> -Shows this window. This API uses a promise to return the result. +Finds a window based on the ID. 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 [findWindow()](#windowfindwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| id | string | Yes | Window ID.| + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | ------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the window found.| **Example** ```js -let promise = windowClass.show(); +let windowClass = null; +let promise = window.find('alertWindow'); promise.then((data)=> { - console.info('Succeeded in showing the window. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in finding the window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); -}) + console.error('Failed to find the Window. Cause: ' + JSON.stringify(err)); +}); ``` -### showWithAnimation9+ +## window.getTopWindow(deprecated) -showWithAnimation(callback: AsyncCallback<void>): void +getTopWindow(callback: AsyncCallback<Window>): void -Shows this window and plays an animation during the process. This API uses an asynchronous callback to return the result. +Obtains the top window of the current application. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9) instead. + +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | -------------------------------------------- | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained.| **Example** ```js -windowClass.showWithAnimation((err, data) => { +let windowClass = null; +window.getTopWindow((err, data) => { if (err.code) { - console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}); ``` -### showWithAnimation9+ +## window.getTopWindow(deprecated) -showWithAnimation(): Promise<void> +getTopWindow(): Promise<Window> -Shows this window and plays an animation during the process. This API uses a promise to return the result. +Obtains the top window of the current application. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getLastWindow()](#windowgetlastwindow9-1) instead. + +**Model restriction**: This API can be used only in the FA model. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | ----------------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the top window obtained.| **Example** ```js -let promise = windowClass.showWithAnimation(); +let windowClass = null; +let promise = window.getTopWindow(); promise.then((data)=> { - console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); }) ``` -### destroy7+ +## window.getTopWindow(deprecated) -destroy(callback: AsyncCallback<void>): void +getTopWindow(ctx: BaseContext, callback: AsyncCallback<Window>): void -Destroys this window. This API uses an asynchronous callback to return the result. +Obtains the top window of the current application. 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 [getLastWindow()](#windowgetlastwindow9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the top window obtained. | **Example** ```js -windowClass.destroy((err, data) => { +let windowClass = null; +window.getTopWindow(this.context, (err, data) => { if (err.code) { - console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); -}) + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); +}); ``` -### destroy7+ +## window.getTopWindow(deprecated) -destroy(): Promise<void> +getTopWindow(ctx: BaseContext): Promise<Window> -Destroys this window. This API uses a promise to return the result. +Obtains the top window of the current application. 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 [getLastWindow()](#windowgetlastwindow9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ------------------------------------------------------------ | +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-Context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| -------------------------------- | ----------------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the top window obtained.| **Example** ```js -let promise = windowClass.destroy(); +let windowClass = null; +let promise = window.getTopWindow(this.context); promise.then((data)=> { - console.info('Succeeded in destroying the window. Data: ' + JSON.stringify(data)); + windowClass = data; + console.info('Succeeded in obtaining the top window. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); + console.error('Failed to obtain the top window. Cause: ' + JSON.stringify(err)); }) ``` -### moveTo7+ +## Window -moveTo(x: number, y: number, callback: AsyncCallback<void>): void +Represents the current window instance, which is the basic unit managed by the window manager. -Moves this window. This API uses an asynchronous callback to return the result. +In the following API examples, you must use [getLastWindow()](#windowgetlastwindow9), [createWindow()](#windowcreatewindow9), or [findWindow()](#windowfindwindow9) to obtain a **Window** instance and then call a method in this instance. + +### hide7+ + +hide (callback: AsyncCallback<void>): void + +Hides this window. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------- | -| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| -| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -windowClass.moveTo(300, 300, (err, data)=>{ +windowClass.hide((err) => { if (err.code) { - console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); - -}); + console.info('Succeeded in hiding the window. data: ' + JSON.stringify(data)); +}) ``` -### moveTo7+ - -moveTo(x: number, y: number): Promise<void> +### hide7+ -Moves this window. This API uses a promise to return the result. +hide(): Promise<void> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Hides this window. This API uses a promise to return the result. -**Parameters** +**System API**: This is a system API. -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------- | -| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| -| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** @@ -1160,59 +1241,72 @@ Moves this window. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js -let promise = windowClass.moveTo(300, 300); -promise.then((data)=> { - console.info('Succeeded in moving the window. Data: ' + JSON.stringify(data)); +let promise = windowClass.hide(); +promise.then(()=> { + console.info('Succeeded in hiding the window.'); }).catch((err)=>{ - console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); + console.error('Failed to hide the window. Cause: ' + JSON.stringify(err)); }) ``` -### resetSize7+ +### hideWithAnimation9+ -resetSize(width: number, height: number, callback: AsyncCallback<void>): void +hideWithAnimation(callback: AsyncCallback<void>): void -Changes the size of this window. This API uses an asynchronous callback to return the result. +Hides this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------------- | -| width | number | Yes | New width of the window, in px.| -| height | number | Yes | New height of the window, in px.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | **Example** ```js -windowClass.resetSize(500, 1000, (err, data) => { +windowClass.hideWithAnimation((err) => { if (err.code) { - console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); -}); + console.info('Succeeded in hiding the window with animation.'); +}) ``` -### resetSize7+ - -resetSize(width: number, height: number): Promise<void> +### hideWithAnimation9+ -Changes the size of this window. This API uses a promise to return the result. +hideWithAnimation(): Promise<void> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Hides this window and plays an animation during the process. This API uses a promise to return the result. -**Parameters** +**System API**: This is a system API. -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------- | -| width | number | Yes | New width of the window, in px.| -| height | number | Yes | New height of the window, in px.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** @@ -1220,323 +1314,660 @@ Changes the size of this window. This API uses a promise to return the result. | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | + **Example** ```js -let promise = windowClass.resetSize(500, 1000); -promise.then((data)=> { - console.info('Succeeded in changing the window size. Data: ' + JSON.stringify(data)); +let promise = windowClass.hideWithAnimation(); +promise.then(()=> { + console.info('Succeeded in hiding the window with animation. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); -}); + console.error('Failed to hide the window with animation. Cause: ' + JSON.stringify(err)); +}) ``` -### setWindowType(deprecated) - -setWindowType(type: WindowType, callback: AsyncCallback<void>): void - -Sets the type of this window. This API uses an asynchronous callback to return the result. +### showWindow9+ -**System API**: This is a system API. +showWindow(callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +Shows this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| type | [WindowType](#windowtype) | Yes | Window type.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -let type = window.WindowType.TYPE_APP; -windowClass.setWindowType(type, (err, data) => { - if (err.code) { - console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)); +windowClass.showWindow((err) => { + if (err.code) { + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window.'); }); ``` -### setWindowType(deprecated) - -setWindowType(type: WindowType): Promise<void> - -Sets the type of this window. This API uses a promise to return the result. +### showWindow9+ -**System API**: This is a system API. +showWindow(): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +Shows this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------------- | ---- | ---------- | -| type | [WindowType](#windowtype) | Yes | Window type.| - **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ----------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js -let type = window.WindowType.TYPE_APP; -let promise = windowClass.setWindowType(type); -promise.then((data)=> { - console.info('Succeeded in setting the window type. Data: ' + JSON.stringify(data)); +let promise = windowClass.showWindow(); +promise.then(()=> { + console.info('Succeeded in showing the window.'); }).catch((err)=>{ - console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); }); ``` -### getProperties +### showWithAnimation9+ -getProperties(callback: AsyncCallback<WindowProperties>): void +showWithAnimation(callback: AsyncCallback<void>): void -Obtains the properties of this window. This API uses an asynchronous callback to return the result. +Shows this window and plays an animation during the process. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------------------- | ---- | ---------------------------- | -| callback | AsyncCallback<[WindowProperties](#windowproperties)> | Yes | Callback used to return the window properties.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | **Example** ```js -windowClass.getProperties((err, data) => { +windowClass.showWithAnimation((err) => { if (err.code) { - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); -}); + console.info('Succeeded in showing the window with animation.'); +}) ``` -### getProperties +### showWithAnimation9+ + +showWithAnimation(): Promise<void> -getProperties(): Promise<WindowProperties> +Shows this window and plays an animation during the process. This API uses a promise to return the result. -Obtains the properties of this window. This API uses a promise to return the result. +**System API**: This is a system API. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ---------------------------------------------------- | ------------------------------- | -| Promise<[WindowProperties](#windowproperties)> | Promise used to return the window properties.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | +| 1300004 | Unauthorized operation. | **Example** ```js -let promise = windowClass.getProperties(); -promise.then((data)=> { - console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +let promise = windowClass.showWithAnimation(); +promise.then(()=> { + console.info('Succeeded in showing the window with animation.'); }).catch((err)=>{ - console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); -}); + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); +}) ``` -### getAvoidArea7+ +### destroyWindow9+ -getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void +destroyWindow(callback: AsyncCallback<void>): void -Obtains the area where this window cannot be displayed, for example, the system bar area and notch. This API uses an asynchronous callback to return the result. +Destroys this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- |-----------------------------------------------| ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. `TYPE_SYSTEM_GESTURE` indicates the gesture area. `TYPE_KEYBOARD` indicates the soft keyboard area.| -| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -let type = window.AvoidAreaType.TYPE_SYSTEM; -windowClass.getAvoidArea(type, (err, data) => { +windowClass.destroyWindow((err) => { if (err.code) { - console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); + console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); -}); + console.info('Succeeded in destroying the window.'); +}) ``` -### getAvoidArea7+ +### destroyWindow9+ -getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise<[AvoidArea](#avoidarea7)> +destroyWindow(): Promise<void> -Obtains the area where this window cannot be displayed, for example, the system bar area and notch. This API uses a promise to return the result. +Destroys this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Parameters** +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| -| Name| Type | Mandatory| Description | -| ------ |----------------------------------| ---- | ------------------------------------------------------------ | -| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. `TYPE_SYSTEM` indicates the default area of the system. `TYPE_CUTOUT` indicates the notch. `TYPE_SYSTEM_GESTURE` indicates the gesture area. `TYPE_KEYBOARD` indicates the soft keyboard area.| +**Error codes** -**Return value** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Type | Description | -|-----------------------------------------| ----------------------------------- | -| Promise<[AvoidArea](#avoidarea7)> | Promise used to return the area.| +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -let type = window.AvoidAreaType.TYPE_SYSTEM; -let promise = windowClass.getAvoidArea(type); -promise.then((data)=> { - console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +let promise = windowClass.destroyWindow(); +promise.then(()=> { + console.info('Succeeded in destroying the window.'); }).catch((err)=>{ - console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); -}); + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); +}) ``` -### setFullScreen +### moveWindowTo9+ -setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void +moveWindowTo(x: number, y: number, callback: AsyncCallback<void>): void -Sets whether to enable the full-screen mode for this window. This API uses an asynchronous callback to return the result. +Moves this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------------------------- | ---- | ---------------------------------------------- | -| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------------------------------------------- | +| x | number | Yes| Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| +| y | number | Yes| Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -let isFullScreen = true; -windowClass.setFullScreen(isFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.moveWindowTo(300, 300, (err)=>{ + if (err.code) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the window.'); + }); +} catch (exception) { + console.error('Failed to move the window. Cause:' + JSON.stringify(exception)); +}; ``` -### setFullScreen +### moveWindowTo9+ -setFullScreen(isFullScreen: boolean): Promise<void> +moveWindowTo(x: number, y: number): Promise<void> -Sets whether to enable the full-screen mode for this window. This API uses a promise to return the result. +Moves this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------- | ---- | ---------------------------------------------- | -| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden.| +| Name| Type| Mandatory| Description| +| -- | ----- | -- | --------------------------------------------- | +| x | number | Yes| Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right.| +| y | number | Yes| Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -let isFullScreen = true; -let promise = windowClass.setFullScreen(isFullScreen); -promise.then((data)=> { - console.info('Succeeded in enabling the full-screen mode. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.moveWindowTo(300, 300); + promise.then(()=> { + console.info('Succeeded in moving the window.'); + }).catch((err)=>{ + console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to move the window. Cause:' + JSON.stringify(exception)); +}; ``` -### setLayoutFullScreen7+ +### resize9+ -setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void +resize(width: number, height: number, callback: AsyncCallback<void>): void -Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result. +Changes the size of this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------------ | ------------------------- | ---- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | ------------------------ | +| width | number | Yes| New width of the window, in px.| +| height | number | Yes| New height of the window, in px.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | -**Example** +**Error codes** -```js -let isLayoutFullScreen= true; -windowClass.setLayoutFullScreen(isLayoutFullScreen, (err, data) => { - if (err.code) { - console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); -}); -``` +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -### setLayoutFullScreen7+ +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | -setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> +**Example** -Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result. +```js +try { + windowClass.resize(500, 1000, (err) => { + if (err.code) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the window size.'); + }); +} catch (exception) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(exception)); +}; +``` + +### resize9+ + +resize(width: number, height: number): Promise<void> + +Changes the size of this window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------------ | ------- | ---- | ------------------------------------------------------------ | -| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed.| +| Name| Type| Mandatory| Description| +| ------ | ------ | -- | ------------------------ | +| width | number | Yes| New width of the window, in px.| +| height | number | Yes| New height of the window, in px.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +try { + let promise = windowClass.resize(500, 1000); + promise.then(()=> { + console.info('Succeeded in changing the window size.'); + }).catch((err)=>{ + console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to change the window size. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowMode9+ + +setWindowMode(mode: WindowMode, callback: AsyncCallback<void>): void + +Sets the mode of this window. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------------------------- | -- | --------- | +| mode | [WindowMode](#windowmode7) | Yes| Window mode to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let mode = window.WindowMode.FULLSCREEN; +try { + windowClass.setWindowMode(mode, (err) => { + if (err.code) { + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window mode.'); + }); +} catch (exception) { + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowMode9+ + +setWindowMode(mode: WindowMode): Promise<void> + +Sets the type of this window. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------------------------- | -- | --------- | +| mode | [WindowMode](#windowmode7) | Yes| Window mode to set.| + +**Return value** + +| Type| Description| +| ------------------- | ----------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let mode = window.WindowMode.FULLSCREEN; +try { + let promise = windowClass.setWindowMode(type); + promise.then(()=> { + console.info('Succeeded in setting the window mode.'); + }).catch((err)=>{ + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window mode. Cause: ' + JSON.stringify(exception)); +}; +``` + +### getWindowProperties9+ + +getWindowProperties(): WindowProperties + +Obtains the properties of this window. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type| Description| +| ------------------------------------- | ------------- | +| [WindowProperties](#windowproperties) | Window properties obtained.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +try { + let properties = windowClass.getWindowProperties(); +} catch (exception) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(exception)); +}; +``` + +### getWindowAvoidArea9+ + +getWindowAvoidArea(type: AvoidAreaType): AvoidArea + +Obtains the area where this window cannot be displayed, for example, the system bar area, notch, gesture area, and soft keyboard area. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---- |----------------------------------| -- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes| Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area.| + +**Return value** + +| Type| Description| +|--------------------------| ----------------- | +| [AvoidArea](#avoidarea7) | Area where the window cannot be displayed.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let type = window.AvoidAreaType.TYPE_SYSTEM; +try { + let avoidArea = windowClass.getWindowAvoidArea(type); +} catch (exception) { + console.error('Failed to obtain the area. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowLayoutFullScreen9+ + +setWindowLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void + +Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------------ | ------------------------- | -- | --------- | +| isLayoutFullScreen | boolean | Yes| Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isLayoutFullScreen= true; +try { + windowClass.setWindowLayoutFullScreen(isLayoutFullScreen, (err) => { + if (err.code) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window layout to full-screen mode.'); + }); +} catch (exception) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowLayoutFullScreen9+ + +setWindowLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> + +Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------------ | ------- | -- | ------------------------------------------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes| Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let isLayoutFullScreen = true; -let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen); -promise.then((data)=> { - console.info('Succeeded in setting the window layout to full-screen mode. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setWindowLayoutFullScreen(isLayoutFullScreen); + promise.then(()=> { + console.info('Succeeded in setting the window layout to full-screen mode.'); + }).catch((err)=>{ + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(exception)); +}; ``` -### setSystemBarEnable7+ +### setWindowSystemBarEnable9+ -setSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void +setWindowSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void Sets whether to display the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. @@ -1544,28 +1975,41 @@ Sets whether to display the status bar and navigation bar in this window. This A **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to `['status', 'navigation']`. By default, they are not displayed.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | --------- | +| names | Array | Yes| Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js // In this example, the status bar and navigation bar are not displayed. let names = []; -windowClass.setSystemBarEnable(names, (err, data) => { - if (err.code) { - console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.setWindowSystemBarEnable(names, (err) => { + if (err.code) { + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar to be invisible.'); + }); +} catch (exception) { + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(exception)); +}; ``` -### setSystemBarEnable7+ +### setWindowSystemBarEnable9+ -setSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void> +setWindowSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void> Sets whether to display the status bar and navigation bar in this window. This API uses a promise to return the result. @@ -1573,32 +2017,45 @@ Sets whether to display the status bar and navigation bar in this window. This A **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----- | ---- | ------------------------------------------------------------ | -| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to `['status', 'navigation']`. By default, they are not displayed.| +| Name| Type | Mandatory| Description| +| ----- | ----- | -- | ------------------------------------------------------------------------------------------------------------ | +| names | Array | Yes| Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js // In this example, the status bar and navigation bar are not displayed. let names = []; -let promise = windowClass.setSystemBarEnable(names); -promise.then((data)=> { - console.info('Succeeded in setting the system bar to be invisible. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setWindowSystemBarEnable(names); + promise.then(()=> { + console.info('Succeeded in setting the system bar to be invisible.'); + }).catch((err)=>{ + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(exception)); +}; ``` -### setSystemBarProperties +### setWindowSystemBarProperties9+ -setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void +setWindowSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void Sets the properties of the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. @@ -1611,31 +2068,41 @@ Sets the properties of the status bar and navigation bar in this window. This AP | SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - // The following properties are supported since API version 7. - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, // The following properties are supported since API version 8. statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' }; -windowClass.setSystemBarProperties(SystemBarProperties, (err, data) => { - if (err.code) { - console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.setWindowSystemBarProperties(SystemBarProperties, (err) => { + if (err.code) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the system bar properties.'); + }); +} catch (exception) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(exception)); +}; ``` -### setSystemBarProperties +### setWindowSystemBarProperties9+ -setSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void> +setWindowSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void> Sets the properties of the status bar and navigation bar in this window. This API uses a promise to return the result. @@ -1653,25 +2120,35 @@ Sets the properties of the status bar and navigation bar in this window. This AP | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - // The following properties are supported since API version 7. - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, // The following properties are supported since API version 8. statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' }; -let promise = windowClass.setSystemBarProperties(SystemBarProperties); -promise.then((data)=> { - console.info('Succeeded in setting the system bar properties. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setWindowSystemBarProperties(SystemBarProperties); + promise.then(()=> { + console.info('Succeeded in setting the system bar properties.'); + }).catch((err)=>{ + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(exception)); +}; ``` ### setPreferredOrientation9+ @@ -1689,17 +2166,29 @@ Sets the preferred orientation for this window. This API uses an asynchronous ca | Orientation | [Orientation](#orientation9) | Yes | Orientation to set. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js let orientation = window.Orientation.AUTO_ROTATION; -windowClass.setPreferredOrientation(orientation, (err, data) => { - if (err.code) { - console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting window orientation. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.setPreferredOrientation(orientation, (err) => { + if (err.code) { + console.error('Failed to set window orientation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window orientation.'); + }); +} catch (exception) { + console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception)); +}; ``` ### setPreferredOrientation9+ @@ -1722,21 +2211,33 @@ Sets the preferred orientation for this window. This API uses a promise to retur | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + **Example** ```js let orientation = window.Orientation.AUTO_ROTATION; -let promise = windowClass.setPreferredOrientation(orientation); -promise.then((data)=> { - console.info('Succeeded in setting the window orientation. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the window orientation. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setPreferredOrientation(orientation); + promise.then(()=> { + console.info('Succeeded in setting the window orientation.'); + }).catch((err)=>{ + console.error('Failed to set the window orientation. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set window orientation. Cause: ' + JSON.stringify(exception)); +}; ``` -### loadContent7+ +### setUIContent9+ -loadContent(path: string, callback: AsyncCallback<void>): void +setUIContent(path: string, callback: AsyncCallback<void>): void Loads content from a page to this window. This API uses an asynchronous callback to return the result. @@ -1744,26 +2245,39 @@ Loads content from a page to this window. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| path | string | Yes | Path of the page from which the content will be loaded.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name| Type| Mandatory| Description| +| -------- | ------------------------- | -- | -------------------- | +| path | string | Yes| Path of the page from which the content will be loaded.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** ```js -windowClass.loadContent('pages/page2/page2', (err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.setUIContent('pages/page2/page2', (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); +} catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); +}; ``` -### loadContent7+ +### setUIContent9+ -loadContent(path: string): Promise<void> +setUIContent(path: string): Promise<void> Loads content from a page to this window. This API uses a promise to return the result. @@ -1771,26 +2285,40 @@ Loads content from a page to this window. This API uses a promise to return the **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------- | -| path | string | Yes | Path of the page from which the content will be loaded.| +| Name| Type| Mandatory| Description| +| ---- | ------ | -- | ------------------ | +| path | string | Yes| Path of the page from which the content will be loaded.| **Return value** -| Type | Description | -| ------------------- | ------------------------- | +| Type| Description| +| ------------------- | ------------------------ | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js -let promise = windowClass.loadContent('pages/page2/page2'); -promise.then((data)=> { - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); -}); +try { + let promise = windowClass.setUIContent('pages/page2/page2'); + promise.then(()=> { + console.info('Succeeded in loading the content.'); + }).catch((err)=>{ + console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to load the content. Cause: ' + JSON.stringify(exception)); +}; ``` + ### loadContent9+ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void @@ -1806,27 +2334,35 @@ Loads content from a page associated with a local storage to this window. This A | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```ts -class myAbility extends Ability { - storage : LocalStorage - onWindowStageCreate(windowStage) { - this.storage = new LocalStorage(); - this.storage.setOrCreate('storageSimpleProp',121); - console.log('onWindowStageCreate'); - windowStage.loadContent('pages/page2',this.storage,(err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }); - } -} +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +console.log('onWindowStageCreate'); +try { + windowClass.loadContent('pages/page2', storage, (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); +} catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); +}; ``` ### loadContent9+ @@ -1844,7 +2380,7 @@ Loads content from a page associated with a local storage to this window. This A | Name | Type | Mandatory| Description | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| **Return value** @@ -1852,75 +2388,64 @@ Loads content from a page associated with a local storage to this window. This A | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| -**Example** - -```ts -class myAbility extends Ability { - storage : LocalStorage - onWindowStageCreate(windowStage) { - this.storage = new LocalStorage(); - this.storage.setOrCreate('storageSimpleProp',121); - console.log('onWindowStageCreate'); - let windowClass = null; - let promise = windowStage.loadContent('pages/page2',this.storage); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - }) - } -} -``` -### isShowing7+ - -isShowing(callback: AsyncCallback<boolean>): void - -Checks whether this window is displayed. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** -**Parameters** +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | **Example** -```js -windowClass.isShowing((err, data) => { - if (err.code) { - console.error('Failed to check whether the window is showing. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); -}); +```ts +let storage = new LocalStorage(); +storage.setOrCreate('storageSimpleProp',121); +console.log('onWindowStageCreate'); +try { + let promise = windowClass.loadContent('pages/page2', storage); + promise.then(() => { + console.info('Succeeded in loading the content.'); + }).catch((err) => { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); +}; ``` -### isShowing7+ +### isWindowShowing9+ -isShowing(): Promise<boolean> +isWindowShowing(): boolean -Checks whether this window is displayed. This API uses a promise to return the result. +Checks whether this window is displayed. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value `true` means that the window is displayed, and `false` means the opposite.| +| Type| Description| +| ------- | ------------------------------------------------------------------ | +| boolean | Whether the window is displayed. The value **true** means that the window is displayed, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -let promise = windowClass.isShowing(); -promise.then((data)=> { +try { + let data = windowClass.isWindowShowing(); console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(err)); -}); +} catch (exception) { + console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('windowSizeChange')7+ @@ -1935,20 +2460,24 @@ Enables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ------------------------------ | ---- | -------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.| | callback | Callback<[Size](#size7)> | Yes | Callback used to return the window size. | **Example** ```js -windowClass.on('windowSizeChange', (data) => { - console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.on('windowSizeChange', (data) => { + console.info('Succeeded in enabling the listener for window size changes. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to enable the listener for window size changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('windowSizeChange')7+ -off(type: 'windowSizeChange', callback?: Callback<Size >): void +off(type: 'windowSizeChange', callback?: Callback<Size>): void Disables listening for window size changes. @@ -1958,69 +2487,22 @@ Disables listening for window size changes. | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | -------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `windowSizeChange`, indicating the window size change event.| +| type | string | Yes | Event type. The value is fixed at **'windowSizeChange'**, indicating the window size change event.| | callback | Callback<[Size](#size)> | No | Callback used to return the window size. | **Example** ```js -windowClass.off('windowSizeChange'); -``` - -### on('systemAvoidAreaChange')(deprecated) - -on(type: 'systemAvoidAreaChange', callback: Callback<[AvoidArea](#avoidarea7)>): void - -Enables listening for changes to the area where the window cannot be displayed. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. Use [on('avoidAreaChange')](#onavoidareachange9) instead. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- |------------------------------------------| ---- | ------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | - -**Example** - -```js -windowClass.on('systemAvoidAreaChange', (data) => { - console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data)); -}); -``` - -### off('systemAvoidAreaChange')(deprecated) - -off(type: 'systemAvoidAreaChange', callback?: Callback<[AvoidArea](#avoidarea7)>): void - -Disables listening for changes to the area where the window cannot be displayed. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- |------------------------------------------| ---- | ------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at `systemAvoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| -| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | - -**Example** - -```js -windowClass.off('systemAvoidAreaChange'); +try { + windowClass.off('windowSizeChange'); +} catch (exception) { + console.error('Failed to disable the listener for window size changes. Cause: ' + JSON.stringify(exception)); +}; ``` - ### on('avoidAreaChange')9+ -on(type: 'avoidAreaChange', callback: Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}>): void +on(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void Enables listening for changes to the area where the window cannot be displayed. @@ -2030,20 +2512,25 @@ Enables listening for changes to the area where the window cannot be displayed. | Name | Type | Mandatory| Description | | -------- |------------------------------------------------------------------| ---- |--------------------------------------| -| type | string | Yes | Event type. The value is fixed at `avoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| type | string | Yes | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| | callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | Yes | Callback used to return the area and area type.| **Example** ```js -windowClass.on('avoidAreaChange', (data) => { - console.info('Succeeded in enabling the listener for system avoid area changes. type:' + JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area)); -}); +try { + windowClass.on('avoidAreaChange', (data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. type:' + + JSON.stringify(data.type) + ', area: ' + JSON.stringify(data.area)); + }); +} catch (exception) { + console.error('Failed to enable the listener for system avoid area changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('avoidAreaChange')9+ -off(type: 'avoidAreaChange', callback: Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}>): void +off(type: 'avoidAreaChange', callback: Callback<{AvoidAreaType, AvoidArea}>): void Disables listening for changes to the area where the window cannot be displayed. @@ -2053,13 +2540,17 @@ Disables listening for changes to the area where the window cannot be displayed. | Name | Type | Mandatory | Description | | -------- |-----------------------------------------------------------------------------|-----|------------------------------------| -| type | string | Yes | Event type. The value is fixed at `avoidAreaChange`, indicating the event of changes to the area where the window cannot be displayed.| +| type | string | Yes | Event type. The value is fixed at **'avoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed.| | callback | Callback<{[AvoidAreaType](#avoidareatype7), [AvoidArea](#avoidarea7)}> | No | Callback used to return the area and area type.| **Example** ```js -windowClass.off('avoidAreaChange'); +try { + windowClass.off('avoidAreaChange'); +} catch (exception) { + console.error('Failed to disable the listener for system avoid area changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('keyboardHeightChange')7+ @@ -2074,15 +2565,19 @@ Enables listening for keyboard height changes. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| -| callback | Callback { - console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); -}); +try { + windowClass.on('keyboardHeightChange', (data) => { + console.info('Succeeded in enabling the listener for keyboard height changes. Data: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('Failed to enable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('keyboardHeightChange')7+ @@ -2097,13 +2592,17 @@ Disables listening for keyboard height changes. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `keyboardHeightChange`, indicating the keyboard height change event.| +| type | string | Yes | Event type. The value is fixed at **'keyboardHeightChange'**, indicating the keyboard height change event.| | callback | Callback<number> | No | Callback used to return the current keyboard height. | **Example** ```js -windowClass.off('keyboardHeightChange'); +try { + windowClass.off('keyboardHeightChange'); +} catch (exception) { + console.error('Failed to disable the listener for keyboard height changes. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('touchOutside')9+ @@ -2120,15 +2619,19 @@ Enables listening for click events outside this window. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `touchOutside`, indicating the click event outside this window.| -| callback | Callback { - console.info('touch outside'); -}); +try { + windowClass.on('touchOutside', () => { + console.info('touch outside'); + }); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('touchOutside')9+ @@ -2145,13 +2648,17 @@ Disables listening for click events outside this window. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `touchOutside`, indicating the click event outside this window.| -| callback | Callback<number> | No | Callback used to Callback used to return the click event outside this window. | +| type | string | Yes | Event type. The value is fixed at **'touchOutside'**, indicating the click event outside this window.| +| callback | Callback<number> | No | Callback used to return the click event outside this window. | **Example** ```js -windowClass.off('touchOutside'); +try { + windowClass.off('touchOutside'); +} catch (exception) { + console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('screenshot')9+ @@ -2166,15 +2673,19 @@ Subscribes to screenshot events. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `screenshot`, indicating the screenshot event.| +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| | callback | Callback<void> | Yes | Callback invoked when a screenshot event occurs. | **Example** ```js -windowClass.on('screenshot', () => { - console.info('screenshot happened'); -}); +try { + windowClass.on('screenshot', () => { + console.info('screenshot happened'); + }); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('screenshot')9+ @@ -2189,7 +2700,7 @@ Unsubscribes from screenshot events. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `screenshot`, indicating the screenshot event.| +| type | string | Yes | Event type. The value is fixed at **'screenshot'**, indicating the screenshot event.| | callback | Callback<void> | No | Callback invoked when a screenshot event occurs.| **Example** @@ -2197,12 +2708,19 @@ Unsubscribes from screenshot events. ```js let callback = ()=>{ console.info('screenshot happened'); -} -windowClass.on('screenshot', callback) -windowClass.off('screenshot', callback) - -// If multiple callbacks are enabled in on(), they will all be disabled. -windowClass.off('screenshot'); +}; +try { + windowClass.on('screenshot', callback); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; +try { + windowClass.off('screenshot', callback); + // If multiple callbacks are enabled in on(), they will all be disabled. + windowClass.off('screenshot'); +} catch (exception) { + console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### on('dialogTargetTouch')9+ @@ -2217,15 +2735,19 @@ Subscribes to click events of the target window in the modal window mode. | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `dialogTargetTouch`, indicating the click event of the target window in the modal window mode.| +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| | callback | Callback<void>| Yes | Callback invoked when the click event occurs in the target window of the modal window mode.| **Example** ```js -windowClass.on('dialogTargetTouch', () => { - console.info('touch dialog target'); -}); +try { + windowClass.on('dialogTargetTouch', () => { + console.info('touch dialog target'); + }); +} catch (exception) { + console.error('Failed to register callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### off('dialogTargetTouch')9+ @@ -2240,13 +2762,17 @@ Unsubscribes from click events of the target window in the modal window mode. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `dialogTargetTouch`, indicating the click event of the target window in the modal window mode.| +| type | string | Yes | Event type. The value is fixed at **'dialogTargetTouch'**, indicating the click event of the target window in the modal window mode.| | callback | Callback<void> | No | Callback invoked when the click event occurs in the target window of the modal window mode.| **Example** ```js -windowClass.off('dialogTargetTouch'); +try { + windowClass.off('dialogTargetTouch'); +} catch (exception) { + console.error('Failed to unregister callback. Cause: ' + JSON.stringify(exception)); +}; ``` ### bindDialogTarget9+ @@ -2267,6 +2793,15 @@ Binds the modal window to the target window, and adds a callback to listen for m | deathCallback | Callback<void> | Yes | Callback used to listen for modal window destruction events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -2290,15 +2825,19 @@ class TestRemoteObject extends rpc.RemoteObject { } } let token = new TestRemoteObject('testObject'); -windowClass.bindDialogTarget(token, () => { - console.info('Dialog Window Need Destroy.'); -}, (err, data) => { - if (err.code) { - console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); -}); +try { + windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); + }, (err) => { + if (err.code) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in binding dialog target.'); + }); +} catch (exception) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(exception)); +}; ``` ### bindDialogTarget9+ @@ -2324,6 +2863,15 @@ Binds the modal window to the target window, and adds a callback to listen for m | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + **Example** ```js @@ -2347,1108 +2895,2950 @@ class TestRemoteObject extends rpc.RemoteObject { } } let token = new TestRemoteObject('testObject'); -let promise = windowClass.bindDialogTarget(token, () => { - console.info('Dialog Window Need Destroy.'); +try { + let promise = windowClass.bindDialogTarget(token, () => { + console.info('Dialog Window Need Destroy.'); + }); + promise.then(()=> { + console.info('Succeeded in binding dialog target.'); + }).catch((err)=>{ + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to bind dialog target. Cause:' + JSON.stringify(exception)); +}; +``` + +### isWindowSupportWideGamut9+ + +isWindowSupportWideGamut(callback: AsyncCallback<boolean>): void + +Checks whether this window supports the wide-gamut color space. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | ---------------------------- | -- | -------------------------------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +windowClass.isWindowSupportWideGamut((err, data) => { + if (err.code) { + console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); }); +``` + +### isWindowSupportWideGamut9+ + +isWindowSupportWideGamut(): Promise<boolean> + +Checks whether this window supports the wide-gamut color space. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type| Description| +| ---------------------- | ------------------------------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let promise = windowClass.isWindowSupportWideGamut(); promise.then((data)=> { - console.info('Succeeded in binding dialog target. Data:' + JSON.stringify(data)); + console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to bind dialog target. Cause:' + JSON.stringify(err)); + console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); }); ``` -### isSupportWideGamut8+ +### setWindowColorSpace9+ -isSupportWideGamut(callback: AsyncCallback<boolean>): void +setWindowColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void -Checks whether this window supports the wide color gamut mode. This API uses an asynchronous callback to return the result. +Sets a color space for this window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value `true` means that the wide color gamut mode is supported, and `false` means the opposite.| +| Name| Type| Mandatory| Description| +| ---------- | ------------------------- | -- | ----------- | +| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | **Example** ```js -windowClass.isSupportWideGamut((err, data) => { +try { + windowClass.setWindowColorSpace(window.ColorSpace.WIDE_GAMUT, (err) => { + if (err.code) { + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting window colorspace.'); + }); +} catch (exception) { + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowColorSpace9+ + +setWindowColorSpace(colorSpace:ColorSpace): Promise<void> + +Sets a color space for this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---------- | ------------------------- | -- | ------------- | +| colorSpace | [ColorSpace](#colorspace) | Yes| Color space to set.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +try { + let promise = windowClass.setWindowColorSpace(window.ColorSpace.WIDE_GAMUT); + promise.then(()=> { + console.info('Succeeded in setting window colorspace.'); + }).catch((err)=>{ + console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(exception)); +}; +``` + +### getWindowColorSpace9+ + +getWindowColorSpace(): ColorSpace + +Obtains the color space of this window. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type| Description| +| ------------------------- | ------------- | +| [ColorSpace](#colorspace) | Color space obtained.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let colorSpace = windowClass.getWindowColorSpace(); +``` + +### setWindowBackgroundColor9+ + +setWindowBackgroundColor(color: string): void + +Sets the background color for this window. In the stage model, this API must be used after [loadContent](#loadcontent9). + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----- | ------ | -- | ----------------------------------------------------------------------- | +| color | string | Yes| Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let color = '#00ff33'; +try { + windowClass.setWindowBackgroundColor(color); +} catch (exception) { + console.error('Failed to set the background color. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowBrightness9+ + +setWindowBrightness(brightness: number, callback: AsyncCallback<void>): void + +Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---------- | ------------------------- | -- | --------------------------------- | +| brightness | number | Yes| Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let brightness = 1; +try { + windowClass.setWindowBrightness(brightness, (err) => { + if (err.code) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the brightness.'); + }); +} catch (exception) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowBrightness9+ + +setWindowBrightness(brightness: number): Promise<void> + +Sets the screen brightness for this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ---------- | ------ | -- | --------------------------------- | +| brightness | number | Yes| Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let brightness = 1; +try { + let promise = windowClass.setWindowBrightness(brightness); + promise.then(()=> { + console.info('Succeeded in setting the brightness.'); + }).catch((err)=>{ + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowFocusable9+ + +setWindowFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void + +Sets whether this window can gain focus. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------------------------- | -- | ------------------------------------------------------- | +| isFocusable | boolean | Yes| Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isFocusable= true; +try { + windowClass.setWindowFocusable(isFocusable, (err) => { + if (err.code) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be focusable.'); + }); +} catch (exception) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowFocusable9+ + +setWindowFocusable(isFocusable: boolean): Promise<void> + +Sets whether this window can gain focus. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------- | -- | -------------------------------------------------------- | +| isFocusable | boolean | Yes| Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isFocusable= true; +try { + let promise = windowClass.setWindowFocusable(isFocusable); + promise.then(()=> { + console.info('Succeeded in setting the window to be focusable.'); + }).catch((err)=>{ + console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowKeepScreenOn9+ + +setWindowKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void + +Sets whether to keep the screen always on. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------------- | ------------------------- | -- | ---------------------------------------------------- | +| isKeepScreenOn | boolean | Yes| Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isKeepScreenOn = true; +try { + windowClass.setWindowKeepScreenOn(isKeepScreenOn, (err) => { + if (err.code) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the screen to be always on.'); + }); +} catch (exception) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowKeepScreenOn9+ + +setWindowKeepScreenOn(isKeepScreenOn: boolean): Promise<void> + +Sets whether to keep the screen always on. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------------- | ------- | -- | --------------------------------------------------- | +| isKeepScreenOn | boolean | Yes| Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isKeepScreenOn = true; +try { + let promise = windowClass.setWindowKeepScreenOn(isKeepScreenOn); + promise.then(() => { + console.info('Succeeded in setting the screen to be always on.'); + }).catch((err)=>{ + console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWakeUpScreen()9+ + +setWakeUpScreen(wakeUp: boolean): void + +Wakes up the screen. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------------- | ------- | ---- | ---------------------------- | +| wakeUp | boolean | Yes | Whether to wake up the screen. The value **true** means to wake up the screen, and **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let wakeUp = true; +try { + windowClass.setWakeUpScreen(wakeUp); +} catch (exception) { + console.error('Failed to wake up the screen. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowPrivacyMode9+ + +setWindowPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void + +Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Required permissions**: ohos.permission.PRIVACY_WINDOW + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------- | ------------------------- | -- | ------------------------------------------------------ | +| isPrivacyMode | boolean | Yes| Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let isPrivacyMode = true; +try { + windowClass.setWindowPrivacyMode(isPrivacyMode, (err) => { + if (err.code) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to privacy mode.'); + }); +} catch (exception) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowPrivacyMode9+ + +setWindowPrivacyMode(isPrivacyMode: boolean): Promise<void> + +Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Required permissions**: ohos.permission.PRIVACY_WINDOW + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------- | ------- | -- | ----------------------------------------------------- | +| isPrivacyMode | boolean | Yes| Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------ | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let isPrivacyMode = true; +try { + let promise = windowClass.setWindowPrivacyMode(isPrivacyMode); + promise.then(()=> { + console.info('Succeeded in setting the window to privacy mode.'); + }).catch((err)=>{ + console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setSnapshotSkip9+ +setSnapshotSkip(isSkip: boolean): void + +Sets whether to ignore this window during screen capturing or recording. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------- | ---- | -------------------- | +| isSkip | boolean | Yes | Whether to ignore the window. The default value is **false**.
The value **true** means that the window is ignored, and **false** means the opposite.
| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +```js +let isSkip = true; +try { + windowClass.setSnapshotSkip(isSkip); +} catch (exception) { + console.error('Failed to Skip. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setWindowTouchable9+ + +setWindowTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void + +Sets whether this window is touchable. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------------------------- | -- | ----------------------------------------------- | +| isTouchable | boolean | Yes| Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isTouchable = true; +try { + windowClass.setWindowTouchable(isTouchable, (err) => { + if (err.code) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be touchable.'); + }); +} catch (exception) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setWindowTouchable9+ + +setWindowTouchable(isTouchable: boolean): Promise<void> + +Sets whether this window is touchable. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----------- | ------- | -- | ----------------------------------------------- | +| isTouchable | boolean | Yes| Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite.| + +**Return value** + +| Type| Description| +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isTouchable = true; +try { + let promise = windowClass.setWindowTouchable(isTouchable); + promise.then(()=> { + console.info('Succeeded in setting the window to be touchable.'); + }).catch((err)=>{ + console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(exception)); +}; +``` + +### setForbidSplitMove9+ + +setForbidSplitMove(isForbidSplitMove: boolean, callback: AsyncCallback<void>): void + +Sets whether this window is forbidden to move in split-screen mode. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------- | ---- | -------------------- | +| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode. The value **true** means the window is forbidden to move in split-screen mode, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isForbidSplitMove = true; +try { + windowClass.setForbidSplitMove(isForbidSplitMove, (err) => { + if (err.code) { + console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in forbidding window moving in split screen mode.'); + }); +} catch (exception) { + console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### setForbidSplitMove9+ + +setForbidSplitMove(isForbidSplitMove: boolean): Promise<void> + +Sets whether this window is forbidden to move in split-screen mode. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------- | ---- | -------------------- | +| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode. The value **true** means the window is forbidden to move in split-screen mode, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 1300002 | This window state is abnormal. | +| 1300003 | This window manager service works abnormally. | + +**Example** + +```js +let isForbidSplitMove = true; +try { + let promise = windowClass.setForbidSplitMove(isForbidSplitMove); + promise.then(()=> { + console.info('Succeeded in forbidding window moving in split screen mode.'); + }).catch((err)=>{ + console.error('Failed to forbid window moving in split screen mode. Cause: ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(exception)); +}; +``` + +### snapshot9+ + +snapshot(callback: AsyncCallback<image.PixelMap>): void + +Captures this window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ----------------------------------- | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +windowClass.snapshot((err, pixelMap) => { + if (err.code) { + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}); +``` + +### snapshot9+ + +snapshot(): Promise<image.PixelMap> + +Captures this window. This API uses a promise to return the result. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | --------------------------------------------- | +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | + +**Example** + +```js +let promise = windowClass.snapshot(); +promise.then((pixelMap)=> { + console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); + pixelMap.release(); // Release the memory in time after the PixelMap is used. +}).catch((err)=>{ + console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); +}); +``` + +### opacity9+ + +opacity(opacity: number): void + +Sets the opacity for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | --------- | ------------------------------------------------- | +| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.opacity(0.5); +} catch (exception) { + console.error('Failed to opacity. Cause: ' + JSON.stringify(exception)); +}; +``` + +### scale9+ + +scale(scaleOptions: ScaleOptions): void + +Sets the scale parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------------------------------ | --------- | ------------------------ | +| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let obj : window.ScaleOptions = { + x : 2.0, + y : 1.0, + pivotX : 0.5, + pivotY : 0.5 +}; +try { + windowClass.scale(obj); +} catch (exception) { + console.error('Failed to scale. Cause: ' + JSON.stringify(exception)); +}; +``` + +### rotate9+ + +rotate(rotateOptions: RotateOptions): void + +Sets the rotation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------- | -------------------------------- | --------- | --------------------------- | +| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let obj : window.RotateOptions = { + x : 1.0, + y : 1.0, + z : 45.0, + pivotX : 0.5, + pivotY : 0.5 +}; +try { + windowClass.rotate(obj); +} catch (exception) { + console.error('Failed to rotate. Cause: ' + JSON.stringify(exception)); +}; +``` + +### translate9+ + +translate(translateOptions: TranslateOptions): void + +Sets the translation parameters for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | -------------------------------------- | --------- | ------------------------------ | +| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters to set. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 +}; +try { + windowClass.translate(obj); +} catch (exception) { + console.error('Failed to translate. Cause: ' + JSON.stringify(exception)); +}; +``` + +### getTransitionController9+ + + getTransitionController(): TransitionController + +Obtains the transition animation controller. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------- | -------------------------------- | +| [TransitionController](#transitioncontroller9) | Transition animation controller. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +let controller = windowClass.getTransitionController(); // Obtain the transition animation controller. +controller.animationForHidden = (context : window.TransitionContext) => { + let toWindow = context.toWindow; + animateTo({ + duration: 1000, // Animation duration. + tempo: 0.5, // Playback speed. + curve: Curve.EaseInOut, // Animation curve. + delay: 0, // Animation delay. + iterations: 1, // Number of playback times. + playMode: PlayMode.Normal // Animation playback mode. + onFinish: ()=> { + context.completeTransition(true) + } + }, () => { + let obj : window.TranslateOptions = { + x : 100.0, + y : 0.0, + z : 0.0 + }; + toWindow.translate(obj); // Set the transition animation. + console.info('toWindow translate end'); + } + ) + console.info('complete transition end'); +} +windowClass.hideWithAnimation((err, data) => { + if (err.code) { + console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); +}) +``` + +### setBlur9+ + +setBlur(radius: number): void + +Blurs this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setBlur(4.0); +} catch (exception) { + console.error('Failed to set blur. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setBackdropBlur9+ + +setBackdropBlur(radius: number): void + +Blurs the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value **0** means that the blur is disabled for the background of the window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setBackdropBlur(4.0); +} catch (exception) { + console.error('Failed to set backdrop blur. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setBackdropBlurStyle9+ + +setBackdropBlurStyle(blurStyle: BlurStyle): void + +Sets the blur style for the background of this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------ | --------- | --------------------------------------------------- | +| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setBackdropBlurStyle(window.BlurStyle.THIN); +} catch (exception) { + console.error('Failed to set backdrop blur style. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setShadow9+ + +setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void + +Sets the shadow for the window borders. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value **0** means that the shadow is disabled for the window borders. | +| color | string | No | Color of the shadow. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | +| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setShadow(4.0, '#FF00FF00', 2, 3); +} catch (exception) { + console.error('Failed to set shadow. Cause: ' + JSON.stringify(exception)); +}; +``` + +### setCornerRadius9+ + +setCornerRadius(cornerRadius: number): void + +Sets the radius of the rounded corners for this window. + +**System API**: This is a system API. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value **0** means that the window does not use rounded corners. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300004 | Unauthorized operation. | + +**Example** + +```js +try { + windowClass.setCornerRadius(4.0); +} catch (exception) { + console.error('Failed to set corner radius. Cause: ' + JSON.stringify(exception)); +}; +``` + +### show(deprecated) + +show(callback: AsyncCallback<void>): void + +Shows this window. 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 [showWindow()](#showwindow9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +windowClass.show((err) => { + if (err.code) { + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing the window.'); +}) +``` + +### show(deprecated) + +show(): Promise<void> + +Shows this window. 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 [showWindow()](#showwindow9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.show(); +promise.then(()=> { + console.info('Succeeded in showing the window.'); +}).catch((err)=>{ + console.error('Failed to show the window. Cause: ' + JSON.stringify(err)); +}) +``` + +### destroy(deprecated) + +destroy(callback: AsyncCallback<void>): void + +Destroys this window. 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 [destroyWindow()](#destroywindow9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +windowClass.destroy((err) => { + if (err.code) { + console.error('Failed to destroy the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in destroying the window.'); +}) +``` + +### destroy(deprecated) + +destroy(): Promise<void> + +Destroys this window. 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 [destroyWindow()](#destroywindow9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.destroy(); +promise.then(()=> { + console.info('Succeeded in destroying the window.'); +}).catch((err)=>{ + console.error('Failed to destroy the window. Cause: ' + JSON.stringify(err)); +}) +``` + +### moveTo(deprecated) + +moveTo(x: number, y: number, callback: AsyncCallback<void>): void + +Moves this window. 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 [moveWindowTo()](#movewindowto9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right. | +| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +windowClass.moveTo(300, 300, (err)=>{ + if (err.code) { + console.error('Failed to move the window. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving the window.'); + +}); +``` + +### moveTo(deprecated) + +moveTo(x: number, y: number): Promise<void> + +Moves this window. 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 [moveWindowTo()](#movewindowto9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------------------------------ | +| x | number | Yes | Distance that the window moves along the x-axis, in px. A positive value indicates that the window moves to the right. | +| y | number | Yes | Distance that the window moves along the y-axis, in px. A positive value indicates that the window moves downwards. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.moveTo(300, 300); +promise.then(()=> { + console.info('Succeeded in moving the window.'); +}).catch((err)=>{ + console.error('Failed to move the window. Cause: ' + JSON.stringify(err)); +}) +``` + +### resetSize(deprecated) + +resetSize(width: number, height: number, callback: AsyncCallback<void>): void + +Changes the size of this window. 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 [resize()](#resize9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ----------------------------------- | +| width | number | Yes | New width of the window, in px. | +| height | number | Yes | New height of the window, in px. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +windowClass.resetSize(500, 1000, (err) => { + if (err.code) { + console.error('Failed to change the window size. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in changing the window size.'); +}); +``` + +### resetSize(deprecated) + +resetSize(width: number, height: number): Promise<void> + +Changes the size of this window. 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 [resize()](#resize9-1) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | -------------------------------- | +| width | number | Yes | New width of the window, in px. | +| height | number | Yes | New height of the window, in px. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let promise = windowClass.resetSize(500, 1000); +promise.then(()=> { + console.info('Succeeded in changing the window size.'); +}).catch((err)=>{ + console.error('Failed to change the window size. Cause: ' + JSON.stringify(err)); +}); + +``` + +### setWindowType(deprecated) + +setWindowType(type: WindowType, callback: AsyncCallback<void>): void + +Sets the type of this window. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------- | --------- | ----------------------------------- | +| type | [WindowType](#windowtype7) | Yes | Window type. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let type = window.WindowType.TYPE_APP; +windowClass.setWindowType(type, (err) => { + if (err.code) { + console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window type.'); +}); +``` + +### setWindowType(deprecated) + +setWindowType(type: WindowType): Promise<void> + +Sets the type of this window. This API uses a promise to return the result. + +**System API**: This is a system API. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------- | --------- | ------------ | +| type | [WindowType](#windowtype7) | Yes | Window type. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Example** + +```js +let type = window.WindowType.TYPE_APP; +let promise = windowClass.setWindowType(type); +promise.then(()=> { + console.info('Succeeded in setting the window type.'); +}).catch((err)=>{ + console.error('Failed to set the window type. Cause: ' + JSON.stringify(err)); +}); +``` + +### getProperties(deprecated) + +getProperties(callback: AsyncCallback<WindowProperties>): void + +Obtains the properties of this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getWindowProperties()](#getwindowproperties9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[WindowProperties](#windowproperties)> | Yes | Callback used to return the window properties. | + +**Example** + +```js +windowClass.getProperties((err, data) => { + if (err.code) { + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +}); + +``` + +### getProperties(deprecated) + +getProperties(): Promise<WindowProperties> + +Obtains the properties of this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getWindowProperties()](#getwindowproperties9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------------- | +| Promise<[WindowProperties](#windowproperties)> | Promise used to return the window properties. | + +**Example** + +```js +let promise = windowClass.getProperties(); +promise.then((data)=> { + console.info('Succeeded in obtaining the window properties. Data: ' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the window properties. Cause: ' + JSON.stringify(err)); +}); + +``` + +### getAvoidArea(deprecated) + +getAvoidArea(type: [AvoidAreaType](#avoidareatype7), callback: AsyncCallback<[AvoidArea](#avoidarea7)>): void + +Obtains the area where this window cannot be displayed, for example, the system bar area, notch, gesture area, and soft keyboard area. 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 [[getWindowAvoidArea()](#getwindowavoidarea9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. | +| callback | AsyncCallback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | + +**Example** + +```js +let type = window.AvoidAreaType.TYPE_SYSTEM; +windowClass.getAvoidArea(type, (err, data) => { + if (err.code) { + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +}); +``` + +### getAvoidArea(deprecated) + +getAvoidArea(type: [AvoidAreaType](#avoidareatype7)): Promise<[AvoidArea](#avoidarea7)> + +Obtains the area where this window cannot be displayed, for example, the system bar area, notch, gesture area, and soft keyboard area. 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 [getWindowProperties()](#getwindowavoidarea9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------------------------------------------ | +| type | [AvoidAreaType](#avoidareatype7) | Yes | Type of the area. **TYPE_SYSTEM** indicates the default area of the system. **TYPE_CUTOUT** indicates the notch. **TYPE_SYSTEM_GESTURE** indicates the gesture area. **TYPE_KEYBOARD** indicates the soft keyboard area. | + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------------- | +| Promise<[AvoidArea](#avoidarea7)> | Promise used to return the area. | + +**Example** + +```js +let type = window.AvoidAreaType.TYPE_SYSTEM; +let promise = windowClass.getAvoidArea(type); +promise.then((data)=> { + console.info('Succeeded in obtaining the area. Data:' + JSON.stringify(data)); +}).catch((err)=>{ + console.error('Failed to obtain the area. Cause:' + JSON.stringify(err)); +}); +``` + +### setFullScreen(deprecated) + +setFullScreen(isFullScreen: boolean, callback: AsyncCallback<void>): void + +Sets whether to enable the full-screen mode for this window. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarEnable()](#setwindowsystembarenable9) instead. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------------------------- | --------- | ------------------------------------------------------------ | +| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +let isFullScreen = true; +windowClass.setFullScreen(isFullScreen, (err) => { if (err.code) { - console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); -}) + console.info('Succeeded in enabling the full-screen mode.'); +}); ``` -### isSupportWideGamut8+ +### setFullScreen(deprecated) -isSupportWideGamut(): Promise<boolean> +setFullScreen(isFullScreen: boolean): Promise<void> -Checks whether this window supports the wide color gamut mode. This API uses a promise to return the result. +Sets whether to enable the full-screen mode for this window. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarEnable()](#setwindowsystembarenable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------ | ------- | --------- | ------------------------------------------------------------ | +| isFullScreen | boolean | Yes | Whether to enable the full-screen mode, in which the status bar and navigation bar are hidden. The value **true** means to enable the full-screen mode, and **false** means the opposite. | + **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value `true` means that the wide color gamut mode is supported, and `false` means the opposite.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.isSupportWideGamut(); -promise.then((data)=> { - console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)); +let isFullScreen = true; +let promise = windowClass.setFullScreen(isFullScreen); +promise.then(()=> { + console.info('Succeeded in enabling the full-screen mode.'); }).catch((err)=>{ - console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); + console.error('Failed to enable the full-screen mode. Cause: ' + JSON.stringify(err)); }); + ``` -### setColorSpace8+ +### setLayoutFullScreen(deprecated) -setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void +setLayoutFullScreen(isLayoutFullScreen: boolean, callback: AsyncCallback<void>): void + +Sets whether to enable the full-screen mode for the window layout. This API uses an asynchronous callback to return the result. -Sets this window to the wide or default color gamut mode. 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 [setWindowLayoutFullScreen()](#setwindowlayoutfullscreen9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------ | -| colorSpace | [ColorSpace](#colorspace) | Yes | Color gamut mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------------------ | ------------------------- | --------- | ------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err, data) => { +let isLayoutFullScreen= true; +windowClass.setLayoutFullScreen(isLayoutFullScreen, (err) => { if (err.code) { - console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)); -}) + console.info('Succeeded in setting the window layout to full-screen mode.'); +}); + ``` -### setColorSpace8+ +### setLayoutFullScreen(deprecated) -setColorSpace(colorSpace:ColorSpace): Promise<void> +setLayoutFullScreen(isLayoutFullScreen: boolean): Promise<void> + +Sets whether to enable the full-screen mode for the window layout. This API uses a promise to return the result. -Sets this window to the wide or default color gamut mode. 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 [setWindowLayoutFullScreen()](#setwindowlayoutfullscreen9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | -------------- | -| colorSpace | [ColorSpace](#colorspace) | Yes | Color gamut mode.| +| Name | Type | Mandatory | Description | +| ------------------ | ------- | --------- | ------------------------------------------------------------ | +| isLayoutFullScreen | boolean | Yes | Whether to enable the full-screen mode for the window layout, in which the status bar and navigation bar are displayed. The value **true** means to enable the full-screen mode for the window layout, and **false** means the opposite. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT); -promise.then((data)=> { - console.info('Succeeded in setting window colorspace. Data: ' + JSON.stringify(data)); +let isLayoutFullScreen = true; +let promise = windowClass.setLayoutFullScreen(isLayoutFullScreen); +promise.then(()=> { + console.info('Succeeded in setting the window layout to full-screen mode.'); }).catch((err)=>{ - console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the window layout to full-screen mode. Cause:' + JSON.stringify(err)); }); ``` -### getColorSpace8+ +### setSystemBarEnable(deprecated) -getColorSpace(callback: AsyncCallback<ColorSpace>): void +setSystemBarEnable(names: Array<'status' | 'navigation'>, callback: AsyncCallback<void>): void + +Sets whether to display the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. -Obtains the color gamut mode of this window. 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 [setWindowSystemBarEnable()](#setwindowsystembarenable9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------- | ---- | ---------------------------------------------------------- | -| callback | AsyncCallback<[ColorSpace](#colorspace)> | Yes | Callback used to return the result. When the color gamut mode is obtained successfully, `err` is `undefined`, and `data` is the current color gamut mode.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.getColorSpace((err, data) => { +// In this example, the status bar and navigation bar are not displayed. +let names = []; +windowClass.setSystemBarEnable(names, (err) => { if (err.code) { - console.error('Failed to get window colorspace. Cause:' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data)); -}) + console.info('Succeeded in setting the system bar to be invisible.'); +}); + ``` -### getColorSpace8+ +### setSystemBarEnable(deprecated) -getColorSpace(): Promise<ColorSpace> +setSystemBarEnable(names: Array<'status' | 'navigation'>): Promise<void> -Obtains the color gamut mode of this window. This API uses a promise to return the result. +Sets whether to display the status bar and navigation bar in this window. 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 [setWindowSystemBarEnable()](#setwindowsystembarenable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----- | --------- | ------------------------------------------------------------ | +| names | Array | Yes | Whether to display the status bar and navigation bar.
For example, to display the status bar and navigation bar, set this parameter to **['status', 'navigation']**. By default, they are not displayed. | + **Return value** -| Type | Description | -| ---------------------------------------- | ------------------------------- | -| Promise<[ColorSpace](#colorspace)> | Promise used to return the current color gamut mode.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.getColorSpace(); -promise.then((data)=> { - console.info('Succeeded in getting window color space. Cause:' + JSON.stringify(data)); +// In this example, the status bar and navigation bar are not displayed. +let names = []; +let promise = windowClass.setSystemBarEnable(names); +promise.then(()=> { + console.info('Succeeded in setting the system bar to be invisible.'); }).catch((err)=>{ - console.error('Failed to get window colorspace. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the system bar to be invisible. Cause:' + JSON.stringify(err)); }); + ``` -### setBackgroundColor +### setSystemBarProperties(deprecated) -setBackgroundColor(color: string, callback: AsyncCallback<void>): void +setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: AsyncCallback<void>): void + +Sets the properties of the status bar and navigation bar in this window. This API uses an asynchronous callback to return the result. -Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9). +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarProperties()](#setwindowsystembarproperties9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ------------------- | ------------------------------------------- | --------- | ------------------------------------------------ | +| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let color = '#00ff33'; -windowClass.setBackgroundColor(color, (err, data) => { +let SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 8. + statusBarContentColor:'#ffffff', + navigationBarContentColor:'#00ffff' +}; +windowClass.setSystemBarProperties(SystemBarProperties, (err) => { if (err.code) { - console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting the system bar properties.'); }); ``` -### setBackgroundColor +### setSystemBarProperties(deprecated) -setBackgroundColor(color: string): Promise<void> +setSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<void> + +Sets the properties of the status bar and navigation bar in this window. This API uses a promise to return the result. -Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9). +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowSystemBarProperties()](#setwindowsystembarproperties9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| +| Name | Type | Mandatory | Description | +| ------------------- | ------------------------------------------- | --------- | ------------------------------------------------ | +| SystemBarProperties | [SystemBarProperties](#systembarproperties) | Yes | Properties of the status bar and navigation bar. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let color = '#00ff33'; -let promise = windowClass.setBackgroundColor(color); -promise.then((data)=> { - console.info('Succeeded in setting the background color. Data: ' + JSON.stringify(data)); +let SystemBarProperties={ + statusBarColor: '#ff00ff', + navigationBarColor: '#00ff00', + // The following properties are supported since API version 8. + statusBarContentColor:'#ffffff', + navigationBarContentColor:'#00ffff' +}; +let promise = windowClass.setSystemBarProperties(SystemBarProperties); +promise.then(()=> { + console.info('Succeeded in setting the system bar properties.'); }).catch((err)=>{ - console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the system bar properties. Cause: ' + JSON.stringify(err)); }); -``` - -### setWakeUpScreen()9+ - -setWakeUpScreen(wakeUp: boolean): void; - -Wakes up the screen. -**System API**: This is a system API. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------------- | ------- | ---- | ---------------------------- | -| wakeUp | boolean | Yes | Whether to wake up the screen.| - -**Example** - -```js -let wakeUp = true; -windowClass.setWakeUpScreen(wakeUp); ``` -### setBrightness +### loadContent(deprecated) -setBrightness(brightness: number, callback: AsyncCallback<void>): void +loadContent(path: string, callback: AsyncCallback<void>): void -Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. +Loads content from a page to this window. 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 [setUIContent()](#setuicontent9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------- | +| path | string | Yes | Path of the page from which the content will be loaded. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let brightness = 1; -windowClass.setBrightness(brightness, (err, data) => { - if (err.code) { - console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); +windowClass.loadContent('pages/page2/page2', (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); }); + ``` -### setBrightness +### loadContent(deprecated) -setBrightness(brightness: number): Promise<void> +loadContent(path: string): Promise<void> -Sets the screen brightness for this window. This API uses a promise to return the result. +Loads content from a page to this window. 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 [setUIContent()](#setuicontent9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | ------------------------------------ | -| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value `1` indicates the brightest.| +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ------------------------------------------------------- | +| path | string | Yes | Path of the page from which the content will be loaded. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let brightness = 1; -let promise = windowClass.setBrightness(brightness); -promise.then((data)=> { - console.info('Succeeded in setting the brightness. Data: ' + JSON.stringify(data)); +let promise = windowClass.loadContent('pages/page2/page2'); +promise.then(()=> { + console.info('Succeeded in loading the content.'); }).catch((err)=>{ - console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); + console.error('Failed to load the content. Cause: ' + JSON.stringify(err)); }); + ``` -### setDimBehind(deprecated) +### isShowing(deprecated) -setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void +isShowing(callback: AsyncCallback<boolean>): void -Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. +Checks whether this window is displayed. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isWindowShowing()](#iswindowshowing9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------- | ---- | -------------------------------------------------- | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value `1` indicates the dimmest.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the window is displayed, and **false** means the opposite. | **Example** ```js -windowClass.setDimBehind(0.5, (err, data) => { +windowClass.isShowing((err, data) => { if (err.code) { - console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window is showing. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the dimness. Data:' + JSON.stringify(data)); + console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); }); ``` -### setDimBehind(deprecated) +### isShowing(deprecated) -setDimBehind(dimBehindValue: number): Promise<void> +isShowing(): Promise<boolean> -Sets the dimness of the window that is not on top. This API uses a promise to return the result. +Checks whether this window is displayed. This API uses a promise to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isWindowShowing()](#iswindowshowing9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | -------------------------------------------------- | -| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value `1` indicates the dimmest.| - **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the window is displayed, and **false** means the opposite. | **Example** ```js -let promise = windowClass.setDimBehind(0.5); +let promise = windowClass.isShowing(); promise.then((data)=> { - console.info('Succeeded in setting the dimness. Data: ' + JSON.stringify(data)); + console.info('Succeeded in checking whether the window is showing. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window is showing. Cause: ' + JSON.stringify(err)); }); ``` -### setFocusable7+ +### on('systemAvoidAreaChange')(deprecated) + +on(type: 'systemAvoidAreaChange', callback: Callback<AvoidArea>): void -setFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void +Enables listening for changes to the area where the window cannot be displayed. -Sets whether this window can gain focus. 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. Use [on('avoidAreaChange')](#onavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | ---------------------------- | -| isFocusable | boolean | Yes | Whether the window can gain focus.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed. | +| callback | Callback<[AvoidArea](#avoidarea7)> | Yes | Callback used to return the area. | **Example** ```js -let isFocusable= true; -windowClass.setFocusable(isFocusable, (err, data) => { - if (err.code) { - console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); +windowClass.on('systemAvoidAreaChange', (data) => { + console.info('Succeeded in enabling the listener for system avoid area changes. Data: ' + JSON.stringify(data)); }); ``` -### setFocusable7+ +### off('systemAvoidAreaChange')(deprecated) -setFocusable(isFocusable: boolean): Promise<void> +off(type: 'systemAvoidAreaChange', callback?: Callback<AvoidArea>): void -Sets whether this window can gain focus. This API uses a promise to return the result. +Disables listening for changes to the area where the window cannot be displayed. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. Use [off('avoidAreaChange')](#offavoidareachange9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | ---------------------------- | -| isFocusable | boolean | Yes | Whether the window can gain focus.| - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'systemAvoidAreaChange'**, indicating the event of changes to the area where the window cannot be displayed. | +| callback | Callback<[AvoidArea](#avoidarea7)> | No | Callback used to return the area. | **Example** ```js -let isFocusable= true; -let promise = windowClass.setFocusable(isFocusable); -promise.then((data)=> { - console.info('Succeeded in setting the window to be focusable. Data: ' + JSON.stringify(data)); -}).catch((err)=>{ - console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); -}); +windowClass.off('systemAvoidAreaChange'); + ``` -### setKeepScreenOn +### isSupportWideGamut(deprecated) -setKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void +isSupportWideGamut(callback: AsyncCallback<boolean>): void -Sets whether to keep the screen always on. This API uses an asynchronous callback to return the result. +Checks whether this window supports the wide-gamut color space. 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 [isWindowSupportWideGamut()](#iswindowsupportwidegamut9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------------- | ---- | ------------------------ | -| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite. | **Example** ```js -let isKeepScreenOn = true; -windowClass.setKeepScreenOn(isKeepScreenOn, (err, data) => { +windowClass.isSupportWideGamut((err, data) => { if (err.code) { - console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window support WideGamut. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); -}); -``` + console.info('Succeeded in checking whether the window support WideGamut Data: ' + JSON.stringify(data)); +}) -### setKeepScreenOn +``` -setKeepScreenOn(isKeepScreenOn: boolean): Promise<void> +### isSupportWideGamut(deprecated) -Sets whether to keep the screen always on. This API uses a promise to return the result. +isSupportWideGamut(): Promise<boolean> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Checks whether this window supports the wide-gamut color space. This API uses a promise to return the result. -**Parameters** +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isWindowSupportWideGamut()](#iswindowsupportwidegamut9-1) instead. -| Name | Type | Mandatory| Description | -| -------------- | ------- | ---- | ------------------------ | -| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the wide-gamut color space is supported, and **false** means the opposite. | **Example** ```js -let isKeepScreenOn = true; -let promise = windowClass.setKeepScreenOn(isKeepScreenOn); -promise.then((data) => { - console.info('Succeeded in setting the screen to be always on. Data: ' + JSON.stringify(data)); +let promise = windowClass.isSupportWideGamut(); +promise.then((data)=> { + console.info('Succeeded in checking whether the window support WideGamut. Data: ' + JSON.stringify(data)); }).catch((err)=>{ - console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + console.error('Failed to check whether the window support WideGamut. Cause: ' + JSON.stringify(err)); }); + ``` -### setOutsideTouchable(deprecated) +### setColorSpace(deprecated) -setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): void +setColorSpace(colorSpace:ColorSpace, callback: AsyncCallback<void>): void -Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. +Sets a color space for this window. This API uses an asynchronous callback to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setWindowColorSpace()](#setwindowcolorspace9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ---------------- | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value `true` means that such an area is touchable, and `false` means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | --------- | ----------------------------------- | +| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setOutsideTouchable(true, (err, data) => { +windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT, (err) => { if (err.code) { - console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + console.error('Failed to set window colorspace. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)); + console.info('Succeeded in setting window colorspace.'); }) ``` -### setOutsideTouchable(deprecated) +### setColorSpace(deprecated) -setOutsideTouchable(touchable: boolean): Promise<void> +setColorSpace(colorSpace:ColorSpace): Promise<void> -Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. +Sets a color space for this window. This API uses a promise to return the result. > **NOTE** > -> This API cannot be used. -> -> This API is supported since API version 7 and deprecated since API version 9. +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [setWindowColorSpace()](#setwindowcolorspace9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------- | ---- | ---------------- | -| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value `true` means that such an area is touchable, and `false` means the opposite.| +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | --------- | ------------------- | +| colorSpace | [ColorSpace](#colorspace) | Yes | Color space to set. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.setOutsideTouchable(true); -promise.then((data)=> { - console.info('Succeeded in setting the area to be touchable. Data: ' + JSON.stringify(data)); +let promise = windowClass.setColorSpace(window.ColorSpace.WIDE_GAMUT); +promise.then(()=> { + console.info('Succeeded in setting window colorspace.'); }).catch((err)=>{ - console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + console.error('Failed to set window colorspace. Cause: ' + JSON.stringify(err)); }); + ``` -### setPrivacyMode7+ +### getColorSpace(deprecated) -setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void +getColorSpace(callback: AsyncCallback<ColorSpace>): void -Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. +Obtains the color space of this window. 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 [getWindowColorSpace()](#getwindowcolorspace9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------------------------- | ---- | -------------------- | -| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------------- | --------- | ------------------------------------------------------------ | +| callback | AsyncCallback<[ColorSpace](#colorspace)> | Yes | Callback used to return the result. When the color space is obtained successfully, **err** is **undefined**, and **data** is the current color space. | **Example** ```js -let isPrivacyMode = true; -windowClass.setPrivacyMode(isPrivacyMode, (err, data) => { +windowClass.getColorSpace((err, data) => { if (err.code) { - console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + console.error('Failed to get window colorspace. Cause:' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the window to privacy mode. Data:' + JSON.stringify(data)); + console.info('Succeeded in getting window colorspace. Cause:' + JSON.stringify(data)); +}) -}); ``` -### setPrivacyMode7+ - -setPrivacyMode(isPrivacyMode: boolean): Promise<void> +### getColorSpace(deprecated) -Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. +getColorSpace(): Promise<ColorSpace> -**System capability**: SystemCapability.WindowManager.WindowManager.Core +Obtains the color space of this window. This API uses a promise to return the result. -**Parameters** +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getWindowColorSpace()](#getwindowcolorspace9) instead. -| Name | Type | Mandatory| Description | -| ------------- | ------- | ---- | -------------------- | -| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode.| +**System capability**: SystemCapability.WindowManager.WindowManager.Core **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ---------------------------------------- | ----------------------------------------------- | +| Promise<[ColorSpace](#colorspace)> | Promise used to return the current color space. | **Example** ```js -let isPrivacyMode = true; -let promise = windowClass.setPrivacyMode(isPrivacyMode); +let promise = windowClass.getColorSpace(); promise.then((data)=> { - console.info('Succeeded in setting the window to privacy mode. Data: ' + JSON.stringify(data)); + console.info('Succeeded in getting window color space. Cause:' + JSON.stringify(data)); }).catch((err)=>{ - console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); + console.error('Failed to get window colorspace. Cause: ' + JSON.stringify(err)); }); -``` - -### setSnapshotSkip9+ -setSnapshotSkip(isSkip: boolean): void - -Sets whether to ignore this window during screen capturing or recording. - -**System API**: This is a system API. - -**System capability**: SystemCapability.WindowManager.WindowManager.Core - -**Parameters** -| Name | Type | Mandatory| Description | -| ------------- | ------- | ---- | -------------------- | -| isSkip | boolean | Yes | Whether to ignore the window. The default value is `false`.
The value `true` means that the window is ignored, and `false` means the opposite.
| -```js -let isSkip = true; -windowClass.setSnapshotSkip(isSkip); ``` -### setTouchable7+ +### setBackgroundColor(deprecated) -setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void +setBackgroundColor(color: string, callback: AsyncCallback<void>): void -Sets whether this window is touchable. This API uses an asynchronous callback to return the result. +Sets the background color for this window. This API uses an asynchronous callback to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBackgroundColor()](#setwindowbackgroundcolor9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | -------------------- | -| isTouchable | boolean | Yes | Whether the window is touchable.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------------ | +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let isTouchable = true; -windowClass.setTouchable(isTouchable, (err, data) => { +let color = '#00ff33'; +windowClass.setBackgroundColor(color, (err) => { if (err.code) { - console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in setting the window to be touchable. Data:' + JSON.stringify(data)); - + console.info('Succeeded in setting the background color.'); }); ``` -### setTouchable7+ +### setBackgroundColor(deprecated) -setTouchable(isTouchable: boolean): Promise<void> +setBackgroundColor(color: string): Promise<void> -Sets whether this window is touchable. This API uses a promise to return the result. +Sets the background color for this window. This API uses a promise to return the result. In the stage model, this API must be used after [loadContent](#loadcontent9) or [setUIContent()](#setuicontent9). + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBackgroundColor()](#setwindowbackgroundcolor9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | -------------------- | -| isTouchable | boolean | Yes | Whether the window is touchable.| +| Name | Type | Mandatory | Description | +| ----- | ------ | --------- | ------------------------------------------------------------ | +| color | string | Yes | Background color to set. The value is a hexadecimal color code and is case insensitive, for example, **#00FF00** or **#FF00FF00**. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let isTouchable = true; -let promise = windowClass.setTouchable(isTouchable); -promise.then((data)=> { - console.info('Succeeded in setting the window to be touchable. Data: ' + JSON.stringify(data)); +let color = '#00ff33'; +let promise = windowClass.setBackgroundColor(color); +promise.then(()=> { + console.info('Succeeded in setting the background color.'); }).catch((err)=>{ - console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the background color. Cause: ' + JSON.stringify(err)); }); + ``` -### setForbidSplitMove9+ +### setBrightness(deprecated) -setForbidSplitMove(isForbidSplitMove: boolean, callback: AsyncCallback<void>): void +setBrightness(brightness: number, callback: AsyncCallback<void>): void -Sets whether this window is forbidden to move in split-screen mode. This API uses an asynchronous callback to return the result. +Sets the screen brightness for this window. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | -------------------- | -| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | --------- | ------------------------------------------------------------ | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let isForbidSplitMove = true; -windowClass.setForbidSplitMove(isForbidSplitMove, (err, data) => { +let brightness = 1; +windowClass.setBrightness(brightness, (err) => { if (err.code) { - console.error('Failed to forbid window moving in split screen mode. Cause:' + JSON.stringify(err)); + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in forbidding window moving in split screen mode. Data:' + JSON.stringify(data)); - + console.info('Succeeded in setting the brightness.'); }); + ``` -### setForbidSplitMove9+ +### setBrightness(deprecated) -setForbidSplitMove(isForbidSplitMove: boolean): Promise<void> +setBrightness(brightness: number): Promise<void> -Sets whether this window is forbidden to move in split-screen mode. This API uses a promise to return the result. +Sets the screen brightness for this window. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowBrightness()](#setwindowbrightness9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | -------------------- | -| isForbidSplitMove | boolean | Yes | Whether the window is forbidden to move in split-screen mode.| +| Name | Type | Mandatory | Description | +| ---------- | ------ | --------- | ------------------------------------------------------------ | +| brightness | number | Yes | Brightness to set, which ranges from 0 to 1. The value **1** indicates the brightest. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let isForbidSplitMove = true; -let promise = windowClass.setForbidSplitMove(isForbidSplitMove); -promise.then((data)=> { - console.info('Succeeded in forbidding window moving in split screen mode. Data: ' + JSON.stringify(data)); +let brightness = 1; +let promise = windowClass.setBrightness(brightness); +promise.then(()=> { + console.info('Succeeded in setting the brightness.'); }).catch((err)=>{ - console.error('Failed to forbid window moving in split screen mode. Cause: ' + JSON.stringify(err)); + console.error('Failed to set the brightness. Cause: ' + JSON.stringify(err)); }); + ``` -### snapshot9+ +### setDimBehind(deprecated) -snapshot(callback: AsyncCallback<image.PixelMap>): void +setDimBehind(dimBehindValue: number, callback: AsyncCallback<void>): void -Captures this window. This API uses an asynchronous callback to return the result. +Sets the dimness of the window that is not on top. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------------------------- | ---- | -------------------- | -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | --------- | ------------------------------------------------------------ | +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.snapshot((err, data) => { +windowClass.setDimBehind(0.5, (err) => { if (err.code) { - console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); return; } - console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - data.release(); // Release the memory in time after the PixelMap is used. + console.info('Succeeded in setting the dimness.'); }); ``` -### snapshot9+ +### setDimBehind(deprecated) -snapshot(): Promise<image.PixelMap> +setDimBehind(dimBehindValue: number): Promise<void> -Captures this window. This API uses a promise to return the result. +Sets the dimness of the window that is not on top. This API uses a promise to return the result. + +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | --------- | ------------------------------------------------------------ | +| dimBehindValue | number | Yes | Dimness of the window to set. The value ranges from 0 to 1. The value **1** indicates the dimmest. | + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the window screenshot.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let promise = windowClass.snapshot(); -promise.then((pixelMap)=> { - console.info('Succeeded in snapshotting window. Pixel bytes number: ' + pixelMap.getPixelBytesNumber()); - pixelMap.release(); // Release the memory in time after the PixelMap is used. +let promise = windowClass.setDimBehind(0.5); +promise.then(()=> { + console.info('Succeeded in setting the dimness.'); }).catch((err)=>{ - console.error('Failed to snapshot window. Cause:' + JSON.stringify(err)); + console.error('Failed to set the dimness. Cause: ' + JSON.stringify(err)); }); + ``` -### setBlur9+ +### setFocusable(deprecated) -setBlur(radius: number): void +setFocusable(isFocusable: boolean, callback: AsyncCallback<void>): void -Blurs this window. +Sets whether this window can gain focus. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowFocusable()](#setwindowfocusable9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the window.| +| Name | Type | Mandatory | Description | +| ----------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setBlur(4.0); +let isFocusable= true; +windowClass.setFocusable(isFocusable, (err) => { + if (err.code) { + console.error('Failed to set the window to be focusable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be focusable.'); +}); + ``` -### setBackdropBlur9+ +### setFocusable(deprecated) -setBackdropBlur(radius: number): void +setFocusable(isFocusable: boolean): Promise<void> -Blurs the background of this window. +Sets whether this window can gain focus. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowFocusable()](#setwindowfocusable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the blur. The value is greater than or equal to 0. The value `0` means that the blur is disabled for the background of the window.| +| Name | Type | Mandatory | Description | +| ----------- | ------- | --------- | ------------------------------------------------------------ | +| isFocusable | boolean | Yes | Whether the window can gain focus. The value **true** means that the window can gain focus, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -windowClass.setBackdropBlur(4.0); +let isFocusable= true; +let promise = windowClass.setFocusable(isFocusable); +promise.then(()=> { + console.info('Succeeded in setting the window to be focusable.'); +}).catch((err)=>{ + console.error('Failed to set the window to be focusable. Cause: ' + JSON.stringify(err)); +}); ``` -### setBackdropBlurStyle9+ +### setKeepScreenOn(deprecated) -setBackdropBlurStyle(blurStyle: BlurStyle): void +setKeepScreenOn(isKeepScreenOn: boolean, callback: AsyncCallback<void>): void -Sets the blur style for the background of this window. +Sets whether to keep the screen always on. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowKeepScreenOn()](#setwindowkeepscreenon9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | --------- | ---- | ---------------------- | -| blurStyle | [BlurStyle](#blurstyle9) | Yes | Blur style to set for the background of the window.| +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setBackdropBlurStyle(window.BlurType.THIN); +let isKeepScreenOn = true; +windowClass.setKeepScreenOn(isKeepScreenOn, (err) => { + if (err.code) { + console.error('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the screen to be always on.'); +}); ``` -### setShadow9+ +### setKeepScreenOn(deprecated) -setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void +setKeepScreenOn(isKeepScreenOn: boolean): Promise<void> -Sets the shadow for the window borders. +Sets whether to keep the screen always on. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [setWindowKeepScreenOn()](#setwindowkeepscreenon9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| radius | number | Yes | Radius of the shadow. The value is greater than or equal to 0. The value `0` means that the shadow is disabled for the window borders.| -| color | string | No | Color of the shadow. The value is a hexadecimal color code and is case insensitive, for example, `#00FF00` or `#FF00FF00`.| -| offsetX | number | No | Offset of the shadow along the x-axis, in pixels. | -| offsetY | number | No | Offset of the shadow along the y-axis, in pixels. | +| Name | Type | Mandatory | Description | +| -------------- | ------- | --------- | ------------------------------------------------------------ | +| isKeepScreenOn | boolean | Yes | Whether to keep the screen always on. The value **true** means to keep the screen always on, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -windowClass.setShadow(4.0, '#FF00FF00', 2, 3); +let isKeepScreenOn = true; +let promise = windowClass.setKeepScreenOn(isKeepScreenOn); +promise.then(() => { + console.info('Succeeded in setting the screen to be always on.'); +}).catch((err)=>{ + console.info('Failed to set the screen to be always on. Cause: ' + JSON.stringify(err)); +}); ``` -### setCornerRadius9+ +### setOutsideTouchable(deprecated) -setCornerRadius(cornerRadius: number): void +setOutsideTouchable(touchable: boolean, callback: AsyncCallback<void>): void -Sets the radius of the rounded corners for this window. +Sets whether the area outside the subwindow is touchable. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | -------------------- | -| radius | number | Yes | Radius of the rounded corners. The value is greater than or equal to 0. The value `0` means that the window does not use rounded corners.| +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | --------- | ------------------------------------------------------------ | +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -windowClass.setCornerRadius(4.0); +windowClass.setOutsideTouchable(true, (err) => { + if (err.code) { + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the area to be touchable.'); +}) ``` -### opacity9+ +### setOutsideTouchable(deprecated) -opacity(opacity: number): void +setOutsideTouchable(touchable: boolean): Promise<void> -Sets the opacity for this window. +Sets whether the area outside the subwindow is touchable. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API cannot be used. This API is supported since API version 7 and deprecated since API version 9. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | --------------------- | -| opacity | number | Yes | Opacity to set. The value ranges from 0.0 to 1.0.| +| Name | Type | Mandatory | Description | +| --------- | ------- | --------- | ------------------------------------------------------------ | +| touchable | boolean | Yes | Whether the area outside the subwindow is touchable. The value **true** means the area outside the subwindow is touchable, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -windowClass.opacity(0.5); +let promise = windowClass.setOutsideTouchable(true); +promise.then(()=> { + console.info('Succeeded in setting the area to be touchable.'); +}).catch((err)=>{ + console.error('Failed to set the area to be touchable. Cause: ' + JSON.stringify(err)); +}); ``` -### scale9+ +### setPrivacyMode(deprecated) -scale(scaleOptions: ScaleOptions): void +setPrivacyMode(isPrivacyMode: boolean, callback: AsyncCallback<void>): void -Sets the scale parameters for this window. +Sets whether this window is in privacy mode. This API uses an asynchronous callback to return the result. When in privacy mode, the window content cannot be captured or recorded. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowPrivacyMode()](#setwindowprivacymode9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------ | ------------------------------ | ---- | ---------- | -| scaleOptions | [ScaleOptions](#scaleoptions9) | Yes | Scale parameters to set.| +| Name | Type | Mandatory | Description | +| ------------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let obj : window.ScaleOptions = { - x : 2.0, - y : 1.0, - pivotX = 0.5; - pivotY = 0.5; -} -windowClass.scale(obj); +let isPrivacyMode = true; +windowClass.setPrivacyMode(isPrivacyMode, (err) => { + if (err.code) { + console.error('Failed to set the window to privacy mode. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to privacy mode.'); + +}); + ``` -### rotate9+ +### setPrivacyMode(deprecated) -rotate(rotateOptions: RotateOptions): void +setPrivacyMode(isPrivacyMode: boolean): Promise<void> -Sets the rotation parameters for this window. +Sets whether this window is in privacy mode. This API uses a promise to return the result. When in privacy mode, the window content cannot be captured or recorded. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowPrivacyMode()](#setwindowprivacymode9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------------- | -------------------------------- | ---- | ---------- | -| rotateOptions | [RotateOptions](#rotateoptions9) | Yes | Rotation parameters to set.| +| Name | Type | Mandatory | Description | +| ------------- | ------- | --------- | ------------------------------------------------------------ | +| isPrivacyMode | boolean | Yes | Whether the window is in privacy mode. The value **true** means that the window is in privacy mode, and **false** means the opposite. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let obj : window.RotateOptions = { - x : 1.0, - y : 1.0, - z : 45.0, - pivotX = 0.5; - pivotY = 0.5; -} -windowClass.rotate(obj); +let isPrivacyMode = true; +let promise = windowClass.setPrivacyMode(isPrivacyMode); +promise.then(()=> { + console.info('Succeeded in setting the window to privacy mode.'); +}).catch((err)=>{ + console.error('Failed to set the window to privacy mode. Cause: ' + JSON.stringify(err)); +}); ``` -### translate9+ +### setTouchable(deprecated) -translate(translateOptions: TranslateOptions): void +setTouchable(isTouchable: boolean, callback: AsyncCallback<void>): void -Sets the translation parameters for this window. +Sets whether this window is touchable. This API uses an asynchronous callback to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowTouchable()](#setwindowtouchable9) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | -------------------------------------- | ---- | ---------- | -| translateOptions | [TranslateOptions](#translateoptions9) | Yes | Translation parameters to set.| +| Name | Type | Mandatory | Description | +| ----------- | ------------------------- | --------- | ------------------------------------------------------------ | +| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -let obj : window.TranslateOptions = { - x : 100.0, - y : 0.0, - z : 0.0 -} -windowClass.translate(obj); +let isTouchable = true; +windowClass.setTouchable(isTouchable, (err) => { + if (err.code) { + console.error('Failed to set the window to be touchable. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in setting the window to be touchable.'); + +}); ``` -### getTransitionController9+ +### setTouchable(deprecated) - getTransitionController(): TransitionController +setTouchable(isTouchable: boolean): Promise<void> -Obtains the transition animation controller. +Sets whether this window is touchable. This API uses a promise to return the result. -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setWindowTouchable()](#setwindowtouchable9-1) instead. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------- | --------- | ------------------------------------------------------------ | +| isTouchable | boolean | Yes | Whether the window is touchable. The value **true** means that the window is touchable, and **false** means the opposite. | + **Return value** -| Type | Description | -| ---------------------------------------------- | ---------------- | -| [TransitionController](#transitioncontroller9) | Transition animation controller.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | **Example** ```js -let controller = windowClass.getTransitionController(); // Obtain the transition animation controller. -controller.animationForHidden = (context : window.TransitionContext) => { - let toWindow = context.toWindow - animateTo({ - duration: 1000, // Animation duration. - tempo: 0.5, // Playback speed. - curve: Curve.EaseInOut, // Animation curve. - delay: 0, // Animation delay. - iterations: 1, // Number of playback times. - playMode: PlayMode.Normal // Animation playback mode. - onFinish: ()=> { - context.completeTransition(true) - } - }, () => { - let obj : window.TranslateOptions = { - x : 100.0, - y : 0.0, - z : 0.0 - } - toWindow.translate(obj); // Set the transition animation. - console.info('toWindow translate end'); - } - ) - console.info('complete transition end'); -} -windowClass.hideWithAnimation((err, data) => { - if (err.code) { - console.error('Failed to show the window with animation. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in showing the window with animation. Data: ' + JSON.stringify(data)); -}) +let isTouchable = true; +let promise = windowClass.setTouchable(isTouchable); +promise.then(()=> { + console.info('Succeeded in setting the window to be touchable.'); +}).catch((err)=>{ + console.error('Failed to set the window to be touchable. Cause: ' + JSON.stringify(err)); +}); ``` ## WindowStageEventType9+ @@ -3459,18 +5849,18 @@ Describes the lifecycle of a window stage. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Default Value | Description | -| ---------- | ------ | ---------- | -| FOREGROUND | 1 | The window stage is running in the foreground.| -| ACTIVE | 2 | The window stage gains focus.| -| INACTIVE | 3 | The window stage loses focus.| -| BACKGROUND | 4 | The window stage is running in the background.| +| Name | Default Value | Description | +| ---------- | ------------- | ---------------------------------------------- | +| FOREGROUND | 1 | The window stage is running in the foreground. | +| ACTIVE | 2 | The window stage gains focus. | +| INACTIVE | 3 | The window stage loses focus. | +| BACKGROUND | 4 | The window stage is running in the background. | ## WindowStage9+ Implements a window manager, which manages each basic window unit, that is, [Window](#window) instance. -Before calling any of the following APIs, you must use `[onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate)` to create a `WindowStage` instance. +Before calling any of the following APIs, you must use [onWindowStageCreate()](js-apis-application-ability.md#abilityonwindowstagecreate) to create a **WindowStage** instance. ### getMainWindow9+ @@ -3484,9 +5874,18 @@ Obtains the main window of this window stage. This API uses an asynchronous call **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | --------------------------------------------- | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the main window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3507,6 +5906,7 @@ class myAbility extends Ability { } } ``` + ### getMainWindow9+ getMainWindow(): Promise<Window> @@ -3519,9 +5919,18 @@ Obtains the main window of this window stage. This API uses a promise to return **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the main window.| +| Type | Description | +| -------------------------------- | --------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the main window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3541,6 +5950,48 @@ class myAbility extends Ability { } } ``` + +### getMainWindowSync9+ + +getMainWindowSync(): Window + +Obtains the main window of this window stage. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.WindowManager.WindowManager.Core + +**Return value** + +| Type | Description | +| ----------------- | ----------------------- | +| [Window](#window) | return the main window. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | + +**Example** + +```ts +import Ability from '@ohos.application.Ability'; +class myAbility extends Ability { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + try { + let windowClass = windowStage.getMainWindowSync(); + } catch (exception) { + console.error('Failed to obtain the main window. Cause: ' + JSON.stringify(exception)); + }; + } +} +``` + ### createSubWindow9+ createSubWindow(name: string, callback: AsyncCallback<Window>): void @@ -3553,10 +6004,19 @@ Creates a subwindow for this window stage. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | --------------------------------------------- | -| name | String | Yes | Name of the subwindow. | -| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | --------- | -------------------------------------- | +| name | String | Yes | Name of the subwindow. | +| callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3566,18 +6026,23 @@ class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; - windowStage.createSubWindow('mySubWindow', (err, data) => { - if (err.code) { - console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); - return; - } - windowClass = data; - console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); - windowClass.resetSize(500, 1000); - }); + try { + windowStage.createSubWindow('mySubWindow', (err, data) => { + if (err.code) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); + return; + } + windowClass = data; + console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); + windowClass.resetSize(500, 1000); + }); + } catch (exception) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(exception)); + }; } } ``` + ### createSubWindow9+ createSubWindow(name: string): Promise<Window> @@ -3590,15 +6055,24 @@ Creates a subwindow for this window stage. This API uses a promise to return the **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------- | -| name | String | Yes | Name of the subwindow.| +| Name | Type | Mandatory | Description | +| ---- | ------ | --------- | ---------------------- | +| name | String | Yes | Name of the subwindow. | **Return value** -| Type | Description | -| -------------------------------- | ------------------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the subwindow.| +| Type | Description | +| -------------------------------- | ------------------------------------- | +| Promise<[Window](#window)> | Promise used to return the subwindow. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3608,16 +6082,21 @@ class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; - let promise = windowStage.createSubWindow('mySubWindow'); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); - }) + try { + let promise = windowStage.createSubWindow('mySubWindow'); + promise.then((data)=> { + windowClass = data; + console.info('Succeeded in creating the subwindow. Data: ' + JSON.stringify(data)); + }).catch((err)=>{ + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(err)); + }); + } catch (exception) { + console.error('Failed to create the subwindow. Cause: ' + JSON.stringify(exception)); + }; } } ``` + ### getSubWindow9+ getSubWindow(callback: AsyncCallback<Array<Window>>): void @@ -3630,9 +6109,17 @@ Obtains all the subwindows of this window stage. This API uses an asynchronous c **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------------- | -| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------------------------------- | --------- | ------------------------------------------- | +| callback | AsyncCallback<Array<[Window](#window)>> | Yes | Callback used to return all the subwindows. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300005 | This window stage is abnormal. | **Example** @@ -3653,6 +6140,7 @@ class myAbility extends Ability { } } ``` + ### getSubWindow9+ getSubWindow(): Promise<Array<Window>> @@ -3665,9 +6153,17 @@ Obtains all the subwindows of this window stage. This API uses a promise to retu **Return value** -| Type | Description | -| --------------------------------------------- | ---------------------------------------------------- | -| Promise<Array<[Window](#window)>> | Promise used to return all the subwindows.| +| Type | Description | +| --------------------------------------------- | ------------------------------------------ | +| Promise<Array<[Window](#window)>> | Promise used to return all the subwindows. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300005 | This window stage is abnormal. | **Example** @@ -3687,6 +6183,7 @@ class myAbility extends Ability { } } ``` + ### loadContent9+ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void>): void @@ -3699,11 +6196,20 @@ Loads content from a page associated with a local storage to the main window in **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | Yes | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3715,13 +6221,17 @@ class myAbility extends Ability { this.storage = new LocalStorage(); this.storage.setOrCreate('storageSimpleProp',121); console.log('onWindowStageCreate'); - windowStage.loadContent('pages/page2',this.storage,(err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }); + try { + windowStage.loadContent('pages/page2',this.storage,(err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); + } catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); + }; } } ``` @@ -3738,16 +6248,25 @@ Loads content from a page associated with a local storage to the main window in **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | -| path | string | Yes | Path of the page from which the content will be loaded. | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application.| +| Name | Type | Mandatory | Description | +| ------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| path | string | Yes | Path of the page from which the content will be loaded. | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | No | A storage unit, which provides storage for variable state properties and non-variable state properties of an application. | **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------------ | +| Promise<void> | Promise that returns no value. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3759,14 +6278,16 @@ class myAbility extends Ability { this.storage = new LocalStorage(); this.storage.setOrCreate('storageSimpleProp',121); console.log('onWindowStageCreate'); - let windowClass = null; - let promise = windowStage.loadContent('pages/page2',this.storage); - promise.then((data)=> { - windowClass = data; - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }).catch((err)=>{ - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - }) + try { + let promise = windowStage.loadContent('pages/page2',this.storage); + promise.then(()=> { + console.info('Succeeded in loading the content.'); + }).catch((err)=>{ + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + }); + } catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); + }; } } ``` @@ -3783,10 +6304,19 @@ Loads content from a page to this window stage. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| path | string | Yes | Path of the page from which the content will be loaded.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | --------- | ------------------------------------------------------- | +| path | string | Yes | Path of the page from which the content will be loaded. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3795,13 +6325,17 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.loadContent('pages/page2', (err, data) => { - if (err.code) { - console.error('Failed to load the content. Cause:' + JSON.stringify(err)); - return; - } - console.info('Succeeded in loading the content. Data: ' + JSON.stringify(data)); - }); + try { + windowStage.loadContent('pages/page2', (err) => { + if (err.code) { + console.error('Failed to load the content. Cause:' + JSON.stringify(err)); + return; + } + console.info('Succeeded in loading the content.'); + }); + } catch (exception) { + console.error('Failed to load the content. Cause:' + JSON.stringify(exception)); + }; } } ``` @@ -3818,10 +6352,19 @@ Enables listening for window stage lifecycle changes. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event. | +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | Yes | Callback used to return the window stage lifecycle state. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3830,9 +6373,15 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.on('windowStageEvent', (data) => { - console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + JSON.stringify(data)); - }); + try { + windowStage.on('windowStageEvent', (data) => { + console.info('Succeeded in enabling the listener for window stage event changes. Data: ' + + JSON.stringify(data)); + }); + } catch (exception) { + console.error('Failed to enable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); + }; } } ``` @@ -3849,10 +6398,19 @@ Disables listening for window stage lifecycle changes. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at `windowStageEvent`, indicating the window stage lifecycle change event.| -| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------------ | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'windowStageEvent'**, indicating the window stage lifecycle change event. | +| callback | Callback<[WindowStageEventType](#windowstageeventtype9)> | No | Callback used to return the window stage lifecycle state. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3861,7 +6419,12 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.off('windowStageEvent'); + try { + windowStage.off('windowStageEvent'); + } catch (exception) { + console.error('Failed to disable the listener for window stage event changes. Cause:' + + JSON.stringify(exception)); + }; } } ``` @@ -3878,6 +6441,15 @@ Disables window decorators. **System capability**: SystemCapability.WindowManager.WindowManager.Core +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | + **Example** ```ts @@ -3904,9 +6476,18 @@ Sets whether to display the window of the application on the lock screen. **Parameters** -| Name | Type | Mandatory| Description | -| ---------------- | ------- | ---- | ---------------------------- | -| showOnLockScreen | boolean | Yes | Whether to display the window on the lock screen.| +| Name | Type | Mandatory | Description | +| ---------------- | ------- | --------- | ------------------------------------------------------------ | +| showOnLockScreen | boolean | Yes | Whether to display the window on the lock screen. The value **true** means to display the window on the lock screen, and **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Window Error Codes](../errorcodes/errorcode-window.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 1300002 | This window state is abnormal. | +| 1300005 | This window stage is abnormal. | **Example** @@ -3915,10 +6496,15 @@ import Ability from '@ohos.application.Ability'; class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); - windowStage.setShowOnLockScreen(true); + try { + windowStage.setShowOnLockScreen(true); + } catch (exception) { + console.error('Failed to show on lockscreen. Cause:' + JSON.stringify(exception)); + }; } } ``` + ## TransitionContext9+ Provides the context for the transition animation. @@ -3929,9 +6515,9 @@ Provides the context for the transition animation. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | Type | Readable| Writable| Description | -| --------------------- | ----------------- | ---- | ---- | ---------------- | -| toWindow9+ | [Window](#window) | Yes | Yes | Target window to display the animation.| +| Name | Type | Readable | Writable | Description | +| --------------------- | ----------------- | -------- | -------- | --------------------------------------- | +| toWindow9+ | [Window](#window) | Yes | Yes | Target window to display the animation. | ### completeTransition9+ @@ -3945,16 +6531,16 @@ Completes the transition. This API can be called only after [animateTo()](../ark **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ------- | ---- | ------------------------------------------------------------ | -| isCompleted | boolean | Yes | Whether the transition is complete. The value `true` means that the transition is complete, and `false` means the opposite.| +| Name | Type | Mandatory | Description | +| ----------- | ------- | --------- | ------------------------------------------------------------ | +| isCompleted | boolean | Yes | Whether the transition is complete. The value **true** means that the transition is complete, and **false** means the opposite. | **Example** ```js let controller = windowClass.getTransitionController(); controller.animationForShown = (context : window.TransitionContext) => { - let toWindow = context.toWindow + let toWindow = context.toWindow; animateTo({ duration: 1000, // Animation duration. tempo: 0.5, // Playback speed. @@ -3967,14 +6553,18 @@ controller.animationForShown = (context : window.TransitionContext) => { x : 100.0, y : 0.0, z : 0.0 - } + }; toWindow.translate(obj); console.info('toWindow translate end'); } ) - context.completeTransition(true) + try { + context.completeTransition(true) + } catch (exception) { + console.info('toWindow translate fail. Cause: ' + JSON.stringify(exception)); + } console.info('complete transition end'); -} +}; ``` ## TransitionController9+ @@ -3993,16 +6583,16 @@ Customizes the animation for the scenario when the window is shown. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------------- | ---- | -------------------- | -| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | --------- | ------------------------------------ | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation. | **Example** ```js let controller = windowClass.getTransitionController(); controller.animationForShown = (context : window.TransitionContext) => { - let toWindow = context.toWindow + let toWindow = context.toWindow; animateTo({ duration: 1000, // Animation duration. tempo: 0.5, // Playback speed. @@ -4018,7 +6608,7 @@ controller.animationForShown = (context : window.TransitionContext) => { x : 100.0, y : 0.0, z : 0.0 - } + }; toWindow.translate(obj); console.info('toWindow translate end'); } @@ -4039,16 +6629,16 @@ Customizes the animation for the scenario when the window is hidden. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------------- | ---- | -------------------- | -| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation.| +| Name | Type | Mandatory | Description | +| ------- | ---------------------------------------- | --------- | ------------------------------------ | +| context | [TransitionContext](#transitioncontext9) | Yes | Context of the transition animation. | **Example** ```js let controller = windowClass.getTransitionController(); controller.animationForHidden = (context : window.TransitionContext) => { - let toWindow = context.toWindow + let toWindow = context.toWindow; animateTo({ duration: 1000, // Animation duration. tempo: 0.5, // Playback speed. @@ -4064,7 +6654,7 @@ controller.animationForHidden = (context : window.TransitionContext) => { x : 100.0, y : 0.0, z : 0.0 - } + }; toWindow.translate(obj); console.info('toWindow translate end'); } @@ -4072,3 +6662,4 @@ controller.animationForHidden = (context : window.TransitionContext) => { console.info('complete transition end'); } ``` + 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/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 322a8000a525eef6e32174a2a099f04573570edc..945c5219bedb22f5efdd6f53b5d55d4cdd97f260 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -59,7 +59,9 @@ Sets an attribute. let arrayBuffer = new ArrayBuffer(1024); let bufView = new DataView(arrayBuffer); let thatSer = new xml.XmlSerializer(bufView); -thatSer.setAttributes("importance", "high"); +thatSer.startElement("note"); +thatSer.setAttributes("importance", "high"); +thatSer.endElement(); ``` diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index aaaad457f25d19f50735576c44f13aa011cbef58..75ac7f144e75fd9ed1068f161854fb185c0d6210 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,7 +1,7 @@ # Zip > **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. ## Constraints @@ -30,9 +30,9 @@ Zips a file. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ---------------------------------------------------- | -| Promise\ | Returns **ERROR_CODE_OK** if the operation is successful; returns **ERROR_CODE_ERRNO** otherwise.| +| Type | Description | +| -------------- | ------------------------------------------------------------ | +| Promise\ | Returns [ERROR_CODE_OK](#ziperrorcode) if the operation is successful.
Returns [ERROR_CODE_ERRNO](#ziperrorcode) if the operation fails.| **Example 1** @@ -96,7 +96,7 @@ Unzips a file. This API uses a promise to return the result. | Type | Description | | -------------- | ------------------------------------------------------------ | -| Promise\ | Returns **ERROR_CODE_OK** if the operation is successful; returns **ERROR_CODE_ERRNO** otherwise.| +| Promise\ | Returns [ERROR_CODE_OK](#ziperrorcode) if the operation is successful.
Returns [ERROR_CODE_ERRNO](#ziperrorcode) if the operation fails.| **Example** diff --git a/en/application-dev/reference/arkui-js/js-components-basic-button.md b/en/application-dev/reference/arkui-js/js-components-basic-button.md index 6e9378efe275d52ea6e28a4e51baa6170f5d6a7c..29061668cc3ddd2c59a2b057a97bb09970807693 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-button.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-button.md @@ -18,7 +18,7 @@ In addition to the [universal attributes](../arkui-js/js-components-common-attri | Name | Type | Default Value | Mandatory | Description | | ---------------------- | ------- | ----- | ---- | ---------------------------------------- | -| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Different from the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| +| type | string | - | No | Button type. The value cannot be dynamically updated. If this attribute is not set, a capsule-like button is displayed. Unlike the capsule button, the capsule-like button allows its corners to be configured using **border-radius**. Available button types are as follows:
- **capsule**: capsule button with fillets, background color, and text.
- **circle**: circle button that can accommodate icons.
- **text**: text button, which displays only text.
- **arc**: arc button. This value is applicable to wearables only.
- **download**: download button, with an extra download progress bar.| | value | string | - | No | Text value of the button. | | icon | string | - | No | Path of the button icon. The supported icon formats are JPG, PNG, and SVG. | | placement5+ | string | end | No | Position of the button icon in text. This attribute is valid only when **type** is not set. Available values are as follows:
- **start**: The button icon is at the beginning of the text.
- **end**: The button icon is at the end of the text.
- **top**: The button icon is at the top of the text.
- **bottom**: The button icon is at the bottom of the text.| @@ -34,27 +34,20 @@ In addition to the [universal styles](../arkui-js/js-components-common-styles.md | Name | Type | Default Value | Mandatory | Description | | ----------- | -------------------------- | --------------- | ---- | ---------------------------------------- | -| text-color | <color> | \#007dff
| No | Text color of the button. | -| font-size | <length> | 16px
| No | Font size of the button. | +| text-color | <color> | \#007dff | No | Text color of the button. | +| font-size | <length> | 16px | No | Font size of the button. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings.
If the **config-changes** tag of **fontSize** is configured for abilities in the **config.json** file, the setting takes effect without application restart.| | font-style | string | normal | No | Font style of the button. | -| font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the font specified by [Custom Font Styles](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| font-weight | number \| string | normal | No | Font weight of the button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | | icon-width | <length> | - | No | Width of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | icon-height | <length> | - | No | Height of the internal icon of a circle button. The entire circle button is filled by default.
This style must be set when the icon uses the SVG image.| | radius | <length> | - | No | Corner radius of the button. For a circle button, this style takes precedence over **width** and **height** in the universal styles.| -> **NOTE** -> - For capsule buttons, border-related styles are not supported. -> -> - For circle buttons, text-related styles are not supported. -> -> - For text buttons, the font size is automatically adaptive, and **radius**, **width**, and **height** cannot be set. The **background-color** style is not supported when the background is completely transparent. - ### When the Button Type Is arc -In addition to the **background-color**, **opacity**, **display**, **visibility**, **position**, **[left|top|right|bottom]** styles in [Universal Styles](../arkui-js/js-components-common-styles.md), the following styles are supported. +In addition to the **background-color**, **opacity**, **display**, **visibility**, **position**, and **[left|top|right|bottom]** styles in [Universal Styles](../arkui-js/js-components-common-styles.md), the following styles are supported. | Name | Type | Default Value | Mandatory | Description | | ----------- | -------------------------- | ---------- | ---- | ---------------------------------------- | @@ -62,8 +55,8 @@ In addition to the **background-color**, **opacity**, **display**, **visibility* | font-size | <length> | 37.5px | No | Font size of the arc button. | | allow-scale | boolean | true | No | Whether the font size changes with the system's font size settings. | | font-style | string | normal | No | Font style of the arc button. | -| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| -| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the font specified by [Custom Font Styles](../arkui-js/js-components-common-customizing-font.md) is used for the text.| +| font-weight | number \| string | normal | No | Font weight of the arc button. For details, see **font-weight** of the [**\** component](../arkui-js/js-components-basic-text.md#styles).| +| font-family | <string> | sans-serif | No | Font family, in which fonts are separated by commas (,). Each font is set using a font name or font family name. The first font in the family or the specified [custom font](../arkui-js/js-components-common-customizing-font.md) is used for the text. | ## Events @@ -79,7 +72,7 @@ When the button type is **download**, the following methods are supported. | Name | Parameters | Description | | ----------- | ------------------------------ | ---------------------------------------- | -| setProgress | { progress:percent } | Progress bar of the download button. The value ranges from 0 to 100. The progress bar is displayed if the value is greater than 0. If the value is greater than or equal to 100, the progress bar is not displayed.
The text displayed on the progress bar is subject to the **value** settings.| +| setProgress | { progress:percent } | Progress bar of the download button. The value ranges from 0 to 100. The progress bar is displayed if the value is greater than 0. If the value is greater than or equal to 100, the progress bar is not displayed.
The text displayed on the progress bar is subject to the **value** settings.| ## Example diff --git a/en/application-dev/reference/arkui-js/js-components-basic-chart.md b/en/application-dev/reference/arkui-js/js-components-basic-chart.md index b674facb9f71daaa97403e865feb983cc3e6dc7c..26ac1ef03d97536474103465f8f61cc5108ab126 100644 --- a/en/application-dev/reference/arkui-js/js-components-basic-chart.md +++ b/en/application-dev/reference/arkui-js/js-components-basic-chart.md @@ -1,1158 +1,355 @@ -# chart +# chart -The **** component displays line charts, gauge charts, and bar charts. +> **NOTE** +> +> This component is supported since API version 4. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions +The **\** component displays line charts, gauge charts, and bar charts. -None - -## Child Component - -Not supported - -## Attributes - -In addition to the attributes in [Universal Attributes](js-components-common-attributes.md), the following attributes are supported. - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

line

-

No

-

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

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

options

-

ChartOptions

-

-

-

No

-

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

-

datasets

-

Array<ChartDataset>

-

-

-

No

-

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

-

segments5+

-

DataSegment | Array<DataSegment>

-

-

-

No

-

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

-

DataSegment is available for progress and loading charts.

-

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

-
NOTE:

-
-

effects5+

-

boolean

-

true

-

No

-

Whether to enable the effects for progress and rainbow charts.

-
NOTE:

-
-

animationduration6+

-

number

-

3000

-

No

-

Animation duration for expanding a rainbow chart, in milliseconds.

-
NOTE:

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

xAxis

-

ChartAxis

-

-

-

Yes

-

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

-

yAxis

-

ChartAxis

-

-

-

Yes

-

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

-

series

-

ChartSeries

-

-

-

No

-

Data sequence parameters.

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

Only line charts support this attribute.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

strokeColor

-

<color>

-

#ff6384

-

No

-

Line color.

-
NOTE:

Only line charts support this attribute.

-
-

fillColor

-

<color>

-

#ff6384

-

No

-

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

-

data

-

Array<number> | Array<Point>5+

-

-

-

Yes

-

Data of the drawn line or bar.

-

gradient

-

boolean

-

false

-

No

-

Whether to display the gradient color.

-
NOTE:

Only line charts support this attribute.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

min

-

number

-

0

-

No

-

Minimum value of the axis.

-
NOTE:

Only line charts support negative numbers.

-
-

max

-

number

-

100

-

No

-

Maximum value of the axis.

-
NOTE:

Only line charts support negative numbers.

-
-

axisTick

-

number

-

10

-

No

-

Number of scales displayed on the axis.

-
NOTE:

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

-

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

-
-

display

-

boolean

-

false

-

No

-

Whether to display the axis.

-

color

-

<color>

-

#c0c0c0

-

No

-

Axis color.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

lineStyle

-

ChartLineStyle

-

-

-

No

-

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

-

headPoint

-

PointStyle

-

-

-

No

-

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

-

topPoint

-

PointStyle

-

-

-

No

-

Style and size of the top point.

-

bottomPoint

-

PointStyle

-

-

-

No

-

Style and size of the bottom point.

-

loop

-

ChartLoop

-

-

-

No

-

Whether to start drawing again when the screen is looped.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

width

-

<length>

-

1px

-

No

-

Line width.

-

smooth

-

boolean

-

false

-

No

-

Whether the line is smooth.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

shape

-

string

-

circle

-

No

-

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

-
  • Circle
  • Square
  • Triangle
-

size

-

<length>

-

5px

-

No

-

Size of the highlight point.

-

strokeWidth

-

<length>

-

1px

-

No

-

Stroke width.

-

strokeColor

-

<color>

-

#ff0000

-

No

-

Frame color.

-

fillColor

-

<color>

-

#ff0000

-

No

-

Fill color.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

margin

-

<length>

-

1

-

No

-

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

-

gradient

-

boolean

-

false

-

No

-

Whether to perform gradient erase.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

value

-

number

-

0

-

Yes

-

Y coordinate of the point to draw.

-

pointStyle

-

PointStyle

-

-

-

No

-

Style of the point.

-

description

-

string

-

-

-

No

-

Description text of the point.

-

textLocation

-

string

-

-

-

No

-

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

-

top: above the point

-

bottom: below the point

-

none: not displayed

-

textColor

-

<color>

-

#000000

-

No

-

Color of the description text.

-

lineDash

-

string

-

solid

-

No

-

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

-

lineColor

-

<color>

-

#000000

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

startColor

-

Color

-

-

-

No

-

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

-

endColor

-

Color

-

-

-

No

-

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

-

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

-

value

-

number

-

0

-

Yes

-

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

-

name

-

string

-

-

-

No

-

Name of this data segment.

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

Data Segment

-

Light Mode

-

Dark Mode

-

0

-

Start color: #f7ce00; end color: #f99b11

-

Start color: #d1a738; end color: #eb933d

-

1

-

Start color: #f76223; end color: #f2400a

-

Start color: #e67d50; end color: #d9542b

-

2

-

Start color: #f772ac; end color: #e65392

-

Start color: #d5749e; end color: #d6568d

-

3

-

Start color: #a575eb; end color: #a12df7

-

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

-

4

-

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

-

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

-

5

-

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

-

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

-

6

-

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

-

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

-

7

-

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

-

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

-

8

-

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

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

percent

-

number

-

0

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

stroke-width

-

<length>

-

32px (gauge charts)

-

24px (rainbow charts)

-

No

-

Width of the scale bar for gaugeand rainbow charts.

-

start-angle

-

<deg>

-

240 (gauge charts)

-

0 (rainbow charts)

-

No

-

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

-

total-angle

-

<deg>

-

240 (gauge charts)

-

360 (rainbow charts)

-

No

-

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

-

center-x

-

<length>

-

-

-

No

-

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

-

center-y

-

<length>

-

-

-

No

-

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

-

radius

-

<length>

-

-

-

No

-

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

-

colors

-

Array

-

-

-

No

-

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

-

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

-

weights

-

Array

-

-

-

No

-

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

-

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

-

font-family5+

-

Array

-

-

-

No

-

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

-

font-size5+

-

<length>

-

-

-

No

-

Font size of the description text.

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

Method

-

Parameter

-

Description

-

append

-

{

-

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

-

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

-

}

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

vertical

-

boolean

-

false

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

margin

-

<length>

-

0

-

No

-

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

-

margin-[left|top|right|bottom]

-

<length>

-

0

-

No

-

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

-

color

-

<color>

-

#08000000

-

No

-

Color of the divider.

-

stroke-width

-

<length>

-

1

-

No

-

Width of the divider.

-

display

-

string

-

flex

-

No

-

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

-

visibility

-

string

-

visible

-

No

-

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

-

line-cap

-

string

-

butt

-

No

-

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

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

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

-
-

flex

-

number

-

-

-

No

-

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

-
NOTE:

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

-
-

flex-grow

-

number

-

0

-

No

-

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

-
NOTE:

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

-
-

-

flex-shrink

-

number

-

1

-

No

-

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

-
NOTE:

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

-
-

flex-basis

-

<length>

-

-

-

-

No

-

Initial length of a child component on the main axis

-
NOTE:

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

images

-

Array<ImageFrame>

-

-

-

Yes

-

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

-
NOTE:

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

-

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

-
-

predecode6+

-

number

-

0

-

No

-

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

-

iteration

-

number | string

-

infinite

-

No

-

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

-

reverse

-

boolean

-

false

-

No

-

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

-

fixedsize

-

boolean

-

true

-

No

-

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

-

duration

-

string

-

-

-

Yes

-

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

-

fillmode5+

-

string

-

forwards

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

src

-

<uri>

-

-

-

Yes

-

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

-

width

-

<length>

-

0

-

No

-

Image width

-

height

-

<length>

-

0

-

No

-

Image height

-

top

-

<length>

-

0

-

No

-

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

-

left

-

<length>

-

0

-

No

-

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

-

duration6+

-

number

-

-

-

No

-

Playback duration of each image frame, in milliseconds.

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

Name

-

Parameter

-

Description

-

start

-

-

-

Triggered when the frame animation starts

-

pause

-

-

-

Triggered when the frame animation pauses

-

stop

-

-

-

Triggered when the frame animation stops

-

resume

-

-

-

Triggered when the frame animation resumes

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

Name

-

Parameter

-

Description

-

start

-

-

-

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

-

pause

-

-

-

Pauses the frame animation playback of an image.

-

stop

-

-

-

Stops the frame animation playback of an image.

-

resume

-

-

-

Resumes the frame animation playback of an image.

-

getState

-

-

-

Obtains the playback state. Available values are as follows:

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

src

-

string

-

-

-

No

-

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

-

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

-

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

-

alt

-

string

-

-

-

No

-

Placeholder image displayed during image loading.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

object-fit

-

string

-

cover

-

No

-

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

-

match-text-direction

-

boolean

-

false

-

No

-

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

-

fit-original-size

-

boolean

-

false

-

No

-

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

-

object-position7+

-

string

-

0px 0px

-

No

-

Position of an image in the component.

-

There are two setting types:

-

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

-

2. Characters. Optional values are as follows:

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

Type

-

Description

-

cover

-

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

-

contain

-

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

-

fill

-

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

-

none

-

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

-

scale-down

-

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

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

Name

-

Parameter

-

Description

-

complete(Rich)

-

{ width: width, height: height }

-

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

-

error(Rich)

-

{ width: width, height: height }

-

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

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

Attribute

-

Type

-

Description

-

width

-

number

-

Width of an element.

-

height

-

number

-

Height of an element.

-

left

-

number

-

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

-

top

-

number

-

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

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

Name

-

Type

-

Mandatory

-

Description

-

param

-

ObserverParam

-

-

-

Obtains the observer callback.

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

Attribute

-

Type

-

Description

-

ratios

-

Array<number>

-

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

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

Name

-

Parameter

-

Description

-

observe

-

callback: function

-

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

-

unobserve

-

-

-

Unsubscribes from events of the observed object.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

placement

-

string

-

rightTop

-

No

-

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

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

count

-

number

-

0

-

No

-

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

-
NOTE:

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

-

The largest integer value supported for count is 2147483647.

-
-

visible

-

boolean

-

false

-

No

-

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

-

maxcount

-

number

-

99

-

No

-

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

-
NOTE:

The largest integer value supported for maxcount is 2147483647.

-
-

config

-

BadgeConfig

-

-

-

No

-

Configuration of the badge.

-

label6+

-

string

-

-

-

No

-

Text of the new notification displayed via the badge.

-
NOTE:

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

badgeColor

-

<color>

-

#fa2a2d

-

No

-

Background color of the badge

-

textColor

-

<color>

-

#ffffff

-

No

-

Text color of the number badge

-

textSize

-

<length>

-

10px

-

No

-

Text size of the number badge

-

badgeSize

-

<length>

-

6px

-

No

-

Default size of the dot badge

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

dragable7+

-

boolean

-

false

-

No

-

Whether the pop-up can be dragged.

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

Name

-

Parameter

-

Description

-

cancel

-

-

-

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

-

show7+

-

-

-

Triggered when the pop-up is displayed.

-

close7+

-

-

-

Triggered when the pop-up is closed.

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

Name

-

Parameter

-

Description

-

show

-

-

-

Shows a dialog box.

-

close

-

-

-

Closes a dialog box.

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

Name

-

Parameters

-

Description

-

submit

-

FormResult

-

Triggered when the Submit button is touched.

-

reset

-

-

-

Triggered when the Reset button is clicked.

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

Name

-

Type

-

Description

-

value

-

Object

-

Values of name and value of the input element.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

default

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

flex-direction

-

string

-

row

-

No

-

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

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

justify-content

-

string

-

flex-start

-

No

-

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

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

Name

-

Parameter

-

Description

-

groupclick

-

{ groupid: string }

-

Triggered when a group is clicked.

-

groupid: ID of the group that is clicked.

-

groupcollapse

-

{ groupid: string }

-

Triggered when a group is collapsed.

-

groupid: ID of the group collapsed.

-

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

-

groupexpand

-

{ groupid: string }

-

Triggered when a group is expanded.

-

groupid: ID of the group expanded.

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

type

-

string

-

default

-

No

-

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

-

primary

-

boolean

-

false

-

No

-

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

-

section

-

string

-

-

-

No

-

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

-

sticky

-

string

-

none

-

No

-

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

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

clickeffect5+

-

boolean

-

true

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

column-span

-

<number>

-

1

-

No

-

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

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

Name

-

Parameter

-

Description

-

sticky

-

{ state: boolean }

-

Callback events for a sticky component.

-

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

-

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

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

scrollpage

-

boolean

-

false

-

No

-

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

-

cachedcount

-

number

-

0

-

No

-

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

-

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

-

scrollbar

-

string

-

off

-

No

-

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

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

scrolleffect

-

string

-

spring

-

No

-

Scroll effect. Available values are as follows:

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

indexer

-

boolean | Array<string>

-

false

-

No

-

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

-

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

-

"indexer" : "false" indicates no indexer.

-

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

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

indexercircle5+

-

boolean

-

-

-

No

-

Whether to use a circle indexer.

-

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

-

indexermulti5+

-

boolean

-

false

-

No

-

Whether to use a multi-language indexer.

-

This attribute is invalid if indexer is set to false.

-

indexerbubble5+

-

boolean

-

true

-

No

-

Whether to display the bubble effect when switching among indexes.

-

This attribute is invalid if indexer is set to false.

-

divider5+

-

boolean

-

false

-

No

-

Whether list items are separated by dividers.

-

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

-

shapemode

-

string

-

default

-

No

-

Shape of the side scrollbar.

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

updateeffect

-

boolean

-

false

-

No

-

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

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

chainanimation5+

-

boolean

-

false

-

No

-

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

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

initialindex

-

number

-

0

-

No

-

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

-

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

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

initialoffset

-

<length>

-

0

-

No

-

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

-

selected5+

-

string

-

-

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

divider-color5+

-

<color>

-

transparent

-

No

-

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

-

divider-height5+

-

<length>

-

1

-

No

-

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

-

divider-length5+

-

<length>

-

The main axis width

-

No

-

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

-

divider-origin5+

-

<length>

-

0

-

No

-

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

-

flex-direction

-

string

-

-

column

-

No

-

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

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

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

-

columns

-

number

-

1

-

No

-

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

-
NOTE:

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

-
-

align-items

-

string

-

stretch

-

No

-

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

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

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

    -
    -
-

item-extent

-

<length> | <percentage>

-

-

-

No

-

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

-

fade-color

-

<color>

-

grey

-

No

-

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

-

scrollbar-color6+

-

<color>

-

-

-

No

-

Color of the scrollbar.

-

scrollbar-width6+

-

<length>

-

-

-

No

-

Width of the scrollbar.

-

scrollbar-offset6+

-

<length>

-

0

-

No

-

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

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

Name

-

Parameter

-

Description

-

indexerchange5+

-

{ local: booleanValue }

-

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

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

scroll

-

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

-

Triggered to indicate the offset and status of list scrolling.

-

stateValue: 0: The list is not scrolling.

-

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

-

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

-

scrollbottom

-

-

-

Triggered when the list is scrolled to the bottom.

-

scrolltop

-

-

-

Triggered when the list is scrolled to the top.

-

scrollend

-

-

-

Triggered when the list stops scrolling.

-

scrolltouchup

-

-

-

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

-

requestitem

-

-

-

Triggered for a request to create a list-item.

-

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

-

rotate7+

-

{ rotateValue: number }

-

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

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

Name

-

Parameter

-

Description

-

scrollTo

-

{ index: number(specified position) }

-

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

-

scrollBy

-

ScrollParam

-

Scrolls the list for a certain distance.

-

This method applies only to smart TVs.

-

scrollTop

-

{ smooth: boolean }

-

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

-

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

-

scrollBottom

-

{ smooth: boolean }

-

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

-

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

-

scrollPage

-

{ reverse: boolean, smooth: boolean }

-

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

-

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

-

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

-

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

-

scrollArrow

-

{ reverse: boolean, smooth: boolean }

-

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

-

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

-

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

-

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

-

collapseGroup

-

{ groupid: string }

-

Collapses a group.

-

groupid: ID of the group to collapse.

-

All groups are collapsed when groupid is not specified.

-

expandGroup

-

{ groupid: string }

-

Expands a group.

-

groupid: ID of the group to expand.

-

All groups are expanded when groupid is not specified.

-

currentOffset

-

-

-

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

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

Name

-

Type

-

Mandatory

-

Default Value

-

Remarks

-

dx

-

number

-

No

-

0

-

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

-

dy

-

number

-

No

-

0

-

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

-

smooth

-

boolean

-

No

-

true

-

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

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

Name

-

Type

-

Remarks

-

x

-

number

-

Scrolling offset in the x-axis, in px

-

y

-

number

-

Scrolling offset in the y-axis, in px

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

Name

-

Type

-

Default Value

-

Mandatory

-

Triggered when

-

type

-

string

-

foldable

-

Yes

-

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

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

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

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

    -
-

mode

-

string

-

full

-

No

-

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

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

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

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

    -
-

dragbar

-

boolean

-

true

-

No

-

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

-

fullheight

-

<length>

-

-

-

No

-

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

-

halfheight

-

<length>

-

-

-

No

-

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

-

miniheight

-

<length>

-

-

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Triggered when

-

padding

-

<length>

-

0

-

No

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

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

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

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

    -
-
-

padding-[left|top|right|bottom]

-

<length>

-

0

-

No

-

Left, top, right, and bottom padding.

-

padding-[start|end]

-

<length>

-

0

-

No

-

Start and end padding.

-

margin

-

<length>

-

0

-

No

-

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

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

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

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

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

    -
-

margin-[left|top|right|bottom]

-

<length>

-

0

-

No

-

Left, top, right, and bottom margins.

-

margin-[start|end]

-

<length>

-

0

-

No

-

Start and end margins.

-

border

-

-

-

0

-

No

-

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

-

border-style

-

string

-

solid

-

No

-

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

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

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

-

string

-

solid

-

No

-

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

-

border-[left|top|right|bottom]

-

-

-

-

-

No

-

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

-

border-width

-

<length>

-

0

-

No

-

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

-

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

-

<length>

-

0

-

No

-

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

-

border-color

-

<color>

-

black

-

No

-

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

-

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

-

<color>

-

black

-

No

-

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

-

border-radius

-

<length>

-

-

-

No

-

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

-

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

-

<length>

-

-

-

No

-

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

-

background

-

<linear-gradient>

-

-

-

No

-

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

-

background-color

-

<color>

-

-

-

No

-

Background color.

-

background-image

-

string

-

-

-

No

-

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

-

background-size

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

auto

-

No

-

Background image size.

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

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

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

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

    -
-

background-repeat

-

string

-

repeat

-

No

-

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

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

background-position

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

0px 0px

-

No

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

opacity

-

number

-

1

-

No

-

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

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

Name

-

Parameter

-

Triggered when

-

sizechange

-

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

-

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

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

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

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

    -
    NOTE:

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

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

Name

-

Parameter

-

Triggered when

-

show

-

-

-

Pops the slidable panel up.

-

close

-

-

-

Closes the slidable panel that has been popped up.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

target

-

string

-

-

-

Yes

-

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

-

placement

-

string

-

bottom

-

No

-

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

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

keepalive5+

-

boolean

-

false

-

No

-

Whether to retain this pop-up.

-

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

-

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

-

clickable5+

-

boolean

-

true

-

No

-

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

-

arrowoffset5+

-

<length>

-

0

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

mask-color

-

<color>

-

-

-

No

-

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

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

Name

-

Parameters

-

Description

-

visibilitychange

-

{ visibility: boolean }

-

Triggered when a pop-up appears or disappears.

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

Name

-

Parameters

-

Description

-

show5+

-

-

-

Pops up a message.

-

hide5+

-

-

-

Hides a pop-up.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

offset

-

<length>

-

-

-

No

-

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

-

refreshing

-

boolean

-

false

-

No

-

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

-

type

-

string

-

auto

-

No

-

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

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

lasttime

-

boolean

-

false

-

No

-

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

-

timeoffset6+

-

<length>

-

-

-

No

-

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

-

friction

-

number

-

42

-

No

-

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

-
NOTE:

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

background-color

-

<color>

-

white

-

No

-

Background color of the <refresh> component.

-

progress-color

-

<color>

-

black

-

No

-

Loading color of the <refresh> component.

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

Name

-

Parameter

-

Description

-

refresh

-

{ refreshing: refreshingValue }

-

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

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

pulldown

-

{ state: string }

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

index

-

number

-

0

-

No

-

Index of a child component currently displayed in the container.

-

autoplay

-

boolean

-

false

-

No

-

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

-

interval

-

number

-

3000

-

No

-

Autoplay interval, in milliseconds, when autoplay is enabled.

-

indicator

-

boolean

-

true

-

No

-

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

-

digital5+

-

boolean

-

false

-

No

-

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

-
NOTE:

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

-
-

indicatordisabled5+

-

boolean

-

false

-

No

-

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

-

loop

-

boolean

-

true

-

No

-

Whether to enable looping.

-

duration

-

number

-

-

-

No

-

Duration of the autoplay for child component switching.

-

vertical

-

boolean

-

false

-

No

-

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

-

cachedsize7+

-

number

-

-1

-

No

-

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

-

scrolleffect7+

-

string

-

spring

-

No

-

Scroll effect. The options are as follows:

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

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

indicator-color

-

<color>

-

-

-

No

-

Fill color of the navigation point indicator.

-

indicator-selected-color

-

<color>

-

#ff007dff

-

No

-

Color of the currently selected navigation point indicator.

-

indicator-size

-

<length>

-

4px

-

No

-

Diameter of the navigation point indicator.

-

indicator-top|left|right|bottom

-

<length> | <percentage>

-

-

-

No

-

Relative position of the indicator in the swiper.

-

next-margin7+

-

<length> | <percentage>

-

-

-

No

-

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

-

previous-margin7+

-

<length> | <percentage>

-

-

-

No

-

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

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

Name

-

Parameter

-

Description

-

change

-

{ index: currentIndex }

-

Triggered when the index of the currently displayed component changes.

-

rotation

-

{ value: rotationValue }

-

Triggered when the crown of the wearable rotates.

-

animationfinish7+

-

-

-

Triggered when the animation is finished.

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

Name

-

Parameter

-

Description

-

swipeTo

-

{ index: number(specified position) }

-

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

-

showNext

-

None

-

Shows the next child component.

-

showPrevious

-

None

-

Shows the previous child component.

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

mode

-

string

-

scrollable

-

No

-

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

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

Name

-

Type

-

Default Value

-

Mandatory

-

Description

-

index

-

number

-

0

-

No

-

Index of the active tab.

-

vertical

-

boolean

-

false

-

No

-

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

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

Name

-

Parameter

-

Description

-

change

-

{ index: indexValue }

-

Triggered upon tab switching.

-
NOTE:

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

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

Attribute

-

Type

-

Description

-

data

-

Object/Function

-

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

-

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

-

props

-

Array/Object

-

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

-

computed

-

Object

-

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

-
+**Table 1** Objects +| Name | Type | Description | +| -------- | --------------- | ---------------------------------------- | +| data | Object/Function | Data model of the page. If the attribute is of the function type, the return value must be of the object type. The attribute name cannot start with a dollar sign ($) or underscore (_). Do not use reserved words (**for**, **if**, **show**, and **tid**).
Do not use this attribute and **private** or **public** at the same time.(Rich) | +| props | Array/Object | Used for communication between components. This attribute can be transferred to components via **\**. A **props** name must be in lowercase and cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words (**for**, **if**, **show**, and **tid**). Currently, **props** does not support functions.| +| computed | Object | Used for pre-processing an object for reading and setting. The result is cached. The name cannot start with a dollar sign ($) or underscore (\_). Do not use reserved words.| diff --git a/en/application-dev/reference/arkui-js/js-components-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 f214967694d8534769932d1b1f0e9d95dc54e61f..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,202 +1,45 @@ # animate -The **** component is used to apply animation to an **** component. ->![](../../public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** > ->This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> 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 animation to an **\** component. ## Required Permissions None + ## 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.

-
+| 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
@@ -208,9 +51,11 @@ Not supported
``` -![](figures/animate-1.gif) -``` +![zh-cn_image_0000001173324703](figures/zh-cn_image_0000001173324703.gif) + + +```html
@@ -222,9 +67,11 @@ Not supported
``` -![](figures/1-10.gif) -``` +![zh-cn_image_0000001167662852](figures/zh-cn_image_0000001167662852.gif) + + +```html
@@ -235,9 +82,11 @@ Not supported
``` -![](figures/animate-3.gif) -``` +![zh-cn_image_0000001127284938](figures/zh-cn_image_0000001127284938.gif) + + +```html
@@ -267,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 1cb9c1f4eb4520ab4e85193353fd0798d23158ca..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,55 +1,37 @@ # animateTransform -The **** component is used to apply a transform animation and supports the following components: -, , , , , , , - ->**NOTE** +> **NOTE** > ->This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. + +The **\** component is used to apply a transform animation and supports the following components: + + +<circle>, <ellipse>, <line>, <path>, <polygon>, <polyline>, <rect>, <text> ## Required Permissions None + ## 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.

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

Name

-

Type

-

Description

-

filter

-

string

-

Image filter.

-

Available options are as follows:

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

Name

-

Type

-

Mandatory

-

Description

-

path

-

Path2D

-

No

-

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

-

x

-

number

-

Yes

-

X-coordinate of the point used for checking.

-

y

-

number

-

Yes

-

Y-coordinate of the point used for checking.

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

Type

-

Description

-

boolean

-

Whether a specified point is in the path area.

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

Name

-

Type

-

Mandatory

-

Description

-

path

-

Path2D

-

No

-

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

-

x

-

number

-

Yes

-

X-coordinate of the point used for checking.

-

y

-

number

-

Yes

-

Y-coordinate of the point used for checking.

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

Type

-

Description

-

boolean

-

Whether a specified point is in the path area.

-
- -- Example - - ``` - -
- In path:{{textValue}} - -
- ``` - - ``` - // xxx.js - export default { - data: { - textValue: 0 - }, - onShow(){ - var canvas = this.$refs.canvas.getContext('2d'); - var offscreen = new OffscreenCanvas(500,500); - var offscreenCanvasCtx = offscreen.getContext("2d"); - - offscreenCanvasCtx.rect(10, 10, 100, 100); - offscreenCanvasCtx.stroke(); - this.textValue = offscreenCanvasCtx.isPointInStroke(50, 10); - - var bitmap = offscreen.transferToImageBitmap(); - canvas.transferFromImageBitmap(bitmap); - } - } - ``` - - ![](figures/en-us_image_0000001178875308.png) - - -### resetTransform - -resetTransform\(\): void - -- Example - - ``` - -
- In path:{{textValue}} - -
- ``` - - ``` - //xxx.js - export default { - data:{ - textValue:0 - }, - onShow(){ - var canvas = this.$refs.canvas.getContext('2d'); - var offscreen = new OffscreenCanvas(500,500); - var offscreenCanvasCtx = offscreen.getContext("2d"); - - offscreenCanvasCtx.transform(1, 0, 1.7, 1, 0, 0); - offscreenCanvasCtx.fillStyle = 'gray'; - offscreenCanvasCtx.fillRect(40, 40, 50, 20); - offscreenCanvasCtx.fillRect(40, 90, 50, 20); - - // Non-skewed rectangles - offscreenCanvasCtx.resetTransform(); - offscreenCanvasCtx.fillStyle = 'red'; - offscreenCanvasCtx.fillRect(40, 40, 50, 20); - offscreenCanvasCtx.fillRect(40, 90, 50, 20); - - var bitmap = offscreen.transferToImageBitmap(); - canvas.transferFromImageBitmap(bitmap); - } - } - ``` - - ![](figures/en-us_image_0000001179035242.png) - +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------------------------- | +| path | Path2D | No | Path used for checking. If this parameter is not set, the current path is used.| +| x | number | Yes | X-coordinate of the point used for checking. | +| y | number | Yes | Y-coordinate of the point used for checking. | + +**Return value** +| Type | Description | +| ------- | ------------- | +| boolean | Whether a specified point is in the path area.| + +**Example** +```html + +
+ In path:{{textValue}} + +
+``` + +```js +// xxx.js +export default { + data: { + textValue: 0 + }, + onShow(){ + var canvas = this.$refs.canvas.getContext('2d'); + var offscreen = new OffscreenCanvas(500,500); + var offscreenCanvasCtx = offscreen.getContext("2d"); + + offscreenCanvasCtx.rect(10, 10, 100, 100); + offscreenCanvasCtx.stroke(); + this.textValue = offscreenCanvasCtx.isPointInStroke(50, 10); + + var bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); + } +} +``` + +![en-us_image_0000001178875308](figures/en-us_image_0000001178875308.png) + +### resetTransform + +resetTransform(): void + +**Example** +```html + +
+ In path:{{textValue}} + +
+``` + +```js +// xxx.js +export default { + data:{ + textValue:0 + }, + onShow(){ + var canvas = this.$refs.canvas.getContext('2d'); + var offscreen = new OffscreenCanvas(500,500); + var offscreenCanvasCtx = offscreen.getContext("2d"); + + offscreenCanvasCtx.transform(1, 0, 1.7, 1, 0, 0); + offscreenCanvasCtx.fillStyle = 'gray'; + offscreenCanvasCtx.fillRect(40, 40, 50, 20); + offscreenCanvasCtx.fillRect(40, 90, 50, 20); + + // Non-skewed rectangles + offscreenCanvasCtx.resetTransform(); + offscreenCanvasCtx.fillStyle = 'red'; + offscreenCanvasCtx.fillRect(40, 40, 50, 20); + offscreenCanvasCtx.fillRect(40, 90, 50, 20); + + var bitmap = offscreen.transferToImageBitmap(); + canvas.transferFromImageBitmap(bitmap); + } +} +``` + +![en-us_image_0000001179035242](figures/en-us_image_0000001179035242.png) diff --git a/en/application-dev/reference/arkui-ts/figures/align.png b/en/application-dev/reference/arkui-ts/figures/align.png new file mode 100644 index 0000000000000000000000000000000000000000..beed805dbff1ec1526bf034c011cf2c7b926eae8 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/align.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422904.jpg b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422904.jpg new file mode 100644 index 0000000000000000000000000000000000000000..bf5c3a49c58818ec9dec43db3c2d4c5e16949a94 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001174422904.jpg differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218456.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218456.gif deleted file mode 100644 index 3174da059167d3560a99d50cca06ec678cabed96..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001212218456.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.png new file mode 100644 index 0000000000000000000000000000000000000000..9eb00739d606ea0b53542eba7c43f6cbb82c73c5 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001231374559.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858409.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858409.gif deleted file mode 100644 index ee69d15a36eda3047be045a3d037fd27a37166fe..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256858409.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978333.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978333.png deleted file mode 100644 index 5499902761b534f84a0405094afe2fb5d4724322..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001256978333.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058421.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058421.gif deleted file mode 100644 index fe69ab973cfd17f540dd1da4fd04de890af95c74..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058421.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058443.png b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058443.png deleted file mode 100644 index 92ddc7d5d9ee2f87128ed8951b2294ea3c07f650..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257058443.png and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138367.gif b/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138367.gif deleted file mode 100644 index dffa33c4389c4576d2492cd98499b71715b8ead8..0000000000000000000000000000000000000000 Binary files a/en/application-dev/reference/arkui-ts/figures/en-us_image_0000001257138367.gif and /dev/null differ diff --git a/en/application-dev/reference/arkui-ts/figures/nozindex.png b/en/application-dev/reference/arkui-ts/figures/nozindex.png new file mode 100644 index 0000000000000000000000000000000000000000..8c131eabacb8bcdee0b8ba891faaab69bb2a08bd Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/nozindex.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/opacity.png b/en/application-dev/reference/arkui-ts/figures/opacity.png new file mode 100644 index 0000000000000000000000000000000000000000..d95114ede941db77cf865d3fab288f602ddcc1d0 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/opacity.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/popup.gif b/en/application-dev/reference/arkui-ts/figures/popup.gif new file mode 100644 index 0000000000000000000000000000000000000000..b32a43bd8fc4ae6416b8402c61e1d8e3b9e694ef Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/popup.gif differ diff --git a/en/application-dev/reference/arkui-ts/figures/position.png b/en/application-dev/reference/arkui-ts/figures/position.png new file mode 100644 index 0000000000000000000000000000000000000000..0c9e34bf611b4d51a49875d71f23fef24d6e2571 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/position.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/richText.png b/en/application-dev/reference/arkui-ts/figures/richText.png new file mode 100644 index 0000000000000000000000000000000000000000..65826de750d037a394178b66805a9d1ffdad374e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/richText.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/size.png b/en/application-dev/reference/arkui-ts/figures/size.png new file mode 100644 index 0000000000000000000000000000000000000000..5170abe9fb68747018cecc57e27df68806bafac4 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/size.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textExp1.png b/en/application-dev/reference/arkui-ts/figures/textExp1.png new file mode 100644 index 0000000000000000000000000000000000000000..15d8410388040337f52a039f946d20f3cc0504fc Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textExp1.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textExp2.png b/en/application-dev/reference/arkui-ts/figures/textExp2.png new file mode 100644 index 0000000000000000000000000000000000000000..f6d1aa365e071f3064e25fe45afa4ce4efcddb65 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textExp2.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/textstyle.png b/en/application-dev/reference/arkui-ts/figures/textstyle.png new file mode 100644 index 0000000000000000000000000000000000000000..38128cb5f1a6aa7a36a3b4e483bf2815c7170117 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/textstyle.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/visibility.png b/en/application-dev/reference/arkui-ts/figures/visibility.png new file mode 100644 index 0000000000000000000000000000000000000000..89018fade9d9bef19dfc8a55d4477ba309353871 Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/visibility.png differ diff --git a/en/application-dev/reference/arkui-ts/figures/zindex.png b/en/application-dev/reference/arkui-ts/figures/zindex.png new file mode 100644 index 0000000000000000000000000000000000000000..bb2193d497c6cce42b5d7c6c94671c8bf7f6158e Binary files /dev/null and b/en/application-dev/reference/arkui-ts/figures/zindex.png differ diff --git a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md index f1bce5a8cc619c0e72e1bff539b311d355c23755..d7b27a661400b2557de5cf6c710f26b0d00e05a5 100644 --- a/en/application-dev/reference/arkui-ts/ts-appendix-enums.md +++ b/en/application-dev/reference/arkui-ts/ts-appendix-enums.md @@ -137,9 +137,9 @@ | Name | Description | | -------- | ---------------------- | | Top | Top edge in the vertical direction. | -| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9. | +| Center(deprecated) | Center position in the vertical direction.
This API is deprecated since API version 9. | | Bottom | Bottom edge in the vertical direction. | -| Baseline(deprecated) | Text baseline position in the cross axis direction.
This API is deprecated since API version 9.| +| Baseline(deprecated) | Text baseline position in the cross axis direction.
This API is deprecated since API version 9. | | Start | Start position in the horizontal direction. | | Middle(deprecated) | Center position in the horizontal direction.
This API is deprecated since API version 9. | | End | End position in the horizontal direction. | @@ -249,7 +249,7 @@ | End | The child components are aligned with the end edge of the main axis. The last component is aligned with the main-end, and other components are aligned with the next one.| | SpaceBetween | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The first component is aligned with the main-start, the last component is aligned with the main-end, and the remaining components are distributed so that the space between any two adjacent components is the same.| | SpaceAround | The child components are evenly distributed along the main axis. The space between any two adjacent components is the same. The space between the first component and main-start, and that between the last component and cross-main are both half the size of the space between two adjacent components.| -| SpaceEvenly | The child components are equally distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between two adjacent components are the same.| +| SpaceEvenly | The child components are evenly distributed along the main axis. The space between the first component and main-start, the space between the last component and main-end, and the space between any two adjacent components are the same. | ## ItemAlign @@ -355,9 +355,9 @@ | Name | Description | | -------- | -------------------------------------- | -| Clip | Extra-long text is truncated. | +| Clip | Extra-long text is clipped. | | Ellipsis | An ellipsis (...) is used to represent clipped text.| -| None | No truncation or ellipsis is used for extra-long text. | +| None | No clipping or ellipsis is used for extra-long text. | ## TextDecorationType @@ -413,9 +413,9 @@ | Name | Description | | ----------- | -------------------- | -| None | Copy and paste is not allowed. | -| InApp | Intra-application copy and paste is allowed.| -| LocalDevice | Intra-device copy and paste is allowed.| +| None | Copy is not allowed. | +| InApp | Intra-application copy is allowed.| +| LocalDevice | Intra-device copy is allowed.| ## HitTestMode9+ diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md index 66c2850e7450574935e07e7d7cc8244653fab906..da9cd933dea63ae836c5f225d6eaab29c1fbdbf4 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-richtext.md @@ -2,17 +2,15 @@ The **\** component parses and displays HTML text. -> **NOTE** +> **NOTE** > -> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions -None ## Child Components -None +Not supported ## APIs @@ -20,9 +18,9 @@ RichText(content:string) **Parameters** -| Name| Type| Mandatory| Default Value| Description| -| -------- | -------- | -------- | -------- | -------- | -| content | string | Yes| - | String in HTML format.| +| Name| Type| Mandatory | Description| +| ------- | -------- | ------------- | -------- | +| content | string | Yes | String in HTML format.| ## Events @@ -49,34 +47,38 @@ RichText(content:string) | \ | Used to embed or reference a client-side script, such as JavaScript.| \ | ## Example + You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. + ```ts // xxx.ets @Entry @Component struct RichTextExample { - @State data: string = "

h1 heading

" + - "

h1 italic

" + - "

h1 underlined

" + - "

h2 heading

" + - "

h3 heading

" + - "

Regular paragraph


" + - "
" + - "

Font size: 35px; line height: 45px

" + - "

" + - "

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

" + @State data: string = '

h1 heading

' + + '

h1 italic

' + + '

h1 underlined

' + + '

h2 heading

' + + '

h3 heading

' + + '

Regular paragraph


' + + '
' + + '

Font size: 35px; line height: 45px

' + + '

' + + '

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

'; build() { - Flex({direction: FlexDirection.Column,alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }){ + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, + justifyContent: FlexAlign.Center }) { RichText(this.data) - .onStart(()=>{ - console.info("RichText onStart") - }) - .onComplete(()=>{ - console.info("RichText onComplete") - }) + .onStart(() => { + console.info('RichText onStart'); + }) + .onComplete(() => { + console.info('RichText onComplete'); + }) } } } ``` + + ![richText](figures/richText.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index 16a2de9bd3026c60ef1ff972133487dc9dd76b3e..354cd00042b8ba46a1cf9a68effc32f792c9f48a 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -2,7 +2,7 @@ The **\** component is used to display a piece of textual information. -> **NOTE** +> **NOTE**
> > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -26,27 +26,29 @@ Text(content?: string | Resource) In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Description| -| -------- | -------- | -------- | -| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Text alignment mode of multiple lines of text.
Default value: **TextAlign.Start**| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect. | -| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode. | -| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| -| decoration | {
type: TextDecorationType,
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: {
type: TextDecorationType.None,
color: Color.Black
} | -| baselineOffset | number \| string | Offset of the text baseline. | -| letterSpacing | number \| string | Letter spacing. | -| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size. | -| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size. | -| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**| +| Name | Type | Description | +| ----------------------- | ----------------------------------- | ------------------------------------------- | +| textAlign | [TextAlign](ts-appendix-enums.md#textalign) | Horizontal alignment mode of the text.
Default value: **TextAlign.Start**| +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md#textoverflow)} | Display mode when the text is too long.
Default value: **{overflow: TextOverflow.Clip}**
**NOTE**
Text is clipped at the transition between words. To clip text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect.| +| maxLines | number | Maximum number of lines in the text.
Default value: **Infinity**
**NOTE**
By default, text is automatically folded. If this attribute is specified, the text will not exceed the specified number of lines. If there is extra text, you can use **textOverflow** to specify how it is displayed.| +| lineHeight | string \| number \| [Resource](ts-types.md#resource) | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: [ResourceColor](ts-types.md#resourcecolor)
} | Style and color of the text decorative line.
Default value: **{
type: TextDecorationType.None,
color: Color.Black
}** | +| baselineOffset | number \| string | Baseline offset of the text. The default value is **0**. | +| letterSpacing | number \| string | Letter spacing. | +| minFontSize | number \| string \| [Resource](ts-types.md#resource) | Minimum font size. | +| maxFontSize | number \| string \| [Resource](ts-types.md#resource) | Maximum font size. | +| textCase | [TextCase](ts-appendix-enums.md#textcase) | Text case.
Default value: **TextCase.Normal**| | copyOption9+ | [CopyOptions](ts-appendix-enums.md#copyoptions9) | Whether copy and paste is allowed.
Default value: **CopyOptions.None**| -> **NOTE** +> **NOTE**
> > The **\** component cannot contain both the text and the child component **\**. If both of them exist, only the content in **\** is displayed. ## Example +### Example 1 +Examples of using **textAlign**, **textOverflow**, **maxLines**, and **lineHeight** ```ts // xxx.ets @Entry @@ -54,77 +56,184 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the struct TextExample1 { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { - Text('lineHeight').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text with the line height set This is the text with the line height set This is the text with the line height set.') - .lineHeight(25).fontSize(12).border({ width: 1 }).padding(10) + // Set the horizontal alignment mode for the text. + // Single-line text + Text('textAlign').fontSize(9).fontColor(0xCCCCCC) + Text('TextAlign set to Center.') + .textAlign(TextAlign.Center) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('TextAlign set to Start.') + .textAlign(TextAlign.Start) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('TextAlign set to End.') + .textAlign(TextAlign.End) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') - Text('TextOverflow').fontSize(9).fontColor(0xCCCCCC) - Text('This is the setting of textOverflow to none text content This is the setting of textOverflow to none text content.') + // Multi-line text + Text('This is the text content with textAlign set to Center.') + .textAlign(TextAlign.Center) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with textAlign set to Start.') + .textAlign(TextAlign.Start) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with textAlign set to End.') + .textAlign(TextAlign.End) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + + // Set the display mode when the text is too long. + Text('TextOverflow+maxLines').fontSize(9).fontColor(0xCCCCCC) + // Clip the text when the value of maxLines is exceeded. + Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content. This is the setting of textOverflow to Clip text content This is the setting of textOverflow to None text content.') .textOverflow({ overflow: TextOverflow.None }) - .fontSize(12).border({ width: 1 }).padding(10) - Text('This is the setting of textOverflow to Clip text content This is the setting of textOverflow to Clip text content.') - .textOverflow({ overflow: TextOverflow.Clip }) - .maxLines(1).fontSize(12).border({ width: 1 }).padding(10) - Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.'.split('').join('\u200B')) + .maxLines(1) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + + // Show an ellipsis (...) when the value of maxLines is exceeded. + Text('This is set textOverflow to Ellipsis text content This is set textOverflow to Ellipsis text content.'.split('') + .join('\u200B')) .textOverflow({ overflow: TextOverflow.Ellipsis }) - .maxLines(1).fontSize(12).border({ width: 1 }).padding(10) + .maxLines(1) + .fontSize(12) + .border({ width: 1 }) + .padding(10) - Text('decoration').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text content with the decoration set to Underline and the color set to Red.') - .decoration({ type: TextDecorationType.Underline, color: Color.Red }) + Text('lineHeight').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text with the line height set. This is the text with the line height set.') .fontSize(12).border({ width: 1 }).padding(10) - Text('This is the text content with the decoration set to LineThrough and the color set to Red.') - .decoration({ type: TextDecorationType.LineThrough, color: Color.Red }) - .fontSize(12).border({ width: 1 }).padding(10) - Text('This is the text content with the decoration set to Overline and the color set to Red.') - .decoration({ type: TextDecorationType.Overline, color: Color.Red }) + Text('This is the text with the line height set. This is the text with the line height set.') .fontSize(12).border({ width: 1 }).padding(10) + .lineHeight(20) }.height(600).width(350).padding({ left: 35, right: 35, top: 35 }) } } ``` +![textExp1](figures/textExp1.png) -![en-us_image_0000001257138337](figures/en-us_image_0000001257138337.gif) - +### Example 2 +Example of using **decoration**, **baselineOffset**, **letterSpacing**, and **textCase**: ```ts -// xxx.ets @Entry @Component struct TextExample2 { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Start, justifyContent: FlexAlign.SpaceBetween }) { + Text('decoration').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text content with the decoration set to LineThrough and the color set to Red.') + .decoration({ + type: TextDecorationType.LineThrough, + color: Color.Red + }) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + + Text('This is the text content with the decoration set to Overline and the color set to Red.') + .decoration({ + type: TextDecorationType.Overline, + color: Color.Red + }) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + + Text('This is the text content with the decoration set to Underline and the color set to Red.') + .decoration({ + type: TextDecorationType.Underline, + color: Color.Red + }) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + // Set the text baseline offset. + Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text content with baselineOffset 0.') + .baselineOffset(0) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with baselineOffset 30.') + .baselineOffset(30) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with baselineOffset -20.') + .baselineOffset(-20) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + + // Set the letter spacing. + Text('letterSpacing').fontSize(9).fontColor(0xCCCCCC) + Text('This is the text content with letterSpacing 0.') + .letterSpacing(0) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with letterSpacing 3.') + .letterSpacing(3) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('This is the text content with letterSpacing -1.') + .letterSpacing(-1) + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + Text('textCase').fontSize(9).fontColor(0xCCCCCC) Text('This is the text content with textCase set to Normal.') .textCase(TextCase.Normal) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + // Display the text in lowercase. Text('This is the text content with textCase set to LowerCase.') .textCase(TextCase.LowerCase) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') + .fontSize(12) + .border({ width: 1 }) + .padding(10) + .width('100%') + // Display the text in uppercase. Text('This is the text content with textCase set to UpperCase.') .textCase(TextCase.UpperCase) .fontSize(12).border({ width: 1 }).padding(10) - Text('textAlign').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text content with textAlign set to Center.') - .textAlign(TextAlign.Center) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with textAlign set to Start.') - .textAlign(TextAlign.Start) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with textAlign set to End.') - .textAlign(TextAlign.End) - .fontSize(12).border({ width: 1 }).padding(10).width('100%') - - Text('baselineOffset').fontSize(9).fontColor(0xCCCCCC) - Text('This is the text content with baselineOffset set to 10.') - .baselineOffset(10).fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with baselineOffset set to 30.') - .baselineOffset(30).fontSize(12).border({ width: 1 }).padding(10).width('100%') - Text('This is the text content with baselineOffset set to -10.') - .baselineOffset(-10).fontSize(12).border({ width: 1 }).padding(10).width('100%') }.height(700).width(350).padding({ left: 35, right: 35, top: 35 }) } } ``` - -![en-us_image_0000001257058391](figures/en-us_image_0000001257058391.gif) +![textExp1](figures/textExp2.png) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md index 1bc12e9014024c9c3fe02f783ca6d65934f98d9f..cc432c20a683e8ae1b81b4772eb9961a8e575935 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-timepicker.md @@ -48,14 +48,14 @@ Creates a time picker whose default time range is from 00:00 to 23:59. ## Example -### Time Selector +### Time Picker ```ts // xxx.ets @Entry @Component struct TimePickerExample { - private selectedTime: Date = new Date('7/22/2022 8:00:00') + private selectedTime: Date = new Date('2022-07-22T08:00:00') build() { Column() { diff --git a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md index 80715dd307dc9164a788de5eda9b073dd1368e42..161072762c3bd658d17c6afea7882a357f58a7af 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-gestures-swipegesture.md @@ -16,7 +16,7 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | fingers | number | No| Minimum number of fingers to trigger a swipe gesture. The value ranges from 1 to 10.
Default value: **1**| -| direction | SwipeDirection | No| Swipe direction.
Default value: **SwipeDirection.All**| +| direction | [swipeDirection](#swipedirection)| No| Swipe direction.
Default value: **SwipeDirection.All**| | speed | number | No| Minimum speed of the swipe gesture, in vp/s.
Default value: **100**| ## SwipeDirection @@ -24,8 +24,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num | Name| Description| | -------- | -------- | | All | All directions.| -| Horizontal | Horizontal direction.| -| Vertical | Vertical direction.| +| Horizontal | Horizontal direction. The gesture event is triggered when the angle between the finger moving direction and the x-axis is less than 45 degrees.| +| Vertical | Vertical direction. The gesture event is triggered when the angle between the finger moving direction and the y-axis is less than 45 degrees.| | None | Swiping disabled.| @@ -33,9 +33,8 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num | Name| Description| | -------- | -------- | -| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md)) => void) | Triggered when a swipe gesture is recognized.| +| onAction(event:(event?: [GestureEvent](ts-gesture-settings.md#gestureevent)) => void) | Triggered when a swipe gesture is recognized.| -![en-us_image_0000001231374661](figures/en-us_image_0000001231374661.png) ## Example ```ts @@ -43,27 +42,31 @@ SwipeGesture(value?: { fingers?: number; direction?: SwipeDirection; speed?: num @Entry @Component struct SwipeGestureExample { - @State rotateAngle : number = 0 - @State speed : number = 1 + @State rotateAngle: number = 0; + @State speed: number = 1; build() { Column() { - Text("SwipGesture speed : " + this.speed) - Text("SwipGesture angle : " + this.rotateAngle) - } - .position({x: 80, y: 200}) - .border({width:2}) - .width(260).height(260) - .rotate({x: 0, y: 0, z: 1, angle: this.rotateAngle}) - .gesture( - SwipeGesture({fingers: 1, direction: SwipeDirection.Vertical}) + Column() { + Text("SwipeGesture speed\n" + this.speed) + Text("SwipeGesture angle\n" + this.rotateAngle) + } + .border({ width: 3 }) + .width(300) + .height(200) + .margin(100) + .rotate({ angle: this.rotateAngle }) + // The gesture event is triggered by swiping vertically with one finger. + .gesture( + SwipeGesture({ direction: SwipeDirection.Vertical }) .onAction((event: GestureEvent) => { - this.speed = event.speed - this.rotateAngle = event.angle - }) - ) + this.speed = event.speed; + this.rotateAngle = event.angle; + }) + ) + }.width('100%') } } ``` -![en-us_image_0000001231374559](figures/en-us_image_0000001231374559.gif) + ![en-us_image_0000001231374559.png](figures/en-us_image_0000001231374559.png) diff --git a/en/application-dev/reference/arkui-ts/ts-container-badge.md b/en/application-dev/reference/arkui-ts/ts-container-badge.md index 912f89de44f63e6e3bb896efb5fa64025f4bd115..7d51379bea19538c5e1c5498d2165373331ed924 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-badge.md +++ b/en/application-dev/reference/arkui-ts/ts-container-badge.md @@ -29,7 +29,7 @@ Create a badge. | count | number | Yes| - | Number of notifications.| | position | BadgePosition | No| BadgePosition.RightTop | Position to display the badge relative to the parent component.| | maxCount | number | No| 99 | Maximum number of notifications. When the maximum number is reached, only **maxCount+** is displayed.| -| style | BadgeStyle | Yes| - | Style of the **** component, including the text color, text size, badge color, and badge size.| +| style | BadgeStyle | Yes| - | Style of the **\** component, including the text color, text size, badge color, and badge size.| Method 2: Badge(value: {value: string, position?: BadgePosition, style: BadgeStyle}) diff --git a/en/application-dev/reference/arkui-ts/ts-container-flex.md b/en/application-dev/reference/arkui-ts/ts-container-flex.md index 6ef5525a1fc2c0c2f6b079a0c75b302b360b434d..7d6c24e671419edc603a17cdea023878ebc6239d 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-flex.md +++ b/en/application-dev/reference/arkui-ts/ts-container-flex.md @@ -29,8 +29,8 @@ Creates a standard **\** component. | direction | [FlexDirection](ts-appendix-enums.md#flexdirection) | No | FlexDirection.Row | Direction in which child components are arranged in the **\** component, that is, the direction of the main axis. | | wrap | [FlexWrap](ts-appendix-enums.md#flexwrap) | No | FlexWrap.NoWrap | Whether the **\** component has a single line or multiple lines. | | justifyContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in the **\** component along the main axis. | - | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Stretch | Alignment mode of the child components in the **\** component along the cross axis. | - | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.| + | alignItems | [ItemAlign](ts-appendix-enums.md#itemalign) | No | ItemAlign.Start | Alignment mode of the child components in the **\** component along the cross axis. | + | alignContent | [FlexAlign](ts-appendix-enums.md#flexalign) | No | FlexAlign.Start | Alignment mode of the child components in a multi-line **\** component along the cross axis. This parameter is valid only when **wrap** is set to **Wrap** or **WrapReverse**.| ## Example @@ -240,9 +240,7 @@ struct FlexExample4 { } ``` -![en-us_image_0000001257138371](figures/en-us_image_0000001257138371.jpg) - -![en-us_image_0000001212378426](figures/en-us_image_0000001212378426.gif) +![en-us_image_0000001174422904](figures/en-us_image_0000001174422904.jpg) ```ts // xxx.ets diff --git a/en/application-dev/reference/arkui-ts/ts-container-scroll.md b/en/application-dev/reference/arkui-ts/ts-container-scroll.md index 9881904bcc8f635930bae6100064243416031442..37ebd29d9ec78398423a8f86c23c21b3bc64afbf 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-scroll.md +++ b/en/application-dev/reference/arkui-ts/ts-container-scroll.md @@ -6,7 +6,7 @@ The **\** component scrolls the content when the layout size of a compon > - This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > - When nesting a **\** within this component, specify the width and height for the **\** under scenarios where consistently high performance is required. If the width and height are not specified, this component will load all content of the **\**. > - This component can scroll only when the size on the main axis is less than the content size. -> - The prerequisite for the component to rebound is that the component is scrolled. +> - This component can produce a bounce effect only when there is more than one screen of content. ## Child Components @@ -24,11 +24,11 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name | Type | Description | | -------------- | ---------------------------------------- | --------- | -| scrollable | ScrollDirection | Scroll direction.
Default value: **ScrollDirection.Vertical**| +| scrollable | [ScrollDirection](#scrolldirection) | Scroll direction.
Default value: **ScrollDirection.Vertical**| | scrollBar | [BarState](ts-appendix-enums.md#barstate) | Scrollbar status.
Default value: **BarState.Off**| -| scrollBarColor | string \| number \| Color | Color of the scrollbar.| +| scrollBarColor | string \| number \| [Color](ts-appendix-enums.md#color) | Color of the scrollbar.| | scrollBarWidth | string \| number | Width of the scrollbar.| -| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**| +| edgeEffect | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Scroll effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.None**| ## ScrollDirection | Name | Description | @@ -36,7 +36,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Horizontal | Only horizontal scrolling is supported. | | Vertical | Only vertical scrolling is supported. | | None | Scrolling is disabled. | -| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9.| +| Free(deprecated) | Vertical or horizontal scrolling is supported.
This API is deprecated since API version 9. | ## Events @@ -104,7 +104,7 @@ Scrolls to the next or previous page. | Name | Type | Mandatory | Description | | --------- | ------- | ---- | ------------------------------ | | next | boolean | Yes | Whether to turn to the next page. The value **true** means to scroll to the next page, and **false** means to scroll to the previous page.| -| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | +| direction(deprecated) | [Axis](ts-appendix-enums.md#axis) | No | Scrolling direction: horizontal or vertical.
This API is deprecated since API version 9. | ### currentOffset @@ -161,14 +161,15 @@ Scrolls by the specified amount. ## Example +### Example 1 ```ts // xxx.ets @Entry @Component struct ScrollExample { - scroller: Scroller = new Scroller() - private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + scroller: Scroller = new Scroller(); + private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; build() { Stack({ alignContent: Alignment.TopStart }) { @@ -186,38 +187,39 @@ struct ScrollExample { }, item => item) }.width('100%') } - .scrollable(ScrollDirection.Vertical) - .scrollBar(BarState.On) - .scrollBarColor(Color.Gray) - .scrollBarWidth(30) + .scrollable(ScrollDirection.Vertical) // The scrollbar scrolls in the vertical direction. + .scrollBar(BarState.On) // The scrollbar is always displayed. + .scrollBarColor(Color.Gray) // Color of the scrollbar. + .scrollBarWidth(30) // Width of the scrollbar. + .edgeEffect(EdgeEffect.None) .onScroll((xOffset: number, yOffset: number) => { - console.info(xOffset + ' ' + yOffset) + console.info(xOffset + ' ' + yOffset); }) .onScrollEdge((side: Edge) => { - console.info('To the edge') + console.info('To the edge'); }) .onScrollEnd(() => { - console.info('Scroll Stop') + console.info('Scroll Stop'); }) - + Button('scroll 150') .onClick(() => { // Click to scroll down to 150.0 vp. - this.scroller.scrollBy(0,150) + this.scroller.scrollBy(0,150); }) .margin({ top: 10, left: 20 }) Button('scroll 100') .onClick(() => { // Click to scroll down by 100.0 vp. - this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }) + this.scroller.scrollTo({ xOffset: 0, yOffset: this.scroller.currentOffset().yOffset + 100 }); }) .margin({ top: 60, left: 20 }) Button('back top') .onClick(() => { // Click to go back to the top. - this.scroller.scrollEdge(Edge.Top) + this.scroller.scrollEdge(Edge.Top); }) .margin({ top: 110, left: 20 }) Button('next page') .onClick(() => { // Click to go to the next page. - this.scroller.scrollPage({ next: true }) + this.scroller.scrollPage({ next: true }); }) .margin({ top: 170, left: 20 }) }.width('100%').height('100%').backgroundColor(0xDCDCDC) @@ -227,14 +229,14 @@ struct ScrollExample { ![en-us_image_0000001256978363](figures/en-us_image_0000001256978363.gif) - +### Example 2 ```ts @Entry @Component struct NestedScroll { - @State listPosition: number = 0 // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the center of the list, and 2 indicates scrolling to the bottom of the list. - private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] - private scroller: Scroller = new Scroller() + @State listPosition: number = 0; // 0 indicates scrolling to the top of the list, 1 indicates scrolling to the middle of the list, and 2 indicates scrolling to the bottom of the list. + private arr: number[] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; + private scroller: Scroller = new Scroller(); build() { Flex() { @@ -255,18 +257,18 @@ struct NestedScroll { } .width("100%").height("50%").edgeEffect(EdgeEffect.None) .onReachStart(() => { - this.listPosition = 0 + this.listPosition = 0; }) .onReachEnd(() => { - this.listPosition = 2 + this.listPosition = 2; }) .onScrollBegin((dx: number, dy: number) => { if ((this.listPosition == 0 && dy >= 0) || (this.listPosition == 2 && dy <= 0)) { - this.scroller.scrollBy(0, -dy) - return { dxRemain: dx, dyRemain: 0 } + this.scroller.scrollBy(0, -dy); + return { dxRemain: dx, dyRemain: 0 }; } this.listPosition = 1; - return { dxRemain: dx, dyRemain: dy } + return { dxRemain: dx, dyRemain: dy }; }) Text("Scroll Area") diff --git a/en/application-dev/reference/arkui-ts/ts-container-swiper.md b/en/application-dev/reference/arkui-ts/ts-container-swiper.md index 9befeb19bfc2ceb801ad82b29d1ce22c9b1db5f1..a2f9888f7fb5f6fc460a838e3db04ddc5b67a7d8 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-swiper.md +++ b/en/application-dev/reference/arkui-ts/ts-container-swiper.md @@ -40,7 +40,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | displayMode | SwiperDisplayMode | Mode in which elements are displayed along the main axis. This attribute takes effect only when **displayCount** is not set.
Default value: **SwiperDisplayMode.Stretch**| | cachedCount8+ | number | Number of child components to be cached.
Default value: **1** | | disableSwipe8+ | boolean | Whether to disable the swipe feature.
Default value: **false** | -| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves ([interpolation curve objects](ts-interpolation-calculation.md)) by using the API provided by the interpolation calculation module.
Default value: **Curve.Ease**| +| curve8+ | [Curve](ts-appendix-enums.md#curve) \| string | Animation curve. The ease-in/ease-out curve is used by default. For details about common curves, see [Curve](ts-appendix-enums.md#curve). You can also create custom curves (interpolation curve objects) by using the API provided by the interpolation calculation module.
Default value: **Curve.Ease**| | indicatorStyle8+ | {
left?: [Length](ts-types.md#length),
top?: [Length](ts-types.md#length),
right?: [Length](ts-types.md#length),
bottom?: [Length](ts-types.md#length),
size?: [Length](ts-types.md#length),
mask?: boolean,
color?: [ResourceColor](ts-types.md#resourcecolor),
selectedColor?: [ResourceColor](ts-types.md#resourcecolor)
} | Style of the navigation dots indicator.
\- **left**: distance between the navigation dots indicator and the left edge of the **\** component.
\- **top**: distance between the navigation dots indicator and the top edge of the **\** component.
\- **right**: distance between the navigation dots indicator and the right edge of the **\** component.
\- **bottom**: distance between the navigation dots indicator and the bottom edge of the **\** component.
\- **size**: diameter of the navigation dots indicator.
\- **mask**: whether to enable the mask for the navigation dots indicator.
\- **color**: color of the navigation dots indicator.
\- **selectedColor**: color of the selected navigation dot.| | displayCount8+ | number\|string | Number of elements to display.
Default value: **1** | | effectMode8+ | [EdgeEffect](ts-appendix-enums.md#edgeeffect) | Swipe effect. For details, see **EdgeEffect**.
Default value: **EdgeEffect.Spring**| @@ -62,7 +62,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## SwiperController -Controller of the **\** component. You can bind this object to the **** component and use it to control page switching. +Controller of the **\** component. You can bind this object to the **\** component and use it to control page switching. ### showNext diff --git a/en/application-dev/reference/arkui-ts/ts-gesture-settings.md b/en/application-dev/reference/arkui-ts/ts-gesture-settings.md index 23da0093a624bcae6f17aa2c6c177ed4c283a44f..81a10d89262340b851a66a47c02735c2dd10c006 100644 --- a/en/application-dev/reference/arkui-ts/ts-gesture-settings.md +++ b/en/application-dev/reference/arkui-ts/ts-gesture-settings.md @@ -29,7 +29,7 @@ Use the following attributes to bind gesture recognition to a component. When a | Name| Description| | -------- | -------- | | Normal | The gestures of child components are not masked and are recognized based on the default gesture recognition sequence.| - | IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.
However, the built-in gestures of the child components are not masked. For example, when the child component is a **** component, the built-in sliding gestures can still be triggered.| + | IgnoreInternal | The gestures of child components are masked. Only the gestures of the current component are recognized.
However, the built-in gestures of the child components are not masked. For example, when the child component is a **\** component, the built-in sliding gestures can still be triggered.| - GestureType diff --git a/en/application-dev/reference/arkui-ts/ts-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-methods-timepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md index 2c0d95f5d73e36376cbc44ef7a76d2e234e1bd3c..ba8f9a55944e12d1693f0e82ac91c282a373e814 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-timepicker-dialog.md @@ -1,15 +1,10 @@ # Time Picker Dialog Box -A time picker dialog box is a dialog box that allows users to select a time from the given range, which is from 00:00 to 23:59 by default. +A time picker dialog box is a dialog box that allows users to select a time from the 24-hour range. > **NOTE** > -> The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. - - -## Required Permissions - -None +> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. ## TimePickerDialog.show @@ -18,71 +13,63 @@ show(options?: TimePickerDialogOptions) Shows a time picker dialog box. - TimePickerDialogOptions - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | selected | Date | No| Current system time| Time of the selected item.| - | useMilitaryTime | boolean | No| false | Whether to display time in 24-hour format.| - | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the OK button in the dialog box is clicked.| - | onCancel | () => void | No| - | Callback invoked when the Cancel button in the dialog box is clicked.| - | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| - | Callback invoked when the selected item in the picker changes.| + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | selected | Date | No| Selected time.
Default value: current system time| + | useMilitaryTime | boolean | No| Whether to display time in 24-hour format. The 12-hour format is used by default.
Default value: **false**| + | onAccept | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the OK button in the dialog box is clicked.| + | onCancel | () => void | No| Callback invoked when the Cancel button in the dialog box is clicked.| + | onChange | (value: [TimePickerResult](ts-basic-components-timepicker.md#TimePickerResult)) => void | No| Callback invoked when the selected time changes.| ## Example -### Time Picker Sample Code (24-Hour Clock) ```ts // xxx.ets @Entry @Component -struct TimePickerDialogExample01 { - @State isUseMilitaryTime: boolean = true +struct TimePickerDialogExample { + private selectTime: Date = new Date('2020-12-25T08:30:00') build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("TimePickerDialog").onClick(() => { - TimePickerDialog.show({ - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: TimePickerResult) => { - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("TimePickerDialog:onCancel()") - }, - onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) - } + Column() { + Button ("TimePickerDialog 12-hour format") + .margin(20) + .onClick(() => { + TimePickerDialog.show({ + selected: this.selectTime, + onAccept: (value: TimePickerResult) => { + //Set selectTime to the time when the OK button is clicked. In this way, when the dialog box is displayed again, the selected time is the time when the operation was confirmed last time. + this.selectTime.setHours(value.hour, value.minute) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()"); + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + } + }) }) - }) - } - } -} -``` -### Time Picker Sample Code (12-Hour Clock) -```ts -// xxx.ets -@Entry -@Component -struct TimePickerDialogExample02 { - @State isUseMilitaryTime: boolean = false - - build() { - Flex({direction: FlexDirection.Column, alignItems: ItemAlign.Center, - justifyContent: FlexAlign.Center }) { - Button("TimePickerDialog").onClick(() => { - TimePickerDialog.show({ - useMilitaryTime: this.isUseMilitaryTime, - onAccept: (value: TimePickerResult) => { - console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)) - }, - onCancel: () => { - console.info("TimePickerDialog:onCancel()") - }, - onChange: (value: TimePickerResult) => { - console.info("TimePickerDialog:onChange()" + JSON.stringify(value)) - } + Button ("TimePickerDialog 24-hour format") + .margin(20) + .onClick(() => { + TimePickerDialog.show({ + selected: this.selectTime, + useMilitaryTime: true, + onAccept: (value: TimePickerResult) => { + this.selectTime.setHours(value.hour, value.minute) + console.info("TimePickerDialog:onAccept()" + JSON.stringify(value)); + }, + onCancel: () => { + console.info("TimePickerDialog:onCancel()"); + }, + onChange: (value: TimePickerResult) => { + console.info("TimePickerDialog:onChange()" + JSON.stringify(value)); + } + }) }) - }) - } + }.width('100%') } } ``` diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md index 25737f363751988499f8bc93232b6d4733470b54..0bde935d8e104ad982c322c342abb71b96909a31 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -10,10 +10,10 @@ You can set the background of a component. | Name| Type| Description| | -------- | -------- | -------- | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. | -| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.
**src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. | +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component.| +| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.| | backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.
Default value: **ImageSize.Auto**| -| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.
Default value:
**{
x: 0,
y: 0
}** | +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component, that is, the coordinates relative to the upper left corner of the component.
Default value:
{
x: 0,
y: 0
}
When **x** and **y** are set in percentage, the offset is calculated based on the width and height of the component.| ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md index cfc0e91df2dfb22513ec43800e6a9ed7fecc73e7..9b36249f0a6e49598b50d0e3e2333ab9c3882bc3 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-component-id.md @@ -77,7 +77,7 @@ Sends a touch event. | Name | Type | Mandatory | Description | | ----- | ----------- | ---- | ------------------------------------------------------------ | -| event | TouchObject | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).| +| event | [TouchObject](ts-universal-events-touch.md#touchobject) | Yes | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).| **Return value** @@ -95,7 +95,7 @@ Sends a key event. | Name | Type | Mandatory | Description | | ----- | -------- | ---- | ------------------------------------------------------------ | -| event | KeyEvent | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).| +| event | [KeyEvent](ts-universal-events-key.md#keyevent) | Yes | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).| **Return value** @@ -113,7 +113,7 @@ Sends a mouse event. | Name | Type | Mandatory | Description | | ----- | ---------- | ---- | --------------------------------------- | -| event | MouseEvent | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).| +| event | [MouseEvent](ts-universal-mouse-key.md#mouseevent) | Yes | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).| **Return value** @@ -132,6 +132,7 @@ class Utils { static rect_bottom; static rect_value; + // Obtain the coordinates of the rectangular area occupied by the component. static getComponentRect(key) { let strJson = getInspectorByKey(key); let obj = JSON.parse(strJson); @@ -171,7 +172,7 @@ struct IdExample { console.info(getInspectorTree()) this.text = "Button 'click to start' is clicked" setTimeout(() => { - sendEventByKey("longClick", 11, "") + sendEventByKey("longClick", 11, "") // Send a long-click event to the component whose ID is "longClick". }, 2000) }).id('click') @@ -183,18 +184,18 @@ struct IdExample { console.info('long clicked') this.text = "Button 'longClick' is longclicked" setTimeout(() => { - let rect = Utils.getComponentRect('onTouch') + let rect = Utils.getComponentRect('onTouch') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onTouch". let touchPoint: TouchObject = { id: 1, - x: rect.left + (rect.right - rect.left) / 2, - y: rect.top + (rect.bottom - rect.top) / 2, + x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center. type: TouchType.Down, - screenX: rect.left + (rect.right - rect.left) / 2, - screenY: rect.left + (rect.right - rect.left) / 2, + screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + screenY: rect.left + (rect.right - rect.left) / 2, // Y coordinate of the component center. } - sendTouchEvent(touchPoint) + sendTouchEvent(touchPoint) // Send a touch event. touchPoint.type = TouchType.Up - sendTouchEvent(touchPoint) + sendTouchEvent(touchPoint) // Send a touch event. }, 2000) })).id('longClick') @@ -205,14 +206,14 @@ struct IdExample { console.info('onTouch is clicked') this.text = "Button 'onTouch' is clicked" setTimeout(() => { - let rect = Utils.getComponentRect('onMouse') + let rect = Utils.getComponentRect('onMouse') // Obtain the coordinates of the rectangular area occupied by the component whose ID is "onMouse". let mouseEvent: MouseEvent = { button: MouseButton.Left, action: MouseAction.Press, - x: rect.left + (rect.right - rect.left) / 2, - y: rect.top + (rect.bottom - rect.top) / 2, - screenX: rect.left + (rect.right - rect.left) / 2, - screenY: rect.top + (rect.bottom - rect.top) / 2, + x: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + y: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center. + screenX: rect.left + (rect.right - rect.left) / 2, // X coordinate of the component center. + screenY: rect.top + (rect.bottom - rect.top) / 2, // Y coordinate of the component center. timestamp: 1, target: { area: { @@ -230,7 +231,7 @@ struct IdExample { }, source: SourceType.Mouse } - sendMouseEvent(mouseEvent) + sendMouseEvent(mouseEvent) // Send a mouse event. }, 2000) }).id('onTouch') @@ -250,7 +251,7 @@ struct IdExample { metaKey: 0, timestamp: 0 } - sendKeyEvent(keyEvent) + sendKeyEvent(keyEvent) // Send a key event. }, 2000) }).id('onMouse') diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md index 874baf8801ad127b5bc494bb2601bce1fd7d917d..6e7645eabe12366ced89fb469334612d2205bd9f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-enable.md @@ -12,7 +12,7 @@ The **enabled** attribute sets whether a component responds to user interactions | Name | Type | Description | | ------- | ------- | ---------------------------------------- | -| enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions,
and **false** means the opposite.
Default value: **true**| +| enabled | boolean | Whether the component responds to user interactions, including clicks and touches. The value **true** means that the component responds to user interactions, and **false** means the opposite.
Default value: **true** | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md index cbcf94d324ce0f13098515e1932bc9f77cf6b404..da9f86c336021bc5f7cc10b57803ef7ef2371f2f 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-flex-layout.md @@ -23,7 +23,6 @@ @Entry @Component struct FlexExample { - build() { Column({ space: 5 }) { Text('flexBasis').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -31,11 +30,18 @@ struct FlexExample { // The value of flexBasis() can be 'auto' or a number, which is equivalent to .width()/.height(). Flex() { Text('flexBasis(100)') - .flexBasis('100').height(100).lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexBasis('100') + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) Text('flexBasis("auto")') - .flexBasis('auto').width('60%').height(100).lineHeight(70) - .backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .flexBasis('auto') + .width('60%') + .height(100) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) Text('flexGrow').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -43,11 +49,17 @@ struct FlexExample { // flexGrow() specifies the percentage of the remaining space allocated to the component. Flex() { Text('flexGrow(2)') - .flexGrow(2).height(100).lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexGrow(2) + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) Text('flexGrow(1)') - .flexGrow(1).height(100).lineHeight(70) - .backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .flexGrow(1) + .height(100) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) Text('flexShrink').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -55,13 +67,25 @@ struct FlexExample { // The ratio of text1 is 0, and the default values of other parameters are 1. If the components cannot be completely displayed, the last two components are shrunk proportionally. The first component is not shrunk. Flex({ direction: FlexDirection.Row }) { Text('flexShrink(0)') - .flexShrink(0).width('50%').height(100).lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexShrink(0) + .width('50%') + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) Text('no flexShrink') - .width('40%').height(100).lineHeight(70).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .width('40%') + .height(100) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) Text('flexShrink(2)') - .flexShrink(2).width('40%').height(100) .lineHeight(70) - .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) + .flexShrink(2) + .width('40%') + .height(100) + .lineHeight(70) + .backgroundColor(0xF5DEB3) + .textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) Text('alignSelf').fontSize(9).fontColor(0xCCCCCC).width('90%') @@ -70,8 +94,12 @@ struct FlexExample { Text('no alignSelf,height:80').width('33%').height(80) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) Text('alignSelf stretch') - .alignSelf(ItemAlign.Stretch).width('33%').height(80).lineHeight(70) - .backgroundColor(0xD2B48C).textAlign(TextAlign.Center) + .alignSelf(ItemAlign.Stretch) + .width('33%') + .height(80) + .lineHeight(70) + .backgroundColor(0xD2B48C) + .textAlign(TextAlign.Center) Text('no alignSelf,height:100').width('34%').height(100) .backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) }.width('90%').height(120).padding(10).backgroundColor(0xAFEEEE) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md index b9121ea16f40a620a93c4638772ea1bc76a35cd9..00099110825c5f1ba47594cf3ce9cd671f40f987 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-layout-constraints.md @@ -11,8 +11,8 @@ Layout constraints refer to constraints on the aspect ratio and display priority | Name | Type | Description | | --------------- | ------ | ---------------------------------------- | -| aspectRatio | number | Aspect ratio of the component. | -| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components.| +| aspectRatio | number | Aspect ratio of the component, which can be obtained using the following formula: Width/Height. | +| displayPriority | number | Display priority for the component in the layout container. When the space of the parent container is insufficient, the component with a lower priority is hidden.
The digits after the decimal point are not counted in determining the display priority. That is, numbers in the [x, x + 1) range are considered to represent the same priority. For example, **1.0** and **1.9** represent the same priority.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** (single-row) container components. | ## Example @@ -22,29 +22,32 @@ Layout constraints refer to constraints on the aspect ratio and display priority @Entry @Component struct AspectRatioExample { - private children : string[] = ['1', '2', '3', '4', '5', '6'] + private children: string[] = ['1', '2', '3', '4', '5', '6'] build() { - Column({space: 20}) { + Column({ space: 20 }) { Text('using container: row').fontSize(14).fontColor(0xCCCCCC).width('100%') - Row({space: 10}) { + Row({ space: 10 }) { ForEach(this.children, (item) => { + // Component width = Component height x 1.5 = 90 Text(item) .backgroundColor(0xbbb2cb) .fontSize(20) .aspectRatio(1.5) .height(60) + // Component height = Component width/1.5 = 60/1.5 = 40 Text(item) .backgroundColor(0xbbb2cb) .fontSize(20) .aspectRatio(1.5) .width(60) - }, item=>item) + }, item => item) } - .size({width: "100%", height: 100}) + .size({ width: "100%", height: 100 }) .backgroundColor(0xd2cab3) .clip(true) + // Grid child component width/height = 3/2 Text('using container: grid').fontSize(14).fontColor(0xCCCCCC).width('100%') Grid() { ForEach(this.children, (item) => { @@ -54,12 +57,12 @@ struct AspectRatioExample { .fontSize(40) .aspectRatio(1.5) } - }, item=>item) + }, item => item) } .columnsTemplate('1fr 1fr 1fr') .columnsGap(10) .rowsGap(10) - .size({width: "100%", height: 165}) + .size({ width: "100%", height: 165 }) .backgroundColor(0xd2cab3) }.padding(10) } @@ -67,47 +70,53 @@ struct AspectRatioExample { ``` **Figure 1** Portrait display + ![en-us_image_0000001256978379](figures/en-us_image_0000001256978379.gif) **Figure 2** Landscape display + ![en-us_image_0000001212218476](figures/en-us_image_0000001212218476.gif) ```ts class ContainerInfo { - label : string = '' - size : string = '' + label: string = ''; + size: string = ''; } class ChildInfo { - text : string = '' - priority : number = 0 + text: string = ''; + priority: number = 0; } @Entry @Component struct DisplayPriorityExample { - private container : ContainerInfo[] = [ - {label: 'Big container', size: '90%'}, - {label: 'Middle container', size: '50%'}, - {label: 'Small container', size: '30%'} + // Display the container size. + private container: ContainerInfo[] = [ + { label: 'Big container', size: '90%' }, + { label: 'Middle container', size: '50%' }, + { label: 'Small container', size: '30%' } ] - private children : ChildInfo[] = [ - {text: '1\n(priority:2)', priority: 2}, - {text: '2\n(priority:1)', priority: 1}, - {text: '3\n(priority:3)', priority: 3}, - {text: '4\n(priority:1)', priority: 1}, - {text: '5\n(priority:2)', priority: 2} + private children: ChildInfo[] = [ + { text: '1\n(priority:2)', priority: 2 }, + { text: '2\n(priority:1)', priority: 1 }, + { text: '3\n(priority:3)', priority: 3 }, + { text: '4\n(priority:1)', priority: 1 }, + { text: '5\n(priority:2)', priority: 2 } ] - @State currentIndex : number = 0 + @State currentIndex: number = 0; build() { - Column({space: 10}) { + Column({ space: 10 }) { + // Switch the size of the parent container. Button(this.container[this.currentIndex].label).backgroundColor(0x317aff) - .onClick((event: ClickEvent) => { - this.currentIndex = (this.currentIndex + 1) % this.container.length + .onClick(() => { + this.currentIndex = (this.currentIndex + 1) % this.container.length; }) - Flex({justifyContent: FlexAlign.SpaceBetween}) { - ForEach(this.children, (item)=>{ + // Set the width for the parent flex container through variables. + Flex({ justifyContent: FlexAlign.SpaceBetween }) { + ForEach(this.children, (item) => { + // Bind the display priority to the child component through displayPriority. Text(item.text) .width(120) .height(60) @@ -115,11 +124,11 @@ struct DisplayPriorityExample { .textAlign(TextAlign.Center) .backgroundColor(0xbbb2cb) .displayPriority(item.priority) - }, item=>item.text) + }, item => item.text) } .width(this.container[this.currentIndex].size) .backgroundColor(0xd2cab3) - }.width("100%").margin({top:50}) + }.width("100%").margin({ top: 50 }) } } diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 3cab264048f797063baf0d40f5b489807033967a..0670ab7d107bc99606d151b229b470b7a42a27a7 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -1,6 +1,6 @@ # Location -The location attribute sets the alignment mode, layout direction, and position of a component. +The location attributes set the alignment mode, layout direction, and position of a component. > **NOTE** > @@ -12,25 +12,25 @@ The location attribute sets the alignment mode, layout direction, and position o | Name| Type| Description| | -------- | -------- | -------- | -| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment of the component content. This attribute is valid only when the values of **width** and **height** are greater than the size of the component content.
Default value: **Alignment.Center**| +| align | [Alignment](ts-appendix-enums.md#alignment) | Alignment mode of the component content in the drawing area.
Default value: **Alignment.Center**| | direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.
Default value: **Direction.Auto**| -| position | [Position](ts-types.md#position8) | Offset of the component anchor point relative to the top start edge of the parent component. The offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| -| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.
Default value:
**{
x: 0,
y: 1**
} | -| offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
**{
x: 0,
y: 1
}** | +| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| +| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
} | +| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
} | | alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| ## Example - +### Example 1 ```ts // xxx.ets @Entry @Component -struct PositionExample { - +struct PositionExample1 { build() { Column() { - Column({space: 10}) { + Column({ space: 10 }) { + // When the component content is within the area specified by the component width and height, set the alignment mode of the content in the component. Text('align').fontSize(9).fontColor(0xCCCCCC).width('90%') Text('top start') .align(Alignment.TopStart) @@ -39,6 +39,14 @@ struct PositionExample { .fontSize(16) .backgroundColor(0xFFE4C4) + Text('Bottom end') + .align(Alignment.BottomEnd) + .height(50) + .width('90%') + .fontSize(16) + .backgroundColor(0xFFE4C4) + + // To arrange the child components from left to right, set direction of the parent container to Direction.Auto or Direction.Ltr, or leave it to the default value. Text('direction').fontSize(9).fontColor(0xCCCCCC).width('90%') Row() { Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3) @@ -47,6 +55,15 @@ struct PositionExample { Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C) } .width('90%') + .direction(Direction.Auto) + // To arrange the child components from right to left, set direction of the parent container to Direction.Rtl. + Row() { + Text('1').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3) + Text('2').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C) + Text('3').height(50).width('25%').fontSize(16).backgroundColor(0xF5DEB3) + Text('4').height(50).width('25%').fontSize(16).backgroundColor(0xD2B48C) + } + .width('90%') .direction(Direction.Rtl) } } @@ -55,54 +72,75 @@ struct PositionExample { } ``` -![en-us_image_0000001212218456](figures/en-us_image_0000001212218456.gif) +![align.png](figures/align.png) +### Example 2 ```ts // xxx.ets @Entry @Component struct PositionExample2 { - build() { Column({ space: 20 }) { + // Set the offset of the component's upper left corner relative to the parent component's upper left corner. Text('position').fontSize(12).fontColor(0xCCCCCC).width('90%') - Row({ space: 20 }) { - Text('1').size({ width: '45%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }) .fontSize(16) - Text('2 position(25, 15)') - .size({ width: '60%', height: '30' }).backgroundColor(0xbbb2cb).border({ width: 1 }) - .fontSize(16).align(Alignment.Start) - .position({ x: 25, y: 15 }) + Row() { + Text('1').size({ width: '30%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) + Text('2 position(30, 10)') + .size({ width: '60%', height: '30' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .fontSize(16) + .align(Alignment.Start) + .position({ x: 30, y: 10 }) Text('3').size({ width: '45%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) Text('4 position(50%, 70%)') - .size({ width: '50%', height: '50' }).backgroundColor(0xbbb2cb).border({ width: 1 }).fontSize(16) + .size({ width: '50%', height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .fontSize(16) .position({ x: '50%', y: '70%' }) }.width('90%').height(100).border({ width: 1, style: BorderStyle.Dashed }) + // Offset relative to the start point. x indicates the horizontal distance between the end point and the start point. If the value of x is greater than 0, the component is offset to the left. Otherwise, the component is offset to the right. + // y indicates the vertical distance between the end point and the start point. If the value of y is greater than 0, the component is offset to the top. Otherwise, the component is offset to the bottom. Text('markAnchor').fontSize(12).fontColor(0xCCCCCC).width('90%') Stack({ alignContent: Alignment.TopStart }) { Row() .size({ width: '100', height: '100' }) .backgroundColor(0xdeb887) - Image($r('app.media.ic_health_heart')) + Text('text') .size({ width: 25, height: 25 }) + .backgroundColor(Color.Green) .markAnchor({ x: 25, y: 25 }) - Image($r('app.media.ic_health_heart')) + Text('text') .size({ width: 25, height: 25 }) - .markAnchor({ x: 25, y: 25 }) - .position({ x: '100%', y: '100%' }) + .backgroundColor(Color.Green) + .markAnchor({ x: -100, y: -25 }) + Text('text') + .size({ width: 25, height: 25 }) + .backgroundColor(Color.Green) + .markAnchor({ x: 25, y: -25 }) }.margin({ top: 25 }).border({ width: 1, style: BorderStyle.Dashed }) + // Offset of the component relative to itself. If the value of x is greater than 0, the component is offset to the right. Otherwise, the component is offset to the left. If the value of y is greater than 0, the component is offset to the bottom. Otherwise, the component is offset to the top. Text('offset').fontSize(12).fontColor(0xCCCCCC).width('90%') Row() { Text('1').size({ width: '15%', height: '50' }).backgroundColor(0xdeb887).border({ width: 1 }).fontSize(16) - Text('2\noffset(15, 15)') - .size({ width: 120, height: '50' }).backgroundColor(0xbbb2cb).border({ width: 1 }) - .fontSize(16).align(Alignment.Start) - .offset({ x: 15, y: 15 }) + Text('2 offset(15, 30)') + .size({ width: 120, height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .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\noffset(-10%, 20%)') - .size({ width: 150, height: '50' }) .backgroundColor(0xbbb2cb).border({ width: 1 }).fontSize(16) - .offset({ x: '-10%', y: '20%' }) + Text('4 offset(-10%, 20%)') + .size({ width: 100, height: '50' }) + .backgroundColor(0xbbb2cb) + .border({ width: 1 }) + .fontSize(16) + .offset({ x: '-5%', y: '20%' }) }.width('90%').height(100).border({ width: 1, style: BorderStyle.Dashed }) } .width('100%').margin({ top: 25 }) @@ -110,4 +148,4 @@ struct PositionExample2 { } ``` -![en-us_image_0000001256858409](figures/en-us_image_0000001256858409.gif) +![position.png](figures/position.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md index 6292412ddfe94444dd8756fef77b0c1df664eecf..db1e33a8ed8e723c626e81fc4bbb6cd9915948fe 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-opacity.md @@ -12,7 +12,7 @@ You can set the opacity of a component. | Name | Type | Description | | ------- | ---------------------------------------- | ---------------------------------------- | -| opacity | number \| [Resource](ts-types.md#resource) | Opacity of a component. The value ranges from **0** to **1**. The value **1** means opaque, and **0** means completely transparent.
Default value: **1**| +| opacity | number \| [Resource](ts-types.md#resource) | Opacity of the component. The value ranges from 0 to 1. The value **1** means opaque, and **0** means completely transparent. When being completely transparent, the component is hidden, but still takes up space in the layout.
**NOTE**
A child component can inherit this attribute of its parent component. Default value: **1**| ## Example @@ -30,6 +30,10 @@ struct OpacityExample { Text().width('90%').height(50).opacity(0.7).backgroundColor(0xAFEEEE) Text('opacity(0.4)').fontSize(9).width('90%').fontColor(0xCCCCCC) Text().width('90%').height(50).opacity(0.4).backgroundColor(0xAFEEEE) + Text('opacity(0.1)').fontSize(9).width('90%').fontColor(0xCCCCCC) + Text().width('90%').height(50).opacity(0.1).backgroundColor(0xAFEEEE) + Text('opacity(0)').fontSize(9).width('90%').fontColor(0xCCCCCC) + Text().width('90%').height(50).opacity(0).backgroundColor(0xAFEEEE) } .width('100%') .padding({ top: 5 }) @@ -37,4 +41,4 @@ struct OpacityExample { } ``` -![en-us_image_0000001256858385](figures/en-us_image_0000001256858385.gif) +![opacity.png](figures/opacity.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md index 0f34f7464c8826adece2aad5c1ccace799786cd3..4bb23b9f11f8f7ab4aa187fedaca3ab37716a461 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-overlay.md @@ -8,10 +8,9 @@ You can set overlay text for a component. ## Attributes -| Name | Type | Description | -| ------- | ----------------------------- | ------------------------- | -| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment),
offset?: {
x?: number,
y?: number
}
} | Overlay added to the component. The overlay has the same layout as the component.
Default value:
{
align: Alignment.Center,
offset: {0, 0}
} | - +| Name| Type| Default Value| Description| +| -------- | -------- | -------- | -------- | +| overlay | value: string,
options?: {
align?: [Alignment](ts-appendix-enums.md#alignment),
offset?: {x?: number, y?: number}
} | {
align: Alignment.Center,
offset: {0, 0}
} | Overlay added to the component.
**value**: mask text.
**options**: text positioning. **align** indicates the location of the text relative to the component. **[offset](ts-universal-attributes-location.md)** indicates the offset of the text relative to the upper left corner of itself. By default, the text is in the upper left corner of the component.
If both **align** and **offset** are set, the text is first positioned relative to the component, and then offset relative to the upper left corner of itself.| ## Example @@ -28,7 +27,10 @@ struct OverlayExample { Column() { Image($r('app.media.img')) .width(240).height(240) - .overlay("Winter is a beautiful season, especially when it snows.", { align: Alignment.Bottom, offset: { x: 0, y: -15 } }) + .overlay("Winter is a beautiful season, especially when it snows.", { + align: Alignment.Bottom, + offset: { x: 0, y: -15 } + }) }.border({ color: Color.Black, width: 2 }) }.width('100%') }.padding({ top: 20 }) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md index b24dfab3a25c47e323201e70b7261f4db2408015..9710a01a6870933d3b832ce589e192fe0cbcb87d 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-popup.md @@ -1,6 +1,6 @@ # Popup Control -The popup attribute defines the popup displayed when a component is clicked. +You can bind a popup to a component, specifying its content, interaction logic, and display status. > **NOTE** > @@ -12,7 +12,7 @@ The popup attribute defines the popup displayed when a component is clicked. | Name | Type | Description | | ---------- | ------------------------------------- | --------------------------------------- | -| bindPopup | show: boolean,
popup: PopupOptions \| CustomPopupOptions8+ | Settings of the popup bound to the component.
**show**: whether to display the popup on the creation page by default. The default value is **false**.
**popup**: parameters of the popup.| +| bindPopup | show: boolean,
popup: [PopupOptions](#popupoptions) \| [CustomPopupOptions](#custompopupoptions8)8+ | Binds a popup to the component.
**show**: whether to show the popup. The default value is **false**, indicating that the popup is hidden.
**popup**: parameters of the popup.| ## PopupOptions @@ -21,6 +21,7 @@ The popup attribute defines the popup displayed when a component is clicked. | message | string | Yes | Content of the popup message. | | placementOnTop | boolean | No | Whether to display the popup above the component. The default value is **false**. | | arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. | +| showInSubWindow9+ | boolean | No | Whether to show the popup in the subwindow. The default value is **false**.| | primaryButton | {
value: string,
action: () => void
} | No | Primary button.
**value**: text of the primary button in the popup.
**action**: callback for clicking the primary button.| | secondaryButton | {
value: string,
action: () => void
} | No | Secondary button.
**value**: text of the secondary button in the popup.
**action**: callback for clicking the secondary button.| | onStateChange | (event: { isVisible: boolean }) => void | No | Callback for the popup status change event. The parameter **isVisible** indicates whether the popup is visible. | @@ -29,9 +30,10 @@ The popup attribute defines the popup displayed when a component is clicked. | Name | Type | Mandatory | Description | | -------------------------| ------------------------- | ---- | ---------------------------------------------------- | -| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Builder of the popup content. | +| builder | [CustomBuilder](ts-types.md#custombuilder8) | Yes | Popup builder. | | placement | [Placement](ts-appendix-enums.md#placement8) | No | Preferred position of the popup. If the set position is insufficient for holding the popup, it will be automatically adjusted.
Default value: **Placement.Bottom** | | arrowOffset9+ | [Length](ts-types.md#length) | No | Offset of the popup arrow in the popup window. When residing above or below the popup, the arrow is offset to the left by default. When residing on the left or right side of the popup, the arrow is offset to the top by default. | +| showInSubWindow9+ | boolean | No | Whether to show the popup in the subwindow. The default value is **false**.| | maskColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup mask. | | popupColor | [ResourceColor](ts-types.md#resourcecolor) | No | Color of the popup. | | enableArrow | boolean | No | Whether to display an arrow.
Since API version 9, if the location set for the popup arrow is not large enough, the arrow will not be displayed. For example, if **placement** is set to **Left** and the popup height is less than the arrow width (32 vp), the arrow will not be displayed.
Default value: **true**| @@ -40,81 +42,80 @@ The popup attribute defines the popup displayed when a component is clicked. ## Example - ```ts // xxx.ets @Entry @Component struct PopupExample { - @State noHandlePopup: boolean = false @State handlePopup: boolean = false @State customPopup: boolean = false + // Popup builder @Builder popupBuilder() { Row({ space: 2 }) { - Image('/resource/ic_public_thumbsup.svg').width(24).height(24).margin({ left: -5 }) + Image($r("app.media.image")).width(24).height(24).margin({ left: -5 }) Text('Custom Popup').fontSize(10) - }.width(100).height(50).backgroundColor(Color.White) + }.width(100).height(50).padding(5) } build() { Flex({ direction: FlexDirection.Column }) { - Button('no handle popup') - .onClick(() => { - this.noHandlePopup = !this.noHandlePopup - }) - .bindPopup(this.noHandlePopup, { - message: 'content1 content1', - placementOnTop: false, - onStateChange: (e) => { - console.info(e.isVisible.toString()) - if (!e.isVisible) { - this.noHandlePopup = false - } - } - }) - .position({ x: 100, y: 50 }) - - Button('with handle popup') + // PopupOptions for setting the popup + Button('PopupOptions') .onClick(() => { this.handlePopup = !this.handlePopup }) .bindPopup(this.handlePopup, { - message: 'content2 content2', + message: 'This is a popup with PopupOptions', placementOnTop: true, + showInSubWindow:false, primaryButton: { - value: 'ok', + value: 'confirm', action: () => { this.handlePopup = !this.handlePopup - console.info('secondaryButton click') + console.info('confirm Button click') + } + }, + // Secondary button + secondaryButton: { + value: 'cancel', + action: () => { + this.handlePopup = !this.handlePopup; + console.info('cancel Button click') } }, onStateChange: (e) => { console.info(e.isVisible.toString()) + if (!e.isVisible) { + this.handlePopup = false + } } }) - .position({ x: 100, y: 200 }) + .position({ x: 100, y: 50 }) + - Button('custom popup') + // CustomPopupOptions for setting the popup + Button('CustomPopupOptions') .onClick(() => { this.customPopup = !this.customPopup }) .bindPopup(this.customPopup, { builder: this.popupBuilder, - placement: Placement.Bottom, + placement: Placement.Top, maskColor: 0x33000000, - popupColor: Color.White, + popupColor: Color.Yellow, enableArrow: true, + showInSubWindow: false, onStateChange: (e) => { if (!e.isVisible) { this.customPopup = false } } }) - .position({ x: 100, y: 350 }) + .position({ x: 80, y: 200 }) }.width('100%').padding({ top: 5 }) } } ``` -![en-us_image_0000001212058458](figures/en-us_image_0000001212058458.gif) +![figures/popup.gif](figures/popup.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md index de23ed8824f18e44b59d70dd282794193df31b18..87e47dd06c71cb138311fa221e658d3451d9b2ef 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-size.md @@ -1,6 +1,6 @@ # Size -The size attributes are used to set the width, height, padding, and margin of a component. +The size attributes set the width, height, and margin of a component. > **NOTE** > @@ -16,9 +16,9 @@ The size attributes are used to set the width, height, padding, and margin of a | height | [Length](ts-types.md#length) | Height of the component. By default, the height required to fully hold the component content is used. If the height of the component is greater than that of the parent container, the range of the parent container is drawn. | | size | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} | Size of the component. | | padding | [Padding](ts-types.md#padding) \| [Length](ts-types.md#length) | Padding of the component.
When the parameter is of the **Length** type, the four paddings take effect.
Default value: **0**
When **padding** is set to a percentage, the width of the parent container is used as the basic value.| -| margin | [Margin](ts-types.md#margin)) \| [Length](ts-types.md#length) | Margin of the component.
When the parameter is of the **Length** type, the four margins take effect.
Default value: **0**
When **margin** is set to a percentage, the width of the parent container is used as the basic value.| +| margin | [Margin](ts-types.md#margin) \| [Length](ts-types.md#length) | Margin of the component.
When the parameter is of the **Length** type, the four margins take effect.
Default value: **0**
When **margin** is set to a percentage, the width of the parent container is used as the basic value.| | constraintSize | {
minWidth?: [Length](ts-types.md#length),
maxWidth?: [Length](ts-types.md#length),
minHeight?: [Length](ts-types.md#length),
maxHeight?: [Length](ts-types.md#length)
} | Constraint size of the component, which is used to limit the size range during component layout. **constraintSize** takes precedence over **width** and **height**.
Default value:
{
minWidth: 0,
maxWidth: Infinity,
minHeight: 0,
maxHeight: Infinity
} | -| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** layouts.
Default value: **0**| +| layoutWeight | number \| string | Weight of the component during layout. When the container size is determined, the container space is allocated along the main axis among the component and sibling components based on the layout weight, and the component size setting is ignored.
**NOTE**
This attribute is valid only for the **\**, **\**, and **\** layouts.| ## Example @@ -31,30 +31,41 @@ struct SizeExample { build() { Column({ space: 10 }) { Text('margin and padding:').fontSize(12).fontColor(0xCCCCCC).width('90%') - // The width is 80, the height is 80, the padding is 20, and the margin is 20. Row() { + // Width: 80; height: 80; margin: 20 (blue area); padding: 10 (white area) Row() { - Row().size({ width: '100%', height: '100%' }).backgroundColor(0xAFEEEE) - }.width(80).height(80).padding(20).margin(20).backgroundColor(0xFDF5E6) - }.backgroundColor(0xFFA500) + Row().size({ width: '100%', height: '100%' }).backgroundColor(Color.Yellow) + } + .width(80) + .height(80) + .padding(10) + .margin(20) + .backgroundColor(Color.White) + }.backgroundColor(Color.Blue) + + Text('constraintSize').fontSize(12).fontColor(0xCCCCCC).width('90%') + Text('this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text.this is a Text') + .width('90%') + .constraintSize({ maxWidth: 200 }) Text('layoutWeight').fontSize(12).fontColor(0xCCCCCC).width('90%') - // When the container size is determined, the layout of the component and sibling components is allocated based on the weight along the main axis. The component size setting is ignored. + // When the container size is determined, the component occupies the space along the main axis based on the layout weight, and the component size setting is ignored. Row() { - // Weight 1 + // Weight 1: The component occupies 1/3 of the remaining space along the main axis. Text('layoutWeight(1)') .size({ width: '30%', height: 110 }).backgroundColor(0xFFEFD5).textAlign(TextAlign.Center) .layoutWeight(1) - // Weight 2 + // Weight 2: The component occupies 2/3 of the remaining space along the main axis. Text('layoutWeight(2)') .size({ width: '30%', height: 110 }).backgroundColor(0xF5DEB3).textAlign(TextAlign.Center) .layoutWeight(2) - // The default weight is 0. + // If layoutWeight is not set, the component is rendered based on its own size setting. Text('no layoutWeight') .size({ width: '30%', height: 110 }).backgroundColor(0xD2B48C).textAlign(TextAlign.Center) }.size({ width: '90%', height: 140 }).backgroundColor(0xAFEEEE) }.width('100%').margin({ top: 5 }) - }} + } +} ``` -![en-us_image_0000001257138367](figures/en-us_image_0000001257138367.gif) +![size](figures/size.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index f7937b97bffbb5ab4f596940910a22e9922b4040..8330e79474aef2c523fadaf3677323c724e3570a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -1,23 +1,23 @@ # Text Style - -The text style attributes are used to set the style for text in a component. +The text style attributes set the style for text in a component. > **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. + ## Attributes | Name | Type | Description | | -----------| ---------------------------------------- | ------------------------------------ | | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Font color. | -| fontSize | Length \| [Resource](ts-types.md#resource) | Font size. If the value is of the number type, the unit fp is used. | +| fontSize | [Length](ts-types.md#length) | Font size. If the value is of the number type, the unit fp is used. The default font size is 10. This attribute cannot be set in percentage. | | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.
Default value: **FontStyle.Normal** | -| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal** | -| fontFamily | string \| [Resource](ts-types.md#resource) | Font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.| +| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in FontWeight.
Default value: **FontWeight.Normal** | +| fontFamily | string \| [Resource](ts-types.md#resource) | Font family.
Default value: **'HarmonyOS Sans'**
Currently, only the default font is supported. | ## Example @@ -30,40 +30,38 @@ struct TextStyleExample { build() { Column({ space: 5 }) { Text('default text') - - Text('text font color red') - .fontColor(Color.Red) - - Text('text font size 20') - .fontSize(20) - - Text('text font style Italic') - .fontStyle(FontStyle.Italic) - - Text('text fontWeight bold') - .fontWeight(700) - - Text('text fontFamily sans-serif') - .fontFamily('sans-serif') - - Text('red 20 Italic bold cursive text') + Divider() + + Text('text font color red').fontColor(Color.Red) + Divider() + + Text('text font default') + Text('text font size 10').fontSize(10) + Text('text font size 10fp').fontSize('10fp') + Text('text font size 20').fontSize(20) + Divider() + + Text('text font style Italic').fontStyle(FontStyle.Italic) + Divider() + + Text('text fontWeight bold').fontWeight(700) + Text('text fontWeight lighter').fontWeight(FontWeight.Lighter) + Divider() + + Text('red 20 Italic bold text') .fontColor(Color.Red) .fontSize(20) .fontStyle(FontStyle.Italic) - .fontWeight(700) - .fontFamily('cursive') - .textAlign(TextAlign.Center) - .width('90%') - - Text('Orange 18 Normal source-sans-pro text') + .fontWeight(FontWeight.Bold) + Divider() + + Text('Orange 18 Normal text') .fontColor(Color.Orange) .fontSize(18) .fontStyle(FontStyle.Normal) - .fontWeight(400) - .fontFamily('source-sans-pro,cursive,sans-serif') }.width('100%') } } ``` -![en-us_image_0000001256978333](figures/en-us_image_0000001256978333.png) +![textstyle](figures/textstyle.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md index 40b83f1cb3f00f756e73b6c95f990c6fced9a272..82d42267a5e9b81c29063ad232c5212bbbf02574 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-visibility.md @@ -10,7 +10,7 @@ The visibility attribute controls whether a component is visible. | Name | Type | Description | | ---------- | ---------------------------- | ------------------------------------------ | -| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is hidden, it needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../ui/ts-rending-control-syntax-if-else.md) instead under scenarios where consistently high performance is required.
Default value: **Visibility.Visible**| +| visibility | [Visibility](ts-appendix-enums.md#visibility) | Whether the component is visible. Note that even if a component is invisible, it still needs to be re-created when the page is refreshed. Therefore, you are advised to use [conditional rendering](../../quick-start/arkts-rendering-control.md#conditional-rendering) instead under scenarios where consistently high performance is required.
Default value: **Visibility.Visible**| ## Example @@ -23,20 +23,21 @@ struct VisibilityExample { build() { Column() { Column() { - Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC) - Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE) - - Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC) // The component is hidden, and no placeholder is used. + Text('None').fontSize(9).width('90%').fontColor(0xCCCCCC) Row().visibility(Visibility.None).width('90%').height(80).backgroundColor(0xAFEEEE) - Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC) // The component is hidden, and a placeholder is used for it in the layout. + Text('Hidden').fontSize(9).width('90%').fontColor(0xCCCCCC) Row().visibility(Visibility.Hidden).width('90%').height(80).backgroundColor(0xAFEEEE) + + // The component is visiable, which is the default display mode. + Text('Visible').fontSize(9).width('90%').fontColor(0xCCCCCC) + Row().visibility(Visibility.Visible).width('90%').height(80).backgroundColor(0xAFEEEE) }.width('90%').border({ width: 1 }) }.width('100%').margin({ top: 5 }) } } ``` -![en-us_image_0000001257058421](figures/en-us_image_0000001257058421.gif) +![visibility.png](figures/visibility.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md index 627f185a148369e77b8cce138b2d62723ddcf584..24be504eef9a302db845b10a0f1e9f082d6d6efd 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-z-order.md @@ -25,20 +25,24 @@ struct ZIndexExample { build() { Column() { Stack() { - // Components are stacked. By default, the component defined later is on the top. - Text('first child, zIndex(2)') - .size({width: '40%', height: '30%'}).backgroundColor(0xbbb2cb) + // Components are stacked. By default, the component defined later is on the top. A component with a larger zIndex value is displayed before one with a smaller zIndex value. + Text('1, zIndex(2)') + .size({ width: '40%', height: '30%' }).backgroundColor(0xbbb2cb) .zIndex(2) - // The default value is 0. - Text('second child, default zIndex(0)') - .size({width: '90%', height: '80%'}).backgroundColor(0xd2cab3).align(Alignment.TopStart) - Text('third child, zIndex(1)') - .size({width: '70%', height: '50%'}).backgroundColor(0xc1cbac).align(Alignment.TopStart) + Text('2, default zIndex(1)') + .size({ width: '70%', height: '50%' }).backgroundColor(0xd2cab3).align(Alignment.TopStart) .zIndex(1) + Text('3, zIndex(0)') + .size({ width: '90%', height: '80%' }).backgroundColor(0xc1cbac).align(Alignment.TopStart) }.width('100%').height(200) }.width('100%').height(200) } } ``` +Display of child components in the **\** component when **zIndex** is not set -![en-us_image_0000001257058443](figures/en-us_image_0000001257058443.png) +![nozindex.png](figures/nozindex.png) + +Display of child components in the **\** component when **zIndex** is set + +![zindex.png](figures/zindex.png) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md b/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md index df4ee9686b18f08139ef6aa814fdda50eea2a015..1d34a1ae15448105d23e77989c031daf50ace78e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-component-visible-area-change-event.md @@ -1,6 +1,6 @@ # Visible Area Change Event -The visible area change event of a component refers to the change in the visual portion of a component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing. +The visible area change event of a component refers to the change in the visual portion of the component on the screen. It can be used to determine whether the component is completely or partially displayed on the screen. It is usually applicable to scenarios such as advertisement exposure tracing. > **NOTE** > @@ -23,8 +23,8 @@ The visible area change event of a component refers to the change in the visual struct ScrollExample { scroller: Scroller = new Scroller() private arr: number[] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] - @State testTextStr: string = "test" - @State testRowStr: string = "test" + @State testTextStr: string = 'test' + @State testRowStr: string = 'test' build() { Column() { @@ -46,22 +46,22 @@ struct ScrollExample { .height(200) .margin({ top: 50, bottom: 20 }) .backgroundColor(Color.Green) - // Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen. + // Set ratios to [0.0, 1.0] to invoke the callback when the component is fully visible or invisible on screen. .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { - console.info("Test Text isVisible: " + isVisible + ", currentRatio:" + currentRatio) + console.info('Test Text isVisible: ' + isVisible + ', currentRatio:' + currentRatio) if (isVisible && currentRatio >= 1.0) { - console.info("Test Text is fully visible. currentRatio:" + currentRatio) - this.testTextStr = "Test Text is fully visible" + console.info('Test Text is fully visible. currentRatio:' + currentRatio) + this.testTextStr = 'Test Text is fully visible' } if (!isVisible && currentRatio <= 0.0) { - console.info("Test Text is completely invisible.") - this.testTextStr = "Test Text is completely invisible" + console.info('Test Text is completely invisible.') + this.testTextStr = 'Test Text is completely invisible' } }) Row() { - Text("Test Row Visible Change") + Text('Test Row Visible Change') .fontSize(20) .margin({ bottom: 20 }) @@ -69,15 +69,15 @@ struct ScrollExample { .height(200) .backgroundColor(Color.Yellow) .onVisibleAreaChange([0.0, 1.0], (isVisible: boolean, currentRatio: number) => { - console.info("Test Row isVisible:" + isVisible + ", currentRatio:" + currentRatio) + console.info('Test Row isVisible:' + isVisible + ', currentRatio:' + currentRatio) if (isVisible && currentRatio >= 1.0) { - console.info("Test Row is fully visible.") - this.testRowStr = "Test Row is fully visible" + console.info('Test Row is fully visible.') + this.testRowStr = 'Test Row is fully visible' } if (!isVisible && currentRatio <= 0.0) { - console.info("Test Row is is completely invisible.") - this.testRowStr = "Test Row is is completely invisible" + console.info('Test Row is is completely invisible.') + this.testRowStr = 'Test Row is is completely invisible' } }) diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md index 31a0c9f822ba7485c1df1982a9e5dc35b210a823..226a6b6030f7050ddff13e6ccc37ddd3663afc4e 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-click.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-click.md @@ -11,7 +11,7 @@ A click event is triggered when a component is clicked. | Name | Bubbling Supported| Description | | ---------------------------------------- | ---- | --------------------------------- | -| onClick(event: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about the event parameters, see **ClickEvent**.| +| onClick(event: (event?: ClickEvent) => void) | No | Called when a click event occurs. For details about **event**, see **ClickEvent**.| ## ClickEvent | Name | Type | Description | @@ -20,8 +20,9 @@ A click event is triggered when a component is clicked. | screenY | number | Y coordinate of the click relative to the upper left corner of the application window. | | x | number | X coordinate of the click relative to the upper left corner of the component being clicked. | | y | number | Y coordinate of the click relative to the upper left corner of the component being clicked. | -| target8+ | [EventTarget](#eventtarget8) | Target element that is clicked. | -| timestamp | number | Timestamp of the event. It is interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| +| timestamp8+ | number | Timestamp of the event. It is the interval between the time when the event is triggered and the time when the system starts, in nanoseconds.| +| target8+ | [EventTarget](#eventtarget8) | Display area of the object that triggers the event.| +| source8+ | [SourceType](ts-gesture-settings.md#sourcetype)| Event input device.| ## EventTarget8+ @@ -42,15 +43,25 @@ struct ClickExample { build() { Column() { - Button('Click').backgroundColor(0x2788D9).width(100).height(40) - .onClick((event: ClickEvent) => { - console.info(this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY - + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:(' - + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:' - + event.target.area.width + '\n height:' + event.target.area.height) - }) - Text(this.text).padding(15) - }.height(350).width('100%').padding(10) + Row({ space: 20 }) { + Button('Click').width(100).height(40) + .onClick((event: ClickEvent) => { + this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY + + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:(' + + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:' + + event.target.area.width + '\n height:' + event.target.area.height + '\ntimestamp' + event.timestamp; + }) + Button('Click').width(200).height(50) + .onClick((event: ClickEvent) => { + this.text = 'Click Point:' + '\n screenX:' + event.screenX + '\n screenY:' + event.screenY + + '\n x:' + event.x + '\n y:' + event.y + '\ntarget:' + '\n component globalPos:(' + + event.target.area.globalPosition.x + ',' + event.target.area.globalPosition.y + ')\n width:' + + event.target.area.width + '\n height:' + event.target.area.height + '\ntimestamp' + event.timestamp; + }) + }.margin(20) + + Text(this.text).margin(15) + }.width('100%') } } ``` diff --git a/en/application-dev/reference/errorcodes/errorcode-device-manager.md b/en/application-dev/reference/errorcodes/errorcode-device-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..3e0459cebcb89d3d501bc331f9526320cd7d72e6 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-device-manager.md @@ -0,0 +1,71 @@ +# Device Management Error Codes + +## 11600101 Service Invoking Exception + +**Error Message** + +Failed to execute the function. + +**Possible Causes** + +An error occurred during internal invocation. + +**Procedure** + +Call the API again. + +## 11600102 Failed to Obtain the Service + +**Error Message** + +Failed to obtain the service. + +**Possible Causes** + +The service is not started or fails to start. + +**Procedure** + +Check whether the service is started normally and obtain the service again. + +## 11600103 Authentication Unavailable + +**Error Message** + +Authentication invalid. + +**Possible Causes** + +The last authentication service is still in progress. + +**Procedure** + +Wait until the last authentication service is complete and call the authentication API again. + +## 11600104 Discovery Unavailable + +**Error Message** + +Discovery invalid. + +**Possible Causes** + +The last discovery service is still in progress. + +**Procedure** + +Wait until the last discovery service is complete and call the discovery API again. + +## 11600105 Publish Unavailable + +**Error Message** + +Publish invalid. + +**Possible Causes** + +The last publish service is still in progress. + +**Procedure** + +Wait until the last publish service is complete and call the publish API again. diff --git a/en/application-dev/reference/errorcodes/errorcode-display.md b/en/application-dev/reference/errorcodes/errorcode-display.md new file mode 100644 index 0000000000000000000000000000000000000000..f86b0b10736c407cefb288e317288c66a9fd5a07 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-display.md @@ -0,0 +1,43 @@ +# Display Error Codes + +## 1400001 Invalid Display or Screen +**Error Message** +Invalid display or screen. + +**Description** +This error code is reported when an invalid display, including a virtual screen, is operated. + +**Possible Causes** +1. The virtual screen has not been created. +2. The virtual screen has been destroyed. + +**Procedure** +1. Before operating the virtual screen, check whether the virtual screen has been created. +2. Check whether the virtual screen has been destroyed. + +## 1400002 Unauthorized Operation +**Error Message** +Unauthorized operation. + +**Description** +This error code is reported when the API does not have the required permissions to operate an object. + +**Possible Causes** +The virtual screen object of another process is operated. + +**Procedure** +Check whether unauthorized operations are performed on the object of another process. If yes, delete the operations. + +## 1400003 Abnormal Display Manager Service +**Error Message** +This display manager service works abnormally. + +**Description** +This error code is reported when the display manager service is abnormal. + +**Possible Causes** +1. The display manager service is not started normally. +2. The bottom-layer graphics synthesis and rendering are abnormal. + +**Procedure** +Try again later or restart the device. diff --git a/en/application-dev/reference/errorcodes/errorcode-promptAction.md b/en/application-dev/reference/errorcodes/errorcode-promptAction.md new file mode 100644 index 0000000000000000000000000000000000000000..7518de5a3f5a1202ece256f2c231039fa0b49542 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-promptAction.md @@ -0,0 +1,19 @@ +# promptAction Error Codes + +## 100001 Internal Error + +**Error Message** + +Internal error. + +**Description** + +This error code is reported when an internal error that cannot be rectified by developers occurs. The internal error type is included in the error information. + +**Possible Causes** + +The operation for obtaining the rendering engine or parsing parameters fails. + +**Procedure** + +NA diff --git a/en/application-dev/reference/errorcodes/errorcode-router.md b/en/application-dev/reference/errorcodes/errorcode-router.md new file mode 100644 index 0000000000000000000000000000000000000000..0f99a215923ac8bfe1aee4ff3aac64ded07fd6ea --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-router.md @@ -0,0 +1,73 @@ +# Router Error Codes + +## 100001 Internal Error + +**Error Message** + +Internal error. + +**Description** + +This error code is reported when an internal error that cannot be rectified by developers occurs. The internal error type is included in the error information. + +**Possible Causes** + +The operation for obtaining the rendering engine or parsing parameters fails. + +**Procedure** + +NA + +## 100002 Incorrect URI + +**Error Message** + +Uri error. The uri of router is not exist. + +**Description** + +This error code is reported when the URI of the page to redirect is incorrect or does not exist. + +**Possible Causes** + +The entered URI is incorrect or does not exist. + +**Procedure** + +Ensure that the URI is correct. + +## 100003 Too Many Pages Are Pushed into the Page Stack + +**Error Message** + +Page stack error. The pages are pushed too much. + +**Description** + +This error code is reported when more than 32 pages are pushed into the page stack. + +**Possible Causes** + +Too many pages are pushed. + +**Procedure** + +Delete unnecessary or invalid pages. + +## 200002 Incorrect URI + +**Error Message** + +Uri error. The uri of router is not exist. + +**Description** + +This error code is reported when the URI of the page to be used for replacement is incorrect or does not exist. + +**Possible Causes** + +The entered URI is incorrect or does not exist. + +**Procedure** + +Ensure that the URI is correct. diff --git a/en/application-dev/reference/errorcodes/errorcode-sensor.md b/en/application-dev/reference/errorcodes/errorcode-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..571156ec00328b0ba564cd6174e6fb81aa5154b1 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-sensor.md @@ -0,0 +1,20 @@ +# Sensor Error Codes + +## 14500101 Service exception. + +**Error Message** + +Service exception. + +**Description** + +This error code is reported if the HDI service is abnormal when the **on**, **once**, or **off** interface of the sensor module is called. + +**Possible Causes** + +The HDI service is abnormal. + +**Procedure** + +1. Retry the operation at a specified interval (for example, 1s) or at an exponential increase interval. +2. If the operation fails for three consecutive times, stop the retry. You can also attempt to obtain the sensor list to check for device availability. diff --git a/en/application-dev/reference/errorcodes/errorcode-vibrator.md b/en/application-dev/reference/errorcodes/errorcode-vibrator.md new file mode 100644 index 0000000000000000000000000000000000000000..f5dc329c1e96d945f76c7625b365a53fe50477b4 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-vibrator.md @@ -0,0 +1,21 @@ +# Vibrator Error Codes + +## 14600101 Device operation failed. + +**Error Message** + +Device operation failed. + +**Description** + +This error code is reported if the HDI service is abnormal or the device is occupied when the **startVibration** interface of the vibrator module is called. + +**Possible Causes** + +1. The HDI service is abnormal. +2. The device is occupied. + +**Procedure** + +1. Retry the operation at a specified interval or at an exponential increase interval. If the operation fails for three consecutive times, stop the retry. You can also obtain the vibrator list to check for device availability. +2. Set a higher priority for the vibrator. diff --git a/en/application-dev/reference/errorcodes/errorcode-window.md b/en/application-dev/reference/errorcodes/errorcode-window.md new file mode 100644 index 0000000000000000000000000000000000000000..9e61c92b592c2e155ac6757f8e1dee4a01d762e9 --- /dev/null +++ b/en/application-dev/reference/errorcodes/errorcode-window.md @@ -0,0 +1,79 @@ +# Window Error Codes + +## 1300001 Repeated Operation +**Error Message** +Repeated operation. + +**Description** +This error code is reported when a repeated operation is performed. + +**Possible Causes** +The window to create already exists. + +**Procedure** +Before creating a window, check whether the window already exists. If it already exists, use it directly. + +## 1300002 Abnormal Window State +**Error Message** +This window state is abnormal. + +**Description** +This error code is reported when you operate a window in an abnormal state, for example, a window that has been destroyed. + +**Possible Causes** +The window has been destroyed when being operated. + +**Procedure** +Before operating the window, check whether it exists. + +## 1300003 Abnormal Window Manager Service +**Error Message** +This window manager service works abnormally. + +**Description** +This error code is reported when the window manager service is abnormal. + +**Possible Causes** +The internal services of the window are not started normally. + +**Procedure** +Try again later or restart the device. + +## 1300004 Unauthorized Operation +**Error Message** +Unauthorized operation. + +**Description** +This error code is reported when the API does not have the required permissions to operate an object. + +**Possible Causes** +The window object of another process is operated. + +**Procedure** +Check whether unauthorized operations are performed on the object of another process. If yes, delete the operations. + +## 1300005 Abnormal Window Stage +**Error Message** +This window stage is abnormal. + +**Description** +This error code is reported when you operate a window stage in the abnormal state, for example, a window stage that has been destroyed. + +**Possible Causes** +The window stage has been destroyed when being operated. + +**Procedure** +Before operating a window stage, check whether it exists. + +## 1300006 Abnormal Window Context +**Error Message** +This window context is abnormal. + +**Description** +This error code is reported when you operate a window context in the abnormal state, for example, a window context that has been destroyed. + +**Possible Causes** +The window context has been destroyed when being operated. + +**Procedure** +Before operating the window context, check whether it exists. diff --git a/en/application-dev/reference/syscap-list.md b/en/application-dev/reference/syscap-list.md index c3d849539af2d3bed9fa49cc27cc4c8162527226..51ada8f2b45879986ed8aa932336827cb5b546f1 100644 --- a/en/application-dev/reference/syscap-list.md +++ b/en/application-dev/reference/syscap-list.md @@ -2,7 +2,7 @@ SysCap, short for System Capability, refers to a standalone feature in the operating system. -Before using an API for development, you are advised to read [SysCap](../quick-start/syscap.md) to familiarize yourself with Syscap, and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type. +Before using an API for development, you are advised to familiarize yourself with [SysCap](../quick-start/syscap.md), and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type. ## SystemCapability.ArkUI.ArkUI.Full diff --git a/en/application-dev/security/Readme-EN.md b/en/application-dev/security/Readme-EN.md index c7c051cfe4cc83e8c1b59f8517401e2a4207d59f..4a2fc6dd307645d4bb529ed9a15172c552b2b440 100644 --- a/en/application-dev/security/Readme-EN.md +++ b/en/application-dev/security/Readme-EN.md @@ -2,8 +2,9 @@ - Access Control - [Access Control (Permission) Overview](accesstoken-overview.md) - - [Guide for Requesting Permissions from User](accesstoken-guidelines.md) - - [Application Permission List](permission-list.md) + - [Permission Application Guide](accesstoken-guidelines.md) + - [Permission Verification Guide](permission-verify-guidelines.md) + - [App Permission List](permission-list.md) - User Authentication - [User Authentication Overview](userauth-overview.md) - [User Authentication Development](userauth-guidelines.md) diff --git a/en/application-dev/security/accesstoken-guidelines.md b/en/application-dev/security/accesstoken-guidelines.md index 71caf0a817d7115f6ce59359ff7d979a975f2406..c46c8fc8283271764986d20659276cf9f64aa555 100644 --- a/en/application-dev/security/accesstoken-guidelines.md +++ b/en/application-dev/security/accesstoken-guidelines.md @@ -1,4 +1,4 @@ -# Guide for Requesting Permissions from User +# Permission Application Guide ## When to Use @@ -115,7 +115,7 @@ The permission level of **ohos.permission.PERMISSION2** is **system_basic**, whi In addition to declaring all the permissions in the configuration file, you must declare the permissions whose levels are higher that the app's APL in the app's profile. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). -In this example, declare the permission under the **acls** field: +For example, declare the required permission in the **acls** field: ```json { diff --git a/en/application-dev/security/accesstoken-overview.md b/en/application-dev/security/accesstoken-overview.md index e6e764eb45b63c9d7f09b2636d6ad26eae2d2e7d..9e8aa2a655ecdfbd3ebc4133230f12fb9cf46d67 100644 --- a/en/application-dev/security/accesstoken-overview.md +++ b/en/application-dev/security/accesstoken-overview.md @@ -1,8 +1,8 @@ # Access Control (Permission) Overview -AccessTokenManager (ATM) implements unified app permission management based on access tokens on OpenHarmony. +OpenHarmony AccessTokenManager (ATM) implements unified app permission management based on access tokens. -By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also share their data or functions through interfaces in an explicit manner. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. +By default, apps can access limited system resources. However, in some cases, an app needs to access excess data (including personal data) and functions of the system or another app to implement extended functions. The system or apps must also explicitly share their data or functions through APIs. OpenHarmony uses app permissions to perform access control and prevent improper or malicious use of these data or functions. App permissions are used to protect the following objects: @@ -11,7 +11,7 @@ App permissions are used to protect the following objects: Without the required permissions, an app cannot access or perform operations on the target object. Permissions must be clearly defined for apps. With well-defined app permissions, the system can standardize the behavior of apps and protect user privacy. Before an app accesses the target object, the target object verifies the app's permissions and denies the access if the app does not have required permissions. -Currently, ATM verifies app permissions based on the token identity (Token ID). A token ID identifies an app. The ATM manages app permissions based on the app's token ID. +Currently, ATM verifies app permissions based on the token identity (token ID). A token ID identifies an app. ATM manages app permissions based on the app's token ID. ## Basic Principles for Permission Management @@ -19,37 +19,52 @@ Observe the following principles for permission management: - Provide clear description about the app functions and scenarios for each permission required by the app so that users can clearly know why and when these permissions are required. Do not induce or mislead users' authorization. The permissions on an app must comply with the description provided in the app. - Use the principle of least authority for user permissions. Allow only necessary permissions for service functions. -- When an app is started for the first time, avoid frequently displaying dialog boxes to request permissions. Allow the app to apply for permissions only when it needs to use the corresponding service functions. -- If a user rejects to authorize a permission, the user can still use functions irrelevant to this permission and can register and access the app. +- When an app is started for the first time, avoid frequently displaying dialog boxes to request multiple permissions. Allow the app to apply for the permission only when it needs to use the corresponding service function. +- If a user rejects to grant a permission, the user can still use functions irrelevant to this permission and can register and access the app. - Provide no more message if a user rejects the authorization required by a function. Provide onscreen instructions to direct the user to grant the permission in **Settings** if the user triggers this function again or needs to use this function. -- All the permissions granted to apps must come from the [Permission List](permission-list.md). Custom permissions are not allowed for apps currently. +- All the permissions granted to apps must come from the [App Permission List](permission-list.md). Custom permissions are not allowed for apps currently. -## Permission Workflow +## Permission Workflows -Determine the permissions required for an app to access data or perform an operation. Declare the required permissions in the app installation package. +### Permission Application and Use -Determine whether the required permissions need to be authorized by users. If yes, provide a dialog box dynamically to request user authorization. +Determine the permissions required by an app, and declare the required permissions in the app installation package. -After the user grants permissions to the app, the app can access the data or perform the operation. +Determine whether the required permissions need user authorization. If yes, display a dialog box dynamically to request user authorization. -The figure below shows the permission workflow. +After the user grants the permissions, the app can access the data or perform the operation. + +The figure below illustrates the process. ![](figures/permission-workflow.png) -1. You can refer to the figure below to determine whether an app can apply for a permission. +1. Refer to the figure below to determine whether an app can apply for a permission. ![](figures/permission-application-process.png) 1. See [Permission Levels](#permission-levels) for details about the mapping between the application Ability Privilege Level (APL) and permission level. -2. The permission authorization modes include user_grant (permission granted by the user) and system_grant (permission granted by the system). For details, see [Permission Authorization Modes](#permission-authorization-mode). +2. The permission authorization modes include user_grant (permission granted by the user) and system_grant (permission granted by the system). For details, see [Permission Types](#permission-types). + +3. A low-APL app can have a high-level permission by using the Access Control List (ACL). For details, see [ACL](#acl). + +### Permission Verification +To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. The API can be called only after the permission verification is successful. + +The figure below shows the permission verification process. + +![](figures/permission-verify-process.png) -3. A low-level app can have a high-level permission by using the Access Control List (ACL). For details, see [ACL](#acl). +1: An app permission can be used to control the access to an API that has sensitive data involved or security threats on the core abilities. + +2: Select the permission from the [App Permission List](permission-list.md). For example, if contact information is involved in an API provided by an app, you can use the contact-related permissions to protect the API. + +3: Use **verifyAccessToken()** to check whether the caller has the required permission. For details, see [Permission Verification Guide](permission-verify-guidelines.md). ## Permission Levels -To protect user privacy, ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability. +ATM defines different permission levels based on the sensitivity of the data involved or the security threat of the ability to protect user privacy. ### App APLs @@ -59,21 +74,21 @@ The table below describes the APLs. | APL | Description | | ---------------- | -------------------------------------- | -| system_core | The apps of this level provide core abilities of the operating system.| +| system_core | The apps of this level provide core abilities of the operating system (OS). | | system_basic| The apps of this level provide basic system services. | | Normal | The apps of this level are normal apps. | -By default, apps are of the normal APL. +The default APL of apps is **normal**. -For the app of the system_basic or system_core APL, declare the APL in the **apl** field of **bundle-info** in the app's profile when developing the application installation package. +To set an app's APL to **system_basic** or **system_core**, declare the APL in the **apl** field of **bundle-info** in the app's profile when developing the app's installation package. Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificate or use DevEco Studio to [have your app automatically signed](https://developer.harmonyos.com/en/docs/documentation/doc-guides/ohos-auto-configuring-signature-information-0000001271659465#section161281722111). -> **CAUTION**
The method of declaring the app's APL in its profile applies only to the application or service in debug phase. For a commercial app, apply for a release certificate and profile in the corresponding app market. +> **CAUTION**
The method of changing the app's APL in its profile applies only to the app or service in debug mode. For a commercial app, apply for a release certificate and profile in the corresponding app market. The following is an example. -This example shows only the modification of the **apl** field. Set other fields based on service requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). +This example shows only the modification of the **apl** field. Set other fields based on your requirements. For details about the fields in the profile, see [HarmonyAppProvision Configuration File](../quick-start/app-provision-structure.md). ```json { @@ -100,17 +115,17 @@ The permissions open to apps vary with the permission level. The permission leve - **system_basic** - The system_basic permission allows access to resources related to basic operating system services. The basic services are basic functions provided or preconfigured by the system, such as system setting and identity authentication. Access to these resources may have considerable risks to user privacy and other apps. + The system_basic permission allows access to resources related to basic OS services. The basic services are basic functions provided or preconfigured by the system, such as system settings and identity authentication. Access to these resources may have considerable risks to user privacy and other apps. The permissions of this level are available only to apps of the system_basic or system_core APL. - **system_core** - The system_core permission allows access to core resources of the operating system. These resources are the underlying core services of the system. If these resources are corrupted, the OS cannot run properly. + The system_core permission allows access to core resources of the OS. These resources are underlying core services of the system. If these resources are corrupted, the OS cannot run properly. - The permissions of this type are not open to third-party apps currently. + The system_core permissions are not open to third-party apps currently. -## Permission Authorization Modes +## Permission Types Permissions can be classified into the following types based on the authorization mode: @@ -126,65 +141,70 @@ Permissions can be classified into the following types based on the authorizatio This type of permissions must be declared in the app installation package and authorized by users dynamically during the running of the app. The app has the permission only after user authorization. - For example, in the [Permission List](permission-list.md), the permissions for the microphone and camera are user_grant. The list provides reasons for using the permissions. + For example, in the [App Permission List](permission-list.md), the permissions for microphones and cameras are user_grant. The list provides reasons for using the permissions. The user_grant permission list must also be presented on the details page of the app in the app store. ### Authorization Processes -The process for an app obtaining the required permissions varies depending on the permission authorization mode. +As described in [Permission Workflows](permission-workflows), you need to first apply for the required permissions for the app. + +- Applying for permissions + + You need to [declare the required permissions](accesstoken-guidelines.md#declaring-permissions) in the configuration file. -- For a system_grant permission, you need to [declare the permission](accesstoken-guidelines.md#declaring-permissions) in the configuration file. The permission will be pre-granted when the app is installed. +- Authorizing permissions -- For a user_grant permission, you need to [declare the permission](accesstoken-guidelines.md#declaring-permissions) in the configuration file and trigger user authorization through a dialog box during the running of the app. + - The system_grant permission will be pre-granted when the app is installed. + - For a user_grant permission, you need to trigger user authorization through a dialog box during the running of the app. For details, see [Requesting User Authorization](#requesting-user-authorization). -### Permission Authorization Process (user_grant) +### Requesting User Authorization The procedure is as follows: 1. In the configuration file, declare the permissions required by the app. For details, see [Access Control Development](accesstoken-guidelines.md). -2. Associate the object that requires the permissions in the app with the target permissions. In this way, the user knows the operations to be granted with the specified permissions. +2. Associate the target objects in the app with the related permissions. This allows the users to know the operations that need user authorization. -3. Check whether the user has granted the required permissions to the app when the app is running. If yes, the app can access the data or perform the operation. If the user has not granted the permissions to the app, display a dialog box requesting the user authorization when the app attempts to access the data. +3. Use an API to dynamically trigger a dialog box requesting user authorization when the target object is accessed. The API first checks whether the user has granted the required permissions to the app. If yes, the app can access the data or perform the operation. Otherwise, a dialog box will be displayed to request user authorization. -4. Check the user authorization result. Allow the next step only after the user has granted the permissions to the app. +4. Check the user authorization result. Allow the subsequent operation only after the user has granted the permissions to the app. **Precautions** - Check the app's permission each time before the operation requiring the permission is performed. -- To check whether a user has granted specific permissions to your app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md). -- Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call the API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the requested permission. The user will determine whether to grant the permission based on the running context of the app. +- To check whether a user has granted specific permissions to an app, use the [verifyAccessToken](../reference/apis/js-apis-abilityAccessCtrl.md) method. This method returns [PERMISSION_GRANTED](../reference/apis/js-apis-abilityAccessCtrl.md) or [PERMISSION_DENIED](../reference/apis/js-apis-abilityAccessCtrl.md). For details about the sample code, see [Access Control Development](accesstoken-guidelines.md). +- Users must be able to understand and control the authorization of user_grant permissions. During the running process, the app requiring user authorization must proactively call an API to dynamically request the authorization. Then, the system displays a dialog box asking the user to grant the permission. The user will determine whether to grant the permission based on the running context of the app. - The permission authorized is not permanent, because the user may revoke the authorization at any time. Therefore, even if the user has granted the requested permission to the app, the app must check for the permission before calling the API controlled by this permission. ## ACL As described above, permission levels and app APLs are in one-to-one correspondence. In principle, **an app with a lower APL cannot apply for higher permissions by default**. -The ACL makes low-level apps have high-level permissions. +The ACL makes low-APL apps have high-level permissions. **Example** -The APL of app A is normal. App A needs to have permission B (system_basic level) and permission C (normal level). +The APL of app A is **normal**. App A needs to have permission B (system_basic level) and permission C (normal level). In this case, you can use the ACL to grant permission B to app A. For details, see [Using the ACL](#using-the-acl). -For details about whether a permission can be enabled through the ACL, see the [Permission List](permission-list.md). +For details about whether a permission can be enabled through the ACL, see the [App Permission List](permission-list.md). ### Using the ACL -If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permissions required. +If the permission required by an app has higher level than the app's APL, you can use the ACL to grant the permission required. In addition to the preceding [authorization processes](#authorization-processes), you must declare the ACL. -In other words, in addition to declaring the required permissions in the app's configuration file, you must [declare the ACL](accesstoken-guidelines.md#declaring-the-acl) in the app's profile. The subsequent steps of authorization are the same. +That is, you need to declare the required permissions in the app's configuration file, and [declare the ACL](accesstoken-guidelines.md#declaring-the-acl) in the app's profile. The subsequent steps of authorization are the same. **NOTICE** -When developing an app installation package, you must declare the allowed ACLs in the **acls** field in the app's profile. Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificate. +When developing an app installation package, you must declare the ACL in the **acls** field in the app's profile. Then, use the [hapsigner](hapsigntool-overview.md) tool to generate a certificate. -> **CAUTION**
The method of declaring the app's APL in its profile applies only to the application or service in debug phase. For a commercial app, apply for a release certificate and profile in the corresponding app market. +> **CAUTION**
The method of changing the app's APL in its profile applies only to the app or service in debug mode. For a commercial app, apply for a release certificate and profile in the corresponding app market. ```json { diff --git a/en/application-dev/security/figures/permission-verify-process.png b/en/application-dev/security/figures/permission-verify-process.png new file mode 100644 index 0000000000000000000000000000000000000000..8fdfadcc5f42486273e6150d302ab9525113756f Binary files /dev/null and b/en/application-dev/security/figures/permission-verify-process.png differ diff --git a/en/application-dev/security/huks-overview.md b/en/application-dev/security/huks-overview.md index cd918d5d3e24b7ac4e94e051f21fc495a44caa6d..b9b0b7a8530e41b40d1ed8d8c1eacb5ab451a7ad 100644 --- a/en/application-dev/security/huks-overview.md +++ b/en/application-dev/security/huks-overview.md @@ -12,17 +12,16 @@ OpenHarmony Universal KeyStore (HUKS) provides KeyStore (KS) capabilities for ap ## Working Principles -HUKS manages keys through the following operations: +HUKS manages keys through the following APIs in an Init-Update-Finish model: -- **Init**: reads the key, creates a session ID, and returns the session ID to the caller. +- **InitSession**: reads the key, creates a session ID, and returns the session ID to the caller. -- **Update**: updates data by segment based on the session ID obtained by the **Init** operation. +- **UpdateSession**: updates data by segment based on the session ID obtained by **InitSession()**. -- **Finish**: processes all data transferred to HUKS and then releases resources. +- **FinishSession**: processes all the data transferred to HUKS and then releases resources. > **NOTICE**
-> The **Abort** operation must be invoked to terminate the use of the key when an error occurs in the **Init**, **Update**, or **Finish** operation. - +> **AbortSession()** must be called to terminate the use of the key when an error occurs in any of **InitSession()**, **UpdateSession()**, and **FinishSession()**. ## Constraints N/A diff --git a/en/application-dev/security/permission-list.md b/en/application-dev/security/permission-list.md index 0f572b206d792df3e373d0468a10bb36690646ed..396f7d7eae1bb1058f615c3663e46be9eb574628 100644 --- a/en/application-dev/security/permission-list.md +++ b/en/application-dev/security/permission-list.md @@ -1,8 +1,8 @@ -# Application Permission List +# App Permission List -Before applying for required permissions, read and understand the [permission workflow](accesstoken-overview.md#permission-workflow). Then, determine whether the app can apply for the target permissions based on the table below. +Before applying for required permissions, read and understand the [permission workflows](accesstoken-overview.md#permission-workflows). Then, determine whether the app can apply for the target permissions based on the table below. -For details about permission usage examples, see [Access Control Development](accesstoken-guidelines.md). +For details about permission usage examples, see [Permission Application Guide](accesstoken-guidelines.md). | Permission | APL | Authorization Mode | Enable ACL| Description | | -------------------------------------------------------- | ------------ | ------------ | ------- | ------------------------------------------- | diff --git a/en/application-dev/security/permission-verify-guidelines.md b/en/application-dev/security/permission-verify-guidelines.md new file mode 100644 index 0000000000000000000000000000000000000000..cca11b49b4f02be2631b354adf47c83d4d57e2c1 --- /dev/null +++ b/en/application-dev/security/permission-verify-guidelines.md @@ -0,0 +1,46 @@ +# Permission Verification Guide + +## When to Use + +To protect sensitive data and eliminate security threads on core abilities, you can use the permissions in the [App Permission List](permission-list.md) to protect the related API from unauthorized calling. Each time before the API is called, a permission verification is performed to check whether the caller has the required permission. + +## Available APIs + +The table below lists only the API used in this guide. For more information, see [AbilityContext](../reference/apis/js-apis-ability-context.md). + +| API | Description | +| ------------------------------------------------------------ | --------------------------------------------------- | +| verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> | Checks whether an application process has the specified permission.| + + +## Example + +The procedure is as follows: + +1. Obtain the caller's identity (**tokenId**). +2. Determine the permission to verify, which is **ohos.permission.PERMISSION** in this example. +3. Call **verifyAccessToken()** to perform a permission verification of the caller. +4. Proceed based on the permission verification result. + +```js + import abilityAccessCtrl from '@ohos.abilityAccessCtrl' + import rpc from '@ohos.rpc' + + class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); + console.log("RpcServer: getCallingTokenId result: " + callerTokenId); + var atManager = abilityAccessCtrl.createAtManager(); + var result = await atManager.verifyAccessToken(tokenID, "ohos.permission.PERMISSION"); + if (result == abilityAccessCtrl.GrantStatus.PERMISSION_GRANTED) { + // Allow the caller to invoke the API provided by the app. + } else { + // Deny the caller's access to the API. + } + return true; + } + } + +``` +> **NOTE**
+> You can use **getCallingTokenId** to obtain the caller's **tokenId**. For details, see [RPC](../reference/apis/js-apis-rpc.md#getcallingtokenid8). 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/figures/en-us_image_0000001118642600.PNG b/en/application-dev/ui/figures/en-us_image_0000001118642600.PNG new file mode 100644 index 0000000000000000000000000000000000000000..31839738950d995d6b8fd6046965d212c385436b Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001118642600.PNG differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001178084014.gif b/en/application-dev/ui/figures/en-us_image_0000001178084014.gif new file mode 100644 index 0000000000000000000000000000000000000000..0365a98883522861faf808d8e207ff287ccd4e22 Binary files /dev/null and b/en/application-dev/ui/figures/en-us_image_0000001178084014.gif differ diff --git a/en/application-dev/ui/figures/en-us_image_0000001276003489.gif b/en/application-dev/ui/figures/en-us_image_0000001276003489.gif deleted file mode 100644 index 0554bd02b6ce8c1d835a3cde3bf2427d8dd15bda..0000000000000000000000000000000000000000 Binary files a/en/application-dev/ui/figures/en-us_image_0000001276003489.gif and /dev/null differ diff --git a/en/application-dev/ui/ts-component-based-builder.md b/en/application-dev/ui/ts-component-based-builder.md index d626bde6074c5e3db373a00f3a78bf6e554cf46f..318f248e6272400a035e01ca804965f0ca42738c 100644 --- a/en/application-dev/ui/ts-component-based-builder.md +++ b/en/application-dev/ui/ts-component-based-builder.md @@ -1,15 +1,43 @@ # @Builder -The **@Builder** decorated method is used to define the declarative UI description of a component and quickly generate multiple layouts in a custom component. The functionality and syntax of the **@Builder** decorator are the same as those of the [build Function](ts-function-build.md). +The **@Builder** decorated method is used to define the declarative UI description of a component and quickly generate multiple layouts in a custom component. If a custom component is used in the **@Builder** decorated method, this component will be re-created each time the method is invoked. The functionality and syntax of the **@Builder** decorator are the same as those of the **build** function. ```ts // xxx.ets + +@Component +struct CompB { + @State CompValue: string = ''; + + aboutToAppear() { + console.info('CompB aboutToAppear.'); + } + + aboutToDisappear() { + console.info('CompB aboutToDisappear.'); + } + + build() { + Column() { + Button(this.CompValue); + } + } +} + @Entry @Component struct CompA { - size1 : number = 100; + size1: number = 100; + @State CompValue1: string = "Hello,CompValue1"; + @State CompValue2: string = "Hello,CompValue2"; + @State CompValue3: string = "Hello,CompValue3"; + + // Use a custom component in the @Builder decorated method. + @Builder CompC(value: string) { + CompB({ CompValue: value }); + } @Builder SquareText(label: string) { Text(label) @@ -35,7 +63,16 @@ struct CompA { } .width(2 * this.size1) .height(1 * this.size1) + this.RowOfSquareTexts("C", "D") + Column() { + // Use the custom component in the @Builder decorated method three times. + this.CompC(this.CompValue1); + this.CompC(this.CompValue2); + this.CompC(this.CompValue3); + } + .width(2 * this.size1) + .height(2 * this.size1) } .width(2 * this.size1) .height(2 * this.size1) @@ -99,7 +136,7 @@ struct CustomContainerUser { } ``` ### Component Initialization Through Trailing Closure -In a custom component, use the **@BuilderParam** decorated attribute to receive a trailing closure. When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (`CustomComponent(){}`). You can consider a trailing closure as a container and add content to it. For example, you can add a component (`{Column(){Text("content")}`) to a trailing closure. The syntax of the closure is the same as that of [build](../ui/ts-function-build.md). In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute. +In a custom component, use the **@BuilderParam** decorated attribute to receive a trailing closure. When the custom component is initialized, the component name is followed by a pair of braces ({}) to form a trailing closure (`CustomComponent(){}`). You can consider a trailing closure as a container and add content to it. For example, you can add a component (`{Column(){Text("content")}`) to a trailing closure. The syntax of the closure is the same as that of the **build** function. In this scenario, the custom component has one and only one **@BuilderParam** decorated attribute. Example: Add a **\** component and a click event to the closure, and call the **specificParam** method decorated by **@Builder** in the new **\** component. After the **\** component is clicked, the value of the component's `header` attribute will change to `changeHeader`. In addition, when the component is initialized, the content of the trailing closure will be assigned to the `closer` attribute decorated by **@BuilderParam**. ```ts diff --git a/en/application-dev/ui/ts-pixel-units.md b/en/application-dev/ui/ts-pixel-units.md index ca95e08be83c3d40d12fba614e11d58470be2f16..032acce26c0cc48faa9cc1584ff1b2e66853908f 100644 --- a/en/application-dev/ui/ts-pixel-units.md +++ b/en/application-dev/ui/ts-pixel-units.md @@ -1,34 +1,32 @@ # Pixel Units - The framework provides four pixel units, with vp as the reference data unit. -| Name | Description | -| -------- | -------- | -| px | Physical pixel unit of the screen. | -| vp | Pixels specific to the screen density, which are converted into physical pixels of the screen based on the screen pixel density. | -| fp | Font pixel, which is similar to vp and varies according to the system font size. | -| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by [designWidth](../quick-start/package-structure.md)). For example, if designWidth is set to 720, then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels. | +| Name | Description | +| ---- | ---------------------------------------- | +| px | Physical pixel unit of the screen. | +| vp | Pixel unit specific to the screen density. Pixels in this unit are converted into physical pixels of the screen based on the screen pixel density. This unit is used for values whose unit is not specified. | +| fp | Font pixel, which is similar to vp and varies according to the system font size. | +| lpx | Logical pixel unit of the window. It is the ratio of the actual screen width to the logical width (configured by **[designWidth](../quick-start/package-structure.md)**). For example, if **designWidth** is set to **720** (default value), then 1lpx is equal to 2px for a screen with an actual width of 1440 physical pixels.| ## Pixel Unit Conversion -Conversion from other pixel units to px is supported. +Conversion between px and other pixel units is supported. -| API | Description | -| -------- | -------- | +| API | Description | +| ---------------------------------------- | ---------------------- | | vp2px(value : number) : number | Converts a value in units of vp to a value in units of px. | | px2vp(value : number) : number | Converts a value in units of px to a value in units of vp. | | fp2px(value : number) : number | Converts a value in units of fp to a value in units of px. | | px2fp(value : number) : number | Converts a value in units of px to a value in units of fp. | -| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px. | -| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx. | +| lpx2px(value : number) : number | Converts a value in units of lpx to a value in units of px.| +| px2lpx(value : number) : number | Converts a value in units of px to a value in units of lpx.| ## Example - ```ts // xxx.ets @Entry @@ -74,3 +72,4 @@ struct Example { ``` ![en-us_image_0000001267607893](figures/en-us_image_0000001267607893.gif) + diff --git a/en/application-dev/ui/ui-js-building-ui-layout-text.md b/en/application-dev/ui/ui-js-building-ui-layout-text.md index a5713dbf1830bd74aa8898bb7a93da027268c908..8eeb5dd599ae8cc7d25be019ba28483f9fd3f8eb 100644 --- a/en/application-dev/ui/ui-js-building-ui-layout-text.md +++ b/en/application-dev/ui/ui-js-building-ui-layout-text.md @@ -1,7 +1,6 @@ # Adding Title and Paragraph Text - -The <text> component is most commonly used to display text in title and paragraph areas. You can set attributes and styles for a <text> component and add the text to be displayed between the <text> and </text> tags. For details about the attributes and styles, see [text](../reference/arkui-js/js-components-basic-text.md). The following is an example of adding title and paragraph text on a page: +The **\** component is most commonly used to display text in title and paragraph areas. You can set attributes and styles for a **\** component and add the text to be displayed between the **\** and **\** tags. For details about the attributes and styles, see [text](../reference/arkui-js/js-components-basic-text.md). The following is an example of adding title and paragraph text on a page: ```html @@ -26,8 +25,10 @@ The <text> component is most commonly used to display text in title and pa font-size: 50px; margin-top: 40px; margin-bottom: 20px; + font-weight: 700; } .paragraph-text { + width: 95%; color: #000000; font-size: 35px; line-height: 60px; @@ -39,9 +40,11 @@ The <text> component is most commonly used to display text in title and pa // xxx.js export default { data: { - headTitle: 'Capture the Beauty in This Moment', + headTitle: 'Capture the Beauty in Moment', paragraphFirst: 'Capture the beauty of light during the transition and fusion of ice and water. At the instant of movement and stillness, softness and rigidity, force and beauty, condensing moving moments.', paragraphSecond: 'Reflecting the purity of nature, the innovative design upgrades your visual entertainment and ergonomic comfort. Effortlessly capture what you see and let it speak for what you feel.', }, } ``` + + ![en-us_image_0000001118642600](figures/en-us_image_0000001118642600.PNG) diff --git a/en/application-dev/ui/ui-js-components-button.md b/en/application-dev/ui/ui-js-components-button.md index 13f62b2abbab04176ab8a7d91dc08981d4ba74d6..b543a415b84bbfb56248be1249d7bb5aeceda799 100644 --- a/en/application-dev/ui/ui-js-components-button.md +++ b/en/application-dev/ui/ui-js-components-button.md @@ -1,12 +1,11 @@ -# <button> Development +# \