diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 32c2d5b1d1d7d78c1247a375cf17d53505050478..9e23ba2b1555dd0935c3d70be2658544fdc40ec2 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -1,64 +1,137 @@ # APIs - [API Reference Document Description](development-intro.md) + - Ability Framework - - FA Model - - [@ohos.ability.featureAbility](js-apis-featureAbility.md) - - [@ohos.ability.particleAbility](js-apis-particleAbility.md) - - ability/[dataAbilityHelper](js-apis-dataAbilityHelper.md) - - app/[context](js-apis-Context.md) - - Stage Model + - Stage Model (Recommended) + - [@ohos.app.ability.Ability](js-apis-app-ability-ability.md) + - [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) + - [@ohos.app.ability.abilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) + - [@ohos.app.ability.AbilityStage](js-apis-app-ability-abilityStage.md) + - [@ohos.app.ability.common](js-apis-app-ability-common.md) + - [@ohos.app.ability.contextConstant](js-apis-app-ability-contextConstant.md) + - [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) + - [@ohos.app.ability.ExtensionAbility](js-apis-app-ability-extensionAbility.md) + - [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) + - [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) + - [@ohos.app.ability.UIAbility](js-apis-app-ability-uiAbility.md) + - [@ohos.app.form.FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) + - [@ohos.application.DataShareExtensionAbility](js-apis-application-dataShareExtensionAbility.md) + - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) + - Stage Model (To Be Deprecated Soon) - [@ohos.application.Ability](js-apis-application-ability.md) - [@ohos.application.AbilityConstant](js-apis-application-abilityConstant.md) - - [@ohos.application.AbilityStage](js-apis-application-abilitystage.md) - - [@ohos.application.abilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) - - [@ohos.application.DataShareExtensionAbility](js-apis-application-DataShareExtensionAbility.md) - - [@ohos.application.EnvironmentCallback](js-apis-application-EnvironmentCallback.md) - - [@ohos.application.FormExtension](js-apis-formextension.md) - - [@ohos.application.ServiceExtensionAbility](js-apis-service-extension-ability.md) - - [@ohos.application.StartOptions](js-apis-application-StartOptions.md) - - [@ohos.application.StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md) - - [@ohos.application.WindowExtensionAbility](js-apis-application-WindowExtensionAbility.md) - - application/[AbilityContext](js-apis-ability-context.md) - - application/[ApplicationContext](js-apis-application-applicationContext.md) - - application/[AbilityStageContext](js-apis-abilitystagecontext.md) - - application/[Context](js-apis-application-context.md) - - application/[ExtensionContext](js-apis-extension-context.md) - - application/[FormExtensionContext](js-apis-formextensioncontext.md) - - application/[PermissionRequestResult](js-apis-permissionrequestresult.md) - - application/[ServiceExtensionContext](js-apis-service-extension-context.md) - - FA and Stage Models - - [@ohos.ability.dataUriUtils](js-apis-DataUriUtils.md) + - [@ohos.application.AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) + - [@ohos.application.AbilityStage](js-apis-application-abilityStage.md) + - [@ohos.application.context](js-apis-application-context.md) + - [@ohos.application.EnvironmentCallback](js-apis-application-environmentCallback.md) + - [@ohos.application.ExtensionAbility](js-apis-application-extensionAbility.md) + - [@ohos.application.FormExtension](js-apis-application-formExtension.md) + - [@ohos.application.ServiceExtensionAbility](js-apis-application-serviceExtensionAbility.md) + - [@ohos.application.StartOptions](js-apis-application-startOptions.md) + - FA Model + - [@ohos.ability.ability](js-apis-ability-ability.md) + - [@ohos.ability.featureAbility](js-apis-ability-featureAbility.md) + - [@ohos.ability.particleAbility](js-apis-ability-particleAbility.md) + - Both Models (Recommended) + - [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) + - [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) + - [@ohos.app.ability.appManager](js-apis-app-ability-appManager.md) + - [@ohos.app.ability.appRecovery](js-apis-app-ability-appRecovery.md) + - [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) + - [@ohos.app.ability.ConfigurationConstant](js-apis-app-ability-configurationConstant.md) + - [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) + - [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) + - [@ohos.app.ability.quickFixManager](js-apis-app-ability-quickFixManager.md) + - [@ohos.app.ability.Want](js-apis-app-ability-want.md) + - [@ohos.app.ability.wantAgent](js-apis-app-ability-wantAgent.md) + - [@ohos.app.ability.wantConstant](js-apis-app-ability-wantConstant.md) + - [@ohos.app.form.formBindingData](js-apis-app-form-formBindingData.md) + - [@ohos.app.form.formHost](js-apis-app-form-formHost.md) + - [@ohos.app.form.formInfo](js-apis-app-form-formInfo.md) + - [@ohos.app.form.formProvider](js-apis-app-form-formProvider.md) + - Both Models (To Be Deprecated Soon) + - [@ohos.ability.dataUriUtils](js-apis-ability-dataUriUtils.md) - [@ohos.ability.errorCode](js-apis-ability-errorCode.md) - [@ohos.ability.wantConstant](js-apis-ability-wantConstant.md) - - [@ohos.application.abilityDelegatorRegistry](js-apis-abilityDelegatorRegistry.md) + - [@ohos.application.abilityDelegatorRegistry](js-apis-application-abilityDelegatorRegistry.md) - [@ohos.application.abilityManager](js-apis-application-abilityManager.md) - - [@ohos.application.appManager](js-apis-appmanager.md) - - [@ohos.application.errorManager](js-apis-errorManager.md) - - [@ohos.application.formBindingData](js-apis-formbindingdata.md) - - [@ohos.application.formError](js-apis-formerror.md) - - [@ohos.application.formHost](js-apis-formhost.md) - - [@ohos.application.formInfo](js-apis-formInfo.md) - - [@ohos.application.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-continuationManager.md) + - [@ohos.application.appManager](js-apis-application-appManager.md) + - [@ohos.application.Configuration](js-apis-application-configuration.md) + - [@ohos.application.ConfigurationConstant](js-apis-application-configurationConstant.md) + - [@ohos.application.errorManager)](js-apis-application-errorManager.md) + - [@ohos.application.formBindingData](js-apis-application-formBindingData.md) + - [@ohos.application.formError](js-apis-application-formError.md) + - [@ohos.application.formHost](js-apis-application-formHost.md) + - [@ohos.application.formInfo](js-apis-application-formInfo.md) + - [@ohos.application.formProvider](js-apis-application-formProvider.md) + - [@ohos.application.missionManager](js-apis-application-missionManager.md) + - [@ohos.application.Want](js-apis-application-want.md) - [@ohos.wantAgent](js-apis-wantAgent.md) - - application/[abilityDelegator](js-apis-application-abilityDelegator.md) - - application/[abilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md) - - application/[abilityMonitor](js-apis-application-abilityMonitor.md) - - application/[AbilityRunningInfo](js-apis-abilityrunninginfo.md) - - application/[ExtensionRunningInfo](js-apis-extensionrunninginfo.md) - - application/[MissionSnapshot](js-apis-application-MissionSnapshot.md) - - application/[ProcessRunningInformation](js-apis-processrunninginformation.md) - - application/[shellCmdResult](js-apis-application-shellCmdResult.md) - - continuation/[continuationExtraParams](js-apis-continuation-continuationExtraParams.md) - - continuation/[ContinuationResult](js-apis-continuation-continuationResult.md) + - Dependent Elements and Definitions + - ability + - [abilityResult](js-apis-inner-ability-abilityResult.md) + - [connectOptions](js-apis-inner-ability-connectOptions.md) + - [dataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) + - [dataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) + - [dataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) + - [startAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) + - [want](js-apis-inner-ability-want.md) + - app + - [appVersionInfo](js-apis-inner-app-appVersionInfo.md) + - [context](js-apis-inner-app-context.md) + - [processInfo](js-apis-inner-app-processInfo.md) + - application + - [AbilityContext](js-apis-ability-context.md) + - [abilityDelegator](js-apis-inner-application-abilityDelegator.md) + - [abilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) + - [abilityMonitor](js-apis-inner-application-abilityMonitor.md) + - [AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md) + - [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) + - [AbilityStateData](js-apis-inner-application-abilityStateData.md) + - [abilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) + - [ApplicationContext](js-apis-inner-application-applicationContext.md) + - [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) + - [AppStateData](js-apis-inner-application-appStateData.md) + - [BaseContext](js-apis-inner-application-baseContext.md) + - [Context](js-apis-inner-application-context.md) + - [ContinueCallback](js-apis-inner-application-continueCallback.md) + - [ContinueDeviceInfo](js-apis-inner-application-continueDeviceInfo.md) + - [ErrorObserver](js-apis-inner-application-errorObserver.md) + - [ExtensionContext](js-apis-inner-application-extensionContext.md) + - [ExtensionRunningInfo](js-apis-inner-application-extensionRunningInfo.md) + - [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) + - [MissionCallbacks](js-apis-inner-application-missionCallbacks.md) + - [MissionDeviceInfo](js-apis-inner-application-missionDeviceInfo.md) + - [MissionInfo](js-apis-inner-application-missionInfo.md) + - [MissionListener](js-apis-inner-application-missionListener.md) + - [MissionParameter](js-apis-inner-application-missionParameter.md) + - [MissionSnapshot](js-apis-inner-application-missionSnapshot.md) + - [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) + - [ProcessData](js-apis-inner-application-processData.md) + - [ProcessRunningInfo](js-apis-inner-application-processRunningInfo.md) + - [ProcessRunningInformation](js-apis-inner-application-processRunningInformation.md) + - [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) + - [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) + - [shellCmdResult](js-apis-inner-application-shellCmdResult.md) + - wantAgent + - [triggerInfo](js-apis-inner-wantAgent-triggerInfo.md) + - [wantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) + - Continuation + - [@ohos.continuation.continuationManager (continuationManager)](js-apis-continuation-continuationManager.md) + - continuation + - [continuationExtraParams](js-apis-continuation-continuationExtraParams.md) + - [continuationResult](js-apis-continuation-continuationResult.md) + - Common Event and Notification + - [@ohos.commonEventManager (Recommended)](js-apis-commonEventManager.md) - [@ohos.events.emitter](js-apis-emitter.md) + - [@ohos.notificationManager (Recommended)](js-apis-notificationManager.md) + - [@ohos.notificationSubscribe (Recommended)](js-apis-notificationSubscribe.md) + - [@ohos.commonEvent (To Be Deprecated Soon)](js-apis-commonEvent.md) - [@ohos.notification](js-apis-notification.md) - - application/[EventHub](js-apis-eventhub.md) + - application + - [EventHub](js-apis-inner-application-eventHub.md) - Bundle Management - [@ohos.bundle.appControl](js-apis-appControl.md) - [@ohos.bundle.bundleManager](js-apis-bundleManager.md) @@ -69,36 +142,42 @@ - [@ohos.bundle.installer](js-apis-installer.md) - [@ohos.bundle.launcherBundleManager](js-apis-launcherBundleManager.md) - [@ohos.zlib](js-apis-zlib.md) - - bundleManager/[abilityInfo](js-apis-bundleManager-abilityInfo.md) - - bundleManager/[applicationInfo](js-apis-bundleManager-applicationInfo.md) - - bundleManager/[bundleInfo](js-apis-bundleManager-bundleInfo.md) - - bundleManager/[dispatchInfo](js-apis-bundleManager-dispatchInfo.md) - - bundleManager/[elementName](js-apis-bundleManager-elementName.md) - - bundleManager/[extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) - - bundleManager/[hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) - - bundleManager/[launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) - - bundleManager/[metadata](js-apis-bundleManager-metadata.md) - - bundleManager/[packInfo](js-apis-bundleManager-packInfo.md) - - bundleManager/[permissionDef](js-apis-bundleManager-permissionDef.md) - - bundleManager/[remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) - - bundleManager/[shortcutInfo](js-apis-bundleManager-shortcutInfo.md) + - bundleManager + - [abilityInfo](js-apis-bundleManager-abilityInfo.md) + - [applicationInfo](js-apis-bundleManager-applicationInfo.md) + - [bundleInfo](js-apis-bundleManager-bundleInfo.md) + - [dispatchInfo](js-apis-bundleManager-dispatchInfo.md) + - [elementName](js-apis-bundleManager-elementName.md) + - [extensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) + - [hapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) + - [launcherAbilityInfo](js-apis-bundleManager-launcherAbilityInfo.md) + - [metadata](js-apis-bundleManager-metadata.md) + - [packInfo](js-apis-bundleManager-packInfo.md) + - [permissionDef](js-apis-bundleManager-permissionDef.md) + - [remoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) + - [shortcutInfo](js-apis-bundleManager-shortcutInfo.md) - UI Page - [@ohos.animator](js-apis-animator.md) + - [@ohos.curves](js-apis-curve.md) + - [@ohos.matrix4](js-apis-matrix4.md) - [@ohos.mediaquery](js-apis-mediaquery.md) - [@ohos.promptAction](js-apis-promptAction.md) - [@ohos.router](js-apis-router.md) - Graphics - [@ohos.animation.windowAnimationManager](js-apis-windowAnimationManager.md) + - [@ohos.application.WindowExtensionAbility](js-apis-application-windowExtensionAbility.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) - - [webgl](js-apis-webgl.md) - - [webgl2](js-apis-webgl2.md) + - webgl + - [webgl](js-apis-webgl.md) + - [webgl2](js-apis-webgl2.md) - Media - [@ohos.multimedia.audio](js-apis-audio.md) + - [@ohos.multimedia.avsession](js-apis-avsession.md) - [@ohos.multimedia.camera](js-apis-camera.md) - [@ohos.multimedia.image](js-apis-image.md) - [@ohos.multimedia.media](js-apis-media.md) @@ -114,30 +193,33 @@ - [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md) - [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md) - Security - - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md) - - [@ohos.privacyManager](js-apis-privacyManager.md) - - [@ohos.security.cryptoFramework](js-apis-cryptoFramework.md) - - [@ohos.security.huks ](js-apis-huks.md) - - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md) - - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md) - - [@system.cipher](js-apis-system-cipher.md) + - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md) + - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md) + - [@ohos.security.cert (Certificate)](js-apis-cert.md) + - [@ohos.security.cryptoFramework (Crypto Framework)](js-apis-cryptoFramework.md) + - [@ohos.security.huks (HUKS)](js-apis-huks.md) + - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md) + - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md) + - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md) - Data Management - - [@ohos.data.dataAbility ](js-apis-data-ability.md) - - [@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.distributedDataObject](js-apis-data-distributedobject.md) - - [@ohos.data.preferences](js-apis-data-preferences.md) - - [@ohos.data.rdb](js-apis-data-rdb.md) - - [@ohos.data.ValuesBucket](js-apis-data-ValuesBucket.md) - - data/rdb/[resultSet](js-apis-data-resultset.md) + - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md) + - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md) + - [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md) + - [@ohos.data.dataShareResultSet (DataShare Result Set)](js-apis-data-DataShareResultSet.md) + - [@ohos.data.distributedDataObject (Distributed Data Object)](js-apis-data-distributedobject.md) + - [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md) + - [@ohos.data.preferences (Preferences)](js-apis-data-preferences.md) + - [@ohos.data.rdb (RDB)](js-apis-data-rdb.md) + - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md) + - data/rdb + - [resultSet](js-apis-data-resultset.md) - File Management - [@ohos.document](js-apis-document.md) - [@ohos.environment](js-apis-environment.md) - [@ohos.data.fileAccess](js-apis-fileAccess.md) - [@ohos.fileExtensionInfo](js-apis-fileExtensionInfo.md) - [@ohos.fileio](js-apis-fileio.md) - - [@ohos.filemanagement.userfile_manager](js-apis-userfilemanager.md) + - [@ohos.filemanagement.userFileManager](js-apis-userFileManager.md) - [@ohos.multimedia.medialibrary](js-apis-medialibrary.md) - [@ohos.securityLabel](js-apis-securityLabel.md) - [@ohos.statfs](js-apis-statfs.md) @@ -166,14 +248,19 @@ - [@ohos.nfc.controller](js-apis-nfcController.md) - [@ohos.nfc.tag](js-apis-nfcTag.md) - [@ohos.rpc](js-apis-rpc.md) + - [@ohos.wifiManager (WLAN)](js-apis-wifiManager.md) + - [@ohos.wifiManagerExt](js-apis-wifiManagerExt.md) - [@ohos.wifi](js-apis-wifi.md) - [@ohos.wifiext](js-apis-wifiext.md) - - tag/[nfctech](js-apis-nfctech.md) - - tag/[tagSession](js-apis-tagSession.md) + - tag + - [nfctech](js-apis-nfctech.md) + - [tagSession](js-apis-tagSession.md) - Basic Features - [@ohos.accessibility](js-apis-accessibility.md) - [@ohos.accessibility.config](js-apis-accessibility-config.md) - - [@ohos.application.AccessibilityExtensionAbility](js-apis-application-AccessibilityExtensionAbility.md) + - [@ohos.accessibility.GesturePat](js-apis-accessibility-GesturePath.md) + - [@ohos.accessibility.GesturePoint](js-apis-accessibility-GesturePoint.md) + - [@ohos.application.AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md) - [@ohos.faultLogger](js-apis-faultLogger.md) - [@ohos.hichecker](js-apis-hichecker.md) - [@ohos.hidebug](js-apis-hidebug.md) @@ -181,23 +268,29 @@ - [@ohos.hiSysEvent](js-apis-hisysevent.md) - [@ohos.hiTraceChain](js-apis-hitracechain.md) - [@ohos.hiTraceMeter](js-apis-hitracemeter.md) - - [@ohos.inputMethod](js-apis-inputmethod.md) - - [@ohos.inputMethodEngine](js-apis-inputmethodengine.md) + - [@ohos.hiviewdfx.hiAppEvent](js-apis-hiviewdfx-hiappevent.md) + - [@ohos.inputmethod](js-apis-inputmethod.md) + - [@ohos.inputmethodengine](js-apis-inputmethodengine.md) - [@ohos.inputmethodextensionability](js-apis-inputmethod-extension-ability.md) - [@ohos.inputmethodextensioncontext](js-apis-inputmethod-extension-context.md) + - [@ohos.inputmethodsubtype](js-apis-inputmethod-subtype.md) - [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) - [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.wallpaper](js-apis-wallpaper.md) + - [@ohos.web.webview](js-apis-webview.md) - [console](js-apis-logs.md) - [Timer](js-apis-timer.md) - - application/[AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) + - application + - [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) - Device Management - [@ohos.batteryInfo ](js-apis-battery-info.md) + - [@ohos.batteryStatistics](js-apis-batteryStatistics.md) - [@ohos.brightness](js-apis-brightness.md) - [@ohos.deviceInfo](js-apis-device-info.md) - [@ohos.distributedHardware.deviceManager](js-apis-device-manager.md) + - [@ohos.geoLocationManager](js-apis-geoLocationManager.md) - [@ohos.multimodalInput.inputConsumer](js-apis-inputconsumer.md) - [@ohos.multimodalInput.inputDevice](js-apis-inputdevice.md) - [@ohos.multimodalInput.inputDeviceCooperate](js-apis-cooperate.md) @@ -213,6 +306,8 @@ - [@ohos.runningLock](js-apis-runninglock.md) - [@ohos.sensor](js-apis-sensor.md) - [@ohos.settings](js-apis-settings.md) + - [@ohos.stationary](js-apis-stationary.md) + - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md) - [@ohos.systemParameterV9](js-apis-system-parameterV9.md) - [@ohos.thermal](js-apis-thermal.md) - [@ohos.update](js-apis-update.md) @@ -224,9 +319,12 @@ - [@ohos.account.osAccount](js-apis-osAccount.md) - Custom Management - [@ohos.configPolicy](js-apis-configPolicy.md) - - [@ohos.EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterprise.adminManager](js-apis-enterprise-adminManager.md) + - [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md) + - Language Base Class Library - - [@ohos.buffer](js-apis-buffer.md) + - [@ohos.buffer (Buffer)](js-apis-buffer.md) - [@ohos.convertxml](js-apis-convertxml.md) - [@ohos.process](js-apis-process.md) - [@ohos.uri](js-apis-uri.md) @@ -249,15 +347,14 @@ - [@ohos.worker](js-apis-worker.md) - [@ohos.xml](js-apis-xml.md) - Test - - [@ohos.application.testRunner](js-apis-testRunner.md) + - [@ohos.application.testRunner](js-apis-application-testRunner.md) - [@ohos.uitest](js-apis-uitest.md) -- APIs No Longer Maintained +- APIs No Longer Maintained - [@ohos.backgroundTaskManager](js-apis-backgroundTaskManager.md) - [@ohos.bundle](js-apis-Bundle.md) - [@ohos.bundle.innerBundleManager](js-apis-Bundle-InnerBundleManager.md) - [@ohos.bundleState](js-apis-deviceUsageStatistics.md) - [@ohos.bytrace](js-apis-bytrace.md) - - [@ohos.commonEvent](js-apis-commonEvent.md) - [@ohos.data.storage](js-apis-data-storage.md) - [@ohos.data.distributedData](js-apis-distributed-data.md) - [@ohos.distributedBundle](js-apis-Bundle-distributedBundle.md) @@ -267,6 +364,7 @@ - [@ohos.prompt](js-apis-prompt.md) - [@ohos.reminderAgent](js-apis-reminderAgent.md) - [@ohos.systemParameter](js-apis-system-parameter.md) + - [@ohos.usb](js-apis-usb-deprecated.md) - [@ohos.workScheduler](js-apis-workScheduler.md) - [@system.app](js-apis-system-app.md) - [@system.battery](js-apis-system-battery.md) @@ -287,17 +385,17 @@ - [@system.sensor](js-apis-system-sensor.md) - [@system.storage](js-apis-system-storage.md) - [@system.vibrator](js-apis-system-vibrate.md) - - application/[ProcessRunningInfo](js-apis-processrunninginfo.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/[elementName](js-apis-bundle-ElementName.md) - - bundle/[hapModuleInfo](js-apis-bundle-HapModuleInfo.md) - - bundle/[launcherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md) - - bundle/[moduleInfo](js-apis-bundle-ModuleInfo.md) - - bundle/[PermissionDef](js-apis-bundle-PermissionDef.md) - - bundle/[remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) - - bundle/[shortcutInfo](js-apis-bundle-ShortcutInfo.md) + - bundle + - [abilityInfo](js-apis-bundle-AbilityInfo.md) + - [applicationInfo](js-apis-bundle-ApplicationInfo.md) + - [bundleInfo](js-apis-bundle-BundleInfo.md) + - [bundleInstaller](js-apis-bundle-BundleInstaller.md) + - [bundleStatusCallback](js-apis-Bundle-BundleStatusCallback.md) + - [customizeData](js-apis-bundle-CustomizeData.md) + - [elementName](js-apis-bundle-ElementName.md) + - [hapModuleInfo](js-apis-bundle-HapModuleInfo.md) + - [launcherAbilityInfo](js-apis-bundle-LauncherAbilityInfo.md) + - [moduleInfo](js-apis-bundle-ModuleInfo.md) + - [PermissionDef](js-apis-bundle-PermissionDef.md) + - [remoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md) + - [shortcutInfo](js-apis-bundle-ShortcutInfo.md) diff --git a/en/application-dev/reference/apis/development-intro.md b/en/application-dev/reference/apis/development-intro.md index aaeab2f2961f4254f4bbd8d634ee0f773f996ab4..281fa66969891561b062b7cfd7185d25f7c7f474 100644 --- a/en/application-dev/reference/apis/development-intro.md +++ b/en/application-dev/reference/apis/development-intro.md @@ -9,9 +9,9 @@ In API references, the earliest versions of APIs and components are specified in - For a new API or component, the version information is provided at the beginning of the reference document. Example: "The initial APIs of this module are supported since API version 7." - For a new feature of an existing API or component, a superscript is added following the feature. For example, "uid8+" indicates that the **uid** attribute is supported since API version 8. -## Ability Framework Model Description +## Application Model Description -Ability is the minimum unit for the system to schedule applications. An application can contain one or more `Ability` instances. Ability framework models are classified into the FA model and stage model. For details, see [Ability Framework Overview](../../ability/ability-brief.md). +Along its evolution, OpenHarmony has provided two application models: FA model and stage model. For their differences, see [Interpretation of the Application Model](../../application-models/application-model-description.md). - If all the APIs of a module support only one model, the following description is provided at the beginning of the reference document: "The APIs of this module can be used only in the FA model." or "The APIs of this module can be used only in the stage model." - If certain APIs of a module support only one model, the following description is provided individually for these APIs: "This API can be used only in the FA model." or "This API can be used only in the stage model." @@ -19,18 +19,18 @@ Ability is the minimum unit for the system to schedule applications. An applicat ## Available APIs -Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by non-system applications. +Certain APIs provided by OpenHarmony are system APIs, which can be used only by original equipment manufacturers (OEMs) and cannot be used by common applications. A description regarding system APIs will be provided in the document. - If all the APIs of a module are system APIs, the following description is provided at the beginning of the reference document: "All the APIs of this module are system APIs." - If a specific API of a module is a system API, the following description is provided individually for the API: "This is a system API." -Non-system applications are applications whose Ability Privilege Level (APL) is **normal**. The default application level is **normal**. +A common application is an application whose application type is **hos_normal_app** in the HarmonyAppProvision configuration file. **hos_normal_app** is the default value for project creation. -For details about the APL and how to declare the APL of an application higher than **normal**, see [Access Control Overview - App APLs](../../security/accesstoken-overview.md#app-apls). - -The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use system APIs, switch to the full SDK. For details on the operation, see [Guide to Switching to Full SDK](../../quick-start/full-sdk-switch-guide.md). +The public SDK, which does not include system APIs, is provided as standard in DevEco Studio. To use the system APIs, you must: +- Switch the public SDK to the full SDK by following the instructions provided in [Guide to Switching to Full SDK] (../../quick-start/full-sdk-switch-guide.md). +- Change the value of **app-feature** in the HarmonyAppProvision configuration file to **hos_system_app**. For details, see [HarmonyAppProvision Configuration File](../../security/app-provision-structure.md). ## Permission Description @@ -41,17 +41,19 @@ To call APIs to access these resources, you must apply for the corresponding per - If an application can call an API only after it has obtained a specific permission, the following description is provided for the API: "**Required permissions**: ohos.permission.xxxx" - If an application can call an API without any permission, no special description is provided. -To determine whether an application can apply for a specific permission, see [Permission List](../../security/permission-list.md). +To determine whether an application can request a specific permission, see [Permission Application and Use](../../security/accesstoken-overview.md#permission-application-and-use). ## System Capability Description -System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SysCap](../../quick-start/syscap.md). +System capability refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. For details, see [SystemCapability](../syscap.md). The following description is provided for each API in the reference document to describe the system capability of the API: "**System capability**: SystemCapability.xxx.xxx" +You can use the [SystemCapability List](../syscap-list.md) to query the devices supported by a specific capability set. + ## Sample Code Language Description OpenHarmony supports two development languages: JS and TS. -- When a code block is labeled with `js`, the sample code can be used in the JS and ArkTS projects. -- When a code block is labeled with `ts`, the sample code can be used only in the ArkTS project. +- When a code block is labeled with **js**, the sample code can be used in the JS and ArkTS projects. +- When a code block is labeled with **ts**, the sample code can be used only in the ArkTS project. diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001118642902.png b/en/application-dev/reference/apis/figures/en-us_image_0000001118642902.png new file mode 100644 index 0000000000000000000000000000000000000000..36eab44e87c075e01baa66bfc48a86ba703b7835 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001118642902.png differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001174104410.gif b/en/application-dev/reference/apis/figures/en-us_image_0000001174104410.gif new file mode 100644 index 0000000000000000000000000000000000000000..df8e47d8359338f9d0412cacfe12b847c28c2a84 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001174104410.gif differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001174422898.png b/en/application-dev/reference/apis/figures/en-us_image_0000001174422898.png new file mode 100644 index 0000000000000000000000000000000000000000..1dc7d8d7beda862221b05a9247723a3f74bf323d Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001174422898.png differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001219662645.png b/en/application-dev/reference/apis/figures/en-us_image_0000001219662645.png new file mode 100644 index 0000000000000000000000000000000000000000..747b8f915f2d40803ce6a7937de1add5deb8e640 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001219662645.png differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001219744181.png b/en/application-dev/reference/apis/figures/en-us_image_0000001219744181.png new file mode 100644 index 0000000000000000000000000000000000000000..605c0a1ddc0e2bace2e4c9a23fc2391af9ebf5bf Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001219744181.png differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001219864131.png b/en/application-dev/reference/apis/figures/en-us_image_0000001219864131.png new file mode 100644 index 0000000000000000000000000000000000000000..5c0ada67867ec3765eeb53af5c62369762d0bac4 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001219864131.png differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG b/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG new file mode 100644 index 0000000000000000000000000000000000000000..14f81499ff0b1b8ef46257bc35a79e94775cd2ba Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_0000001219864133.PNG differ diff --git a/en/application-dev/reference/apis/figures/en-us_image_00007.gif b/en/application-dev/reference/apis/figures/en-us_image_00007.gif new file mode 100644 index 0000000000000000000000000000000000000000..8c43bdf5b331963459154d4f0400fad7b17b34e8 Binary files /dev/null and b/en/application-dev/reference/apis/figures/en-us_image_00007.gif differ 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 9d023410fff66869318fca78d3cae361ff71217b..40725aefbf65838c8da46d75a13368c68118df0d 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @@ -1,8 +1,8 @@ -# innerBundleManager(deprecated) +# @ohos.bundle.innerBundleManager The **innerBundleManager** module provides APIs for the **Home Screen** application. -> +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. > This module is deprecated since API version 9. You are advised to use [launcherBundleManager](js-apis-launcherBundleManager.md) and [bundleMonitor](js-apis-bundleMonitor.md) instead. @@ -41,7 +41,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| | callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | @@ -69,7 +69,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ----------------------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** @@ -216,7 +216,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------------------- | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| | callback | AsyncCallback\> | Yes | Callback used to return an array of the launcher ability information. | ## innerBundleManager.getAllLauncherAbilityInfos(deprecated) @@ -242,7 +242,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ----------------------------------------------------- | -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| userId | number | Yes | User ID. The value must be greater than or equal to 0.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md index 8701a6b80d7d54dc8bf6a30850c3551a741e77ed..493b263bd25d74fa7cfa5d9c59a45659fb4b5740 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -46,7 +46,7 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**. | | callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Yes | Callback used to return the remote ability information.| @@ -75,7 +75,7 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ----------- | -------------------------------------------- | ---- | ----------------------- | | elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | **ElementName**.| @@ -107,10 +107,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | | elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10. | -| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return the remote ability information.| +| callback | AsyncCallback< Array<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)>> | Yes | Callback used to return an array of the remote ability information.| @@ -136,7 +136,7 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------ | --------------------------------------------------- | ---- | ----------------------- | | elementNames | Array<[ElementName](js-apis-bundle-ElementName.md)> | Yes | **ElementName** array, whose maximum length is 10.| diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index 52a10b74d2346bc15d2fc17ce196b190bfbfa521..83cf9c77d2899e1c0c0969be8199c602e4374816 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -1,24 +1,24 @@ -# Bundle +# @ohos.bundle -The **Bundle** module provides APIs for querying the information about bundles, applications, abilities, Extension abilities, and application states. +The **bundle** module provides APIs for obtaining information about an application, including [bundle information](js-apis-bundle-BundleInfo.md), [application information](js-apis-bundle-ApplicationInfo.md), and [ability information](js-apis-bundle-AbilityInfo.md). It also provides APIs to obtain and set the application disabling 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. ## Modules to Import -```js +```ts import bundle from '@ohos.bundle'; ``` ## Required Permissions -| Required Permissions | Permission Level | Description | -| ------------------------------------------ | ------------ | ------------------ | -| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified application. | -| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all applications.| -| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall applications. | -| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status. | +| Required Permissions | Permission Level | Description | +|--------------------------------------------|--------------|---------------| +| ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle. | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles. | +| ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall bundles. | +| ohos.permission.MANAGE_DISPOSED_APP_STATUS | system_core | Permission to set and query the application disposal status.| For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). @@ -30,6 +30,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, userId?: number): Pr Obtains the application information based on a given bundle name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -42,8 +44,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflagdeprecated).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -54,7 +56,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; let userId = 100; @@ -74,6 +76,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, userId: number, call Obtains the application information of the specified user based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -86,14 +90,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; let userId = 100; @@ -115,6 +119,8 @@ getApplicationInfo(bundleName: string, bundleFlags: number, callback: AsyncCallb Obtains the application information based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -127,13 +133,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | callback | AsyncCallback\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Yes | Callback used to return the application information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 0; bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { @@ -152,7 +158,7 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> -Obtains the information of all available bundles of the specified user in the system. This API uses a promise to return the result. +Obtains the information of all bundles of the specified user. This API uses a promise to return the result. **Required permissions** @@ -166,7 +172,7 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------- | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -177,7 +183,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleFlag = 0; let userId = 100; bundle.getAllBundleInfo(bundleFlag, userId) @@ -195,7 +201,7 @@ bundle.getAllBundleInfo(bundleFlag, userId) getAllBundleInfo(bundleFlag: BundleFlag, callback: AsyncCallback>): void -Obtains the information of all available bundles in the system. This API uses an asynchronous callback to return the result. +Obtains the information of all bundles of the current user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -209,12 +215,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | **Example** -```js +```ts let bundleFlag = 0; bundle.getAllBundleInfo(bundleFlag, (err, data) => { if (err) { @@ -232,7 +238,7 @@ bundle.getAllBundleInfo(bundleFlag, (err, data) => { getAllBundleInfo(bundleFlag: BundleFlag, userId: number, callback: AsyncCallback>): void -Obtains the information of all available bundles of the specified user in the system. This API uses an asynchronous callback to return the result. +Obtains the information of all bundles of the specified user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -244,15 +250,16 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlag | BundleFlag | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | -| callback | AsyncCallback> | Yes | Callback used to return the information of all available bundles. | +| Name | Type | Mandatory | Description | +|------------|-------------------------------------------------------------------|-----|---------------------------------------------------------------------| +| bundleFlag | BundleFlag | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the information of all bundles. | +| **Example** -```js +```ts let bundleFlag = 0; let userId = 100; bundle.getAllBundleInfo(bundleFlag, userId, (err, data) => { @@ -273,6 +280,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, options?: BundleOptions): Obtains the bundle information based on a given bundle name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -283,11 +292,11 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------- | ---- | --------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| options | [BundleOptions](#bundleoptions) | No | Includes **userId**. | +| Name | Type | Mandatory | Description | +| ----------- | ------------- | ---- |---------------------------------------------------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| options | [BundleOptions](#bundleoptions) | No | Options that contain the user ID. | **Return value** @@ -297,7 +306,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { @@ -319,6 +328,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\< Obtains the bundle information based on a given bundle name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -329,15 +340,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| -| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | +| Name | Type | Mandatory| Description | +| ----------- | ---------------------------------------------------------- | ---- |---------------------------------------------------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; bundle.getBundleInfo(bundleName, bundleFlags, (err, data) => { @@ -358,6 +369,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, options: BundleOptions, c Obtains the bundle information based on a given bundle name and bundle options. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -370,14 +383,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ---------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Bundle name of an application. | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| bundleName | string | Yes | Bundle name of the application. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | options | [BundleOptions](#bundleoptions) | Yes | Includes **userId**. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the bundle information. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; let bundleFlags = 1; let options = { @@ -400,7 +413,7 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { getBundleInstaller(): Promise<BundleInstaller>; -Obtains the installation package information. This API uses a promise to return the result. +Obtains the installation package. This API uses a promise to return the result. **Required permissions** @@ -418,7 +431,17 @@ This is a system API and cannot be called by third-party applications. | Type | Description | | ------------------------------------------------------------ | -------------------------------------------- | -| Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Promise used to return the installation package information.| +| Promise<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Promise used to return the installation package.| + +**Example** + +```ts +bundle.getBundleInstaller().then((data) => { + console.info('getBundleInstaller successfully.'); +}).catch((error) => { + console.error('getBundleInstaller failed.'); +}); +``` ## bundle.getBundleInstallerdeprecated @@ -426,7 +449,7 @@ This is a system API and cannot be called by third-party applications. getBundleInstaller(callback: AsyncCallback<BundleInstaller>): void; -Obtains the installation package information. This API uses an asynchronous callback to return the result. +Obtains the installation package. This API uses an asynchronous callback to return the result. **Required permissions** @@ -444,8 +467,19 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------- | -| callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Yes | Callback used to return the installation package information.| +| callback | AsyncCallback<[BundleInstaller](js-apis-bundle-BundleInstaller.md)> | Yes | Callback used to return the installation package.| + +**Example** +```ts +bundle.getBundleInstaller((err, data) => { + if (err.code == 0) { + console.error('getBundleInstaller failed.'); + } else { + console.info('getBundleInstaller successfully'); + } +}); +``` ## bundle.cleanBundleCacheFiles8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles) instead. @@ -470,9 +504,23 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.cleanBundleCacheFiles(bundleName, err => { + if (err) { + console.error('cleanBundleCacheFiles failed.'); + } else { + console.info('cleanBundleCacheFiles successfully.'); + } +}); +``` + ## bundle.cleanBundleCacheFiles8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.cleanBundleCacheFiles](js-apis-bundleManager.md#bundlemanagercleanbundlecachefiles) instead. @@ -497,7 +545,7 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------- | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** @@ -505,6 +553,18 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.cleanBundleCacheFiles(bundleName).then(()=> { + console.info('cleanBundleCacheFiles successfully.'); +}).catch(err=> { + console.error('cleanBundleCacheFiles failed.'); +}); +``` + ## bundle.setApplicationEnabled8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.setApplicationEnabled](js-apis-bundleManager.md#bundlemanagersetapplicationenabled) instead. @@ -527,11 +587,25 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------- | ---- | ----------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------- | ---- |--------------------------------| +| bundleName | string | Yes | Bundle name of the application. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundle.setApplicationEnabled(bundleName, false, err => { + if (err) { + console.error('setApplicationEnabled failed.'); + } else { + console.info('setApplicationEnabled successfully.'); + } +}); +``` ## bundle.setApplicationEnabled8+ deprecated @@ -555,9 +629,9 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------- | ---- | ----------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- |------------------------------| +| bundleName | string | Yes | Bundle name of the application. | | isEnable | boolean | Yes | Whether to enable the application. The value **true** means to enable the application, and **false** means the opposite.| **Return value** @@ -566,6 +640,18 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let bundleName = "com.example.myapplication"; + +bundleManager.setApplicationEnabled(bundleName, false).then(()=> { + console.info('setApplicationEnabled successfully.'); +}).catch(err=> { + console.error('setApplicationEnabled failed.'); +}); +``` + ## bundle.setAbilityEnabled8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.setAbilityEnabled](js-apis-bundleManager.md#bundlemanagersetabilityenabled) instead. @@ -627,6 +713,28 @@ This is a system API and cannot be called by third-party applications. | ------------- | ------------------------------------ | | Promise\ | Promise that returns no value.| +**Example** + +```ts +let flag = bundle.BundleFlag.GET_ABILITY_INFO_WITH_PERMISSION; +let userId = 100; +let want = { + bundleName : "com.example.myapplication", + abilityName : "com.example.myapplication.MainAbility" +}; + +bundle.getAbilityInfo(want, flag, userId).then((abilityInfo) => { + console.info('getAbilityInfo successfully. Data: ' + JSON.stringify(abilityInfo)); + + bundle.setAbilityEnabled(abilityInfo, false).then(data => { + console.info('setAbilityEnabled successfully.'); + }).catch(err => { + console.error('setAbilityEnabled failed:' + JSON.stringify(err)); + }) +}).catch(error => { + console.error('getAbilityInfo failed. Cause: ' + JSON.stringify(error)); +}); +``` ## bundle.getPermissionDef8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef) instead. @@ -654,6 +762,19 @@ This is a system API and cannot be called by third-party applications. | permissionName | string | Yes | Name of the permission. | | callback | AsyncCallback<[PermissionDef](js-apis-bundle-PermissionDef)> | Yes | Callback used to return the permission details.| +**Example** + +```ts +let permission = "ohos.permission.GET_BUNDLE_INFO"; +bundleManager.getPermissionDef(permission, (err, data) => { + if (err) { + console.error('getPermissionDef failed:' + err.message); + } else { + console.info('getPermissionDef successfully:' + JSON.stringify(data)); + } +}); +``` + ## bundle.getPermissionDef8+ deprecated > This API is deprecated since API version 9. You are advised to use [bundleManager.getPermissionDef](js-apis-bundleManager.md#bundlemanagergetpermissiondef) instead. @@ -686,6 +807,16 @@ This is a system API and cannot be called by third-party applications. | ------------------------------------------------------ | ------------------------------------------------------ | | Promise<[PermissionDef](js-apis-bundle-PermissionDef)> | Promise used to return the permission details.| +**Example** + +```ts +let permissionName = "ohos.permission.GET_BUNDLE_INFO"; +bundle.getPermissionDef(permissionName).then((data) => { + console.info('getPermissionDef successfully. Data: ' + JSON.stringify(data)); +}).catch(error => { + console.error('getPermissionDef failed. Cause: ' + error.message); +}); +``` ## bundle.getAllApplicationInfodeprecated @@ -707,8 +838,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| -| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -718,7 +849,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleFlags = 8; let userId = 100; bundle.getAllApplicationInfo(bundleFlags, userId) @@ -735,7 +866,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId) getAllApplicationInfo(bundleFlags: number, userId: number, callback: AsyncCallback>): void -Obtains the information about all applications of the specified user. This API uses an asynchronous callback to return the result. +Obtains the information about all applications. This API uses an asynchronous callback to return the result. **Required permissions** @@ -749,14 +880,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** -```js -let bundleFlags = 8; +```ts +let bundleFlags = bundle.BundleFlag.GET_APPLICATION_INFO_WITH_PERMISSION; let userId = 100; bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { if (err) { @@ -774,7 +905,7 @@ bundle.getAllApplicationInfo(bundleFlags, userId, (err, data) => { getAllApplicationInfo(bundleFlags: number, callback: AsyncCallback>) : void; -Obtains the information about all applications. This API uses an asynchronous callback to return the result. +Obtains the information about all applications of the current user. This API uses an asynchronous callback to return the result. **Required permissions** @@ -788,13 +919,13 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| bundleFlags | number | Yes | Type of information that will be returned. For details about the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| | callback | AsyncCallback> | Yes | Callback used to return the application information. | **Example** -```js -let bundleFlags = 8; +```ts +let bundleFlags = bundle.BundleFlag.GET_APPLICATION_INFO_WITH_PERMISSION; bundle.getAllApplicationInfo(bundleFlags, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -820,8 +951,8 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| hapFilePath | string | Yes | Path where the HAP file is stored. The absolute path of the application and the data directory sandbox path are supported.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| **Return value** | Type | Description | @@ -830,8 +961,8 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js -let hapFilePath = "/data/xxx/test.hap"; +```ts +let hapFilePath = "/data/storage/el2/base/test.hap"; let bundleFlags = 0; bundle.getBundleArchiveInfo(hapFilePath, bundleFlags) .then((data) => { @@ -857,14 +988,14 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ------------ | -| hapFilePath | string | Yes | Path where the HAP file is stored. The path should point to the relative directory of the current application's data directory.| -| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| hapFilePath | string | Yes | Path where the HAP file is stored.. The absolute path of the application and the data directory sandbox path are supported.| +| bundleFlags | number | Yes | Flags used to specify information contained in the **BundleInfo** object that will be returned. For details about the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| | callback| AsyncCallback\<[BundleInfo](js-apis-bundle-BundleInfo.md)> | Yes | Callback used to return the information about the bundles.| **Example** -```js -let hapFilePath = "/data/xxx/test.hap"; +```ts +let hapFilePath = "/data/storage/el2/base/test.hap"; let bundleFlags = 0; bundle.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { if (err) { @@ -884,6 +1015,8 @@ getAbilityInfo(bundleName: string, abilityName: string): Promise\ Obtains the ability information based on a given bundle name and ability name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -894,9 +1027,9 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory | Description | +| ----------- | ------ | ---- |------------| +| bundleName | string | Yes | Bundle name of the application. | | abilityName | string | Yes | Ability name.| **Return value** @@ -907,7 +1040,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName) @@ -926,6 +1059,8 @@ getAbilityInfo(bundleName: string, abilityName: string, callback: AsyncCallback\ Obtains the ability information based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -936,15 +1071,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory | Description | +| ----------- | ------------ | ---- |----------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name. | | callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName, (err, data) => { @@ -964,6 +1099,8 @@ getAbilityLabel(bundleName: string, abilityName: string): Promise\ Obtains the application name based on a given bundle name and ability name. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -974,10 +1111,10 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ------ | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| +| Name | Type | Mandatory | Description | +|-------------|--------|-----|------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name.| **Return value** @@ -987,7 +1124,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityLabel(bundleName, abilityName) @@ -1006,6 +1143,8 @@ getAbilityLabel(bundleName: string, abilityName: string, callback : AsyncCallbac Obtains the application name based on a given bundle name and ability name. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **Required permissions** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -1016,15 +1155,15 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory | Description | -| ----------- | ---------------------- | ---- | ---------------- | -| bundleName | string | Yes | Bundle name of an application. | -| abilityName | string | Yes | Ability name.| -| callback | AsyncCallback\ | Yes | Callback used to return the application name. | +| Name | Type | Mandatory | Description | +|-------------|------------------------|-----|-------------------------| +| bundleName | string | Yes | Bundle name of the application. | +| abilityName | string | Yes | Ability name. | +| callback | AsyncCallback\ | Yes | Callback used to return the application name.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityLabel(bundleName, abilityName, (err, data) => { @@ -1062,7 +1201,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ @@ -1095,7 +1234,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityInfo(bundleName, abilityName).then((abilityInfo)=>{ @@ -1125,17 +1264,17 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** | Type | Description | | ----------------- | ------------------------- | -| Promise\ | Promise used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned.| +| Promise\ | Promise used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName) .then((data) => { @@ -1161,12 +1300,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ----------------------- | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| -| callback | AsyncCallback\ | Yes | Callback used to return whether the ability is enabled. If the ability is enabled, **true** will be returned; otherwise, **false** will be returned. | +| bundleName | string | Yes | Bundle name of the application.| +| callback | AsyncCallback\ | Yes | Callback used to return whether the application is enabled. If the application is enabled, **true** will be returned; otherwise, **false** will be returned. | **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.isApplicationEnabled(bundleName, (err, data) => { if (err) { @@ -1185,6 +1324,8 @@ queryAbilityByWant(want: Want, bundleFlags: number, userId?: number): Promise> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| +| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The value must be greater than or equal to 0. | +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** -```js +```ts let bundleFlags = 0; let userId = 100; let want = { @@ -1277,6 +1420,8 @@ queryAbilityByWant(want: Want, bundleFlags: number, callback: AsyncCallback> | Yes | Callback used to return the ability information. | +| Name | Type | Mandatory | Description | +|-------------|---------------------------------------------------------------------|-----|-------------------------------------------------------------------------| +| want | [Want](js-apis-application-want.md) | Yes | Want that contains the bundle name. | +| bundleFlags | number | Yes | Ability information to be returned. For details about the available enumerated values, see the ability information flags in [BundleFlag](#bundleflag).| +| callback | AsyncCallback> | Yes | Callback used to return the ability information. | **Example** -```js +```ts let bundleFlags = 0; let want = { bundleName : "com.example.myapplication", @@ -1332,16 +1477,16 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------ | -| bundleName | string | Yes | Bundle name of an application.| +| bundleName | string | Yes | Bundle name of the application.| **Return value** | Type | Description | | -------------- | -------------------------------------- | -| Promise\<[Want](js-apis-application-Want.md)> | Promise used to return the **Want** object.| +| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the **Want** object.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.getLaunchWantForBundle(bundleName) .then((data) => { @@ -1371,12 +1516,12 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | --------------------------------------------------- | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the **Want** object.| +| bundleName | string | Yes | Bundle name of the application. | +| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the **Want** object.| **Example** -```js +```ts let bundleName = "com.example.myapplication"; bundle.getLaunchWantForBundle(bundleName, (err, data) => { if (err) { @@ -1413,7 +1558,7 @@ SystemCapability.BundleManager.BundleFramework **Example** -```js +```ts let uid = 20010005; bundle.getNameForUid(uid) .then((data) => { @@ -1437,14 +1582,14 @@ SystemCapability.BundleManager.BundleFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ----------------------------------------------- | -| uid | number | Yes | UID based on which the bundle name is to obtain. | +| Name | Type | Mandatory | Description | +|----------|------------------------|-----|----------------------------| +| uid | number | Yes | UID based on which the bundle name is to obtain. | | callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** -```js +```ts let uid = 20010005; bundle.getNameForUid(uid, (err, data) => { if (err) { @@ -1464,6 +1609,8 @@ getAbilityIcon(bundleName: string, abilityName: string): Promise\ | Yes | Callback used to return the [pixel map](js-apis-image.md).| **Example** -```js +```ts let bundleName = "com.example.myapplication"; let abilityName = "com.example.myapplication.MainAbility"; bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { @@ -1536,7 +1686,7 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { ``` ## InstallErrorCodedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1567,7 +1717,11 @@ bundle.getAbilityIcon(bundleName, abilityName, (err, data) => { > This API is deprecated since API version 9. You are advised to use [bundleManager.BundleFlag](js-apis-bundleManager.md#bundleflag) instead. -Enumerates bundle flags. +Enumerates the bundle flags, which indicate the type of bundle information to obtain. + +If an API does not match the flag, the flag is ignored. For example, using **GET_ABILITY_INFO_WITH_PERMISSION** to obtain the application information does not affect the result. + +Flags can be used together. For example, you can use the combination of **GET_APPLICATION_INFO_WITH_PERMISSION** and **GET_APPLICATION_INFO_WITH_DISABLE** to obtain the result that contains both application permission information and disabled application information. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1587,9 +1741,9 @@ Enumerates bundle flags. | GET_ALL_APPLICATION_INFO | 0xFFFF0000 | Obtains all application information. | ## BundleOptionsdeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Describes the bundle options. +Options that contain the user ID. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1601,7 +1755,7 @@ Describes the bundle options. > This API is deprecated since API version 9. You are advised to use [bundleManager.AbilityType](js-apis-bundleManager.md#abilitytype) instead. -Enumerates ability types. +Enumerates the ability types. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1630,7 +1784,7 @@ Enumerates display orientations. > This API is deprecated since API version 9. You are advised to use [bundleManager.LaunchType](js-apis-bundleManager.md#launchtype) instead. -Enumerates launch modes. +Enumerates the ability launch modes. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1640,9 +1794,9 @@ Enumerates launch modes. | STANDARD | 1 | The ability can have multiple instances. | ## AbilitySubTypedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Enumerates ability subtypes. +Enumerates the ability subtypes. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1652,9 +1806,9 @@ Enumerates ability subtypes. | CA | 1 | Ability that has a UI.| ## ColorModedeprecated -> This API is deprecated since API version 9. You are not advised to use it anymore. +> This API is deprecated since API version 9. You are not advised using it anymore. -Enumerates color modes. +Enumerates the color modes of applications and widgets. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -1669,7 +1823,7 @@ Enumerates color modes. > This API is deprecated since API version 9. You are advised to use [bundleManager.PermissionGrantState](js-apis-bundleManager.md#permissiongrantstate) instead. -Enumerates permission grant states. +Enumerates the permission grant states. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index 7732457b6f32608db4c51f55e1cfa5ff0ee28ae8..a55ab990ef39072d83989526e66723eab794ca63 100644 --- a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -1,4 +1,4 @@ -# EnterpriseAdminExtensionAbility +# @ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility) The **EnterpriseAdminExtensionAbility** module provides Extension abilities for enterprise administrators. @@ -13,7 +13,7 @@ To have the capabilities provided by the module, for example, receiving the appl ## Modules to Import ```ts -import EnterpriseAdminExtensionAbility from '@ohos.EnterpriseAdminExtensionAbility' +import EnterpriseAdminExtensionAbility from '@ohos.enterprise.EnterpriseAdminExtensionAbility' ``` ## EnterpriseAdminExtensionAbility.onAdminEnabled @@ -24,6 +24,8 @@ Called when an enterprise administrator is enabled. **System capability**: SystemCapability.Customization.EnterpriseDeviceManager +**System API**: This is a system API. + **Example** ```ts @@ -41,6 +43,8 @@ Called when an enterprise administrator is disabled. **System capability**: SystemCapability.Customization.EnterpriseDeviceManager +**System API**: This is a system API. + **Example** ```ts @@ -58,6 +62,8 @@ Called when a bundle is added. **System capability**: SystemCapability.Customization.EnterpriseDeviceManager +**System API**: This is a system API. + **Parameters** | Parameter | Type | Mandatory | Description | @@ -82,6 +88,8 @@ Called when a bundle is removed. **System capability**: SystemCapability.Customization.EnterpriseDeviceManager +**System API**: This is a system API. + **Parameters** | Parameter | Type | Mandatory | Description | diff --git a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md index e7be32c9b840dbe67f99e120e3798ad5ecd9fcd4..a22f7b48a977066e085da4b9ddfcdeb24f21463f 100644 --- a/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-WorkSchedulerExtensionAbility.md @@ -1,4 +1,4 @@ -# Work Scheduler Callbacks +# @ohos.WorkSchedulerExtensionAbility (Work Scheduler Callbacks) The **WorkSchedulerExtensionAbility** module provides callbacks for Work Scheduler tasks. diff --git a/en/application-dev/reference/apis/js-apis-ability-ability.md b/en/application-dev/reference/apis/js-apis-ability-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..37bf04c704a91f0580fddf99b14f9f52fb94d683 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-ability-ability.md @@ -0,0 +1,39 @@ +# @ohos.ability.ability (Ability) + +The **Ability** module provides all level-2 module APIs for developers to export. + +> **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 FA model. + +## Modules to Import + +```ts +import ability from '@ohos.ability.ability' +``` + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| DataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | No | Level-2 module **DataAbilityHelper**. | +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | No | Level-2 module **PacMap**.| +| DataAbilityOperation | [DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md) | No | Level-2 module **DataAbilityOperation**.| +| DataAbilityResult | [DataAbilityResult](js-apis-inner-ability-dataAbilityResult.md) | No | Level-2 module **DataAbilityResult**.| +| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | No | Level-2 module **AbilityResult**.| +| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | No | Level-2 module **ConnectOptions**.| +| StartAbilityParameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | No | Level-2 module **StartAbilityParameter**.| + +**Example** +```ts +import ability from '@ohos.ability.ability'; + +let dataAbilityHelper: ability.DataAbilityHelper; +let pacMap: ability.PacMap; +let dataAbilityOperation: ability.DataAbilityOperation; +let dataAbilityResult: ability.DataAbilityResult; +let abilityResult: ability.AbilityResult; +let connectOptions: ability.ConnectOptions; +let startAbilityParameter: ability.StartAbilityParameter; +``` 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 40110bb6f928b5d76a9f916340cc7fce07975152..d345bbb9db0739da16156ecfc0bd4fe344989149 100644 --- a/en/application-dev/reference/apis/js-apis-ability-context.md +++ b/en/application-dev/reference/apis/js-apis-ability-context.md @@ -14,10 +14,10 @@ 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**. ```ts -import Ability from '@ohos.app.ability.UIAbility'; +import UIAbility from '@ohos.app.ability.UIAbility'; - let context = undefined; -class MainAbility extends Ability { +let context = undefined; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { context = this.context; } @@ -30,9 +30,9 @@ class MainAbility extends Ability { | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| abilityInfo | AbilityInfo | Yes| No| Ability information.| -| currentHapModuleInfo | HapModuleInfo | Yes| No| Information about the current HAP.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration information.| +| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| Ability information.| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| Information about the current HAP.| +| config | [Configuration](js-apis-application-configuration.md) | Yes| No| Configuration information.| ## AbilityContext.startAbility @@ -40,27 +40,33 @@ startAbility(want: Want, callback: AsyncCallback<void>): void; Starts an ability. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; @@ -89,30 +95,36 @@ startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void& Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0 @@ -142,14 +154,19 @@ startAbility(want: Want, options?: StartOptions): Promise<void>; Starts an ability. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Return value** @@ -161,14 +178,15 @@ Starts an ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; var options = { @@ -198,7 +216,12 @@ Starts an ability. This API uses a promise to return the result. startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; -Starts an ability. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -206,23 +229,24 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -248,7 +272,12 @@ Starts an ability. This API uses an asynchronous callback to return the result w startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; -Starts an ability with start options specified. This API uses an asynchronous callback to return the result when the ability is terminated. +Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -256,24 +285,25 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want |[Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Yes| Callback used to return the result.| +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0, @@ -303,7 +333,12 @@ Starts an ability with start options specified. This API uses an asynchronous ca startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; -Starts an ability. This API uses a promise to return the result when the ability is terminated. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#abilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -311,28 +346,29 @@ Starts an ability. This API uses a promise to return the result when the ability | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<[AbilityResult](js-apis-featureAbility.md#abilityresult)> | Promise used to return the result.| +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { - bundleName: "com.example.myapp", + bundleName: "com.example.myapplication", abilityName: "MyAbility" }; var options = { @@ -361,9 +397,14 @@ Starts an ability. This API uses a promise to return the result when the ability startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts an ability. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -373,24 +414,25 @@ Starts an ability. This API uses an asynchronous callback to return the result w | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| callback | AsyncCallback\ | Yes| Callback used to return the result.| +| callback | AsyncCallback\<[AbilityResult](js-apis-inner-ability-abilityResult.md)\> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -418,9 +460,14 @@ Starts an ability. This API uses an asynchronous callback to return the result w startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; -Starts an ability with start options specified. This API uses an asynchronous callback to return the result when the account of the ability is destroyed. +Starts an ability with the start options and account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -430,25 +477,26 @@ Starts an ability with start options specified. This API uses an asynchronous ca | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -479,9 +527,14 @@ Starts an ability with start options specified. This API uses an asynchronous ca startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; -Starts an ability with start options specified. This API uses a promise to return the result when the account of the ability is destroyed. +Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -491,30 +544,31 @@ Starts an ability with start options specified. This API uses a promise to retur | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<AbilityResult> | Promise used to return the result.| +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -543,7 +597,7 @@ Starts an ability with start options specified. This API uses a promise to retur startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -553,23 +607,24 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -594,7 +649,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -604,22 +659,23 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -644,9 +700,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +Starts a ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -656,7 +712,7 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -664,16 +720,17 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -699,9 +756,9 @@ Starts a new Service Extension ability with the account ID specified. This API u startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +Starts a ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -711,23 +768,24 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -752,7 +810,7 @@ Starts a new Service Extension ability with the account ID specified. This API u stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -762,28 +820,35 @@ Stops a Service Extension ability in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { + this.context.startAbility(want, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbility(want, (error) => { - if (error.code) { + if (error.code != 0) { // Process service logic errors. console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + ' error.message: ' + JSON.stringify(error.message)); @@ -803,7 +868,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -813,25 +878,32 @@ Stops a Service Extension ability in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { + this.context.startAbility(want, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbility(want) .then((data) => { // Carry out normal service processing. @@ -853,9 +925,9 @@ Stops a Service Extension ability in the same application. This API uses a promi stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -865,7 +937,7 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -873,20 +945,27 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { if (error.code) { // Process service logic errors. @@ -908,9 +987,9 @@ Stops a Service Extension ability in the same application with the account ID sp stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -920,27 +999,34 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code != 0) { + console.log("start ability fail, err: " + JSON.stringify(err)); + } + }) + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) .then((data) => { // Carry out normal service processing. @@ -976,8 +1062,9 @@ Terminates this ability. This API uses an asynchronous callback to return the re | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1013,8 +1100,9 @@ Terminates this ability. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1034,7 +1122,7 @@ Terminates this ability. This API uses a promise to return the result. terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; -Terminates this ability. This API uses an asynchronous callback to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1042,15 +1130,16 @@ Terminates this ability. This API uses an asynchronous callback to return the ab | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1088,8 +1177,7 @@ Terminates this ability. This API uses an asynchronous callback to return the ab ## AbilityContext.terminateSelfWithResult terminateSelfWithResult(parameter: AbilityResult): Promise<void>; - -Terminates this ability. This API uses a promise to return the ability result information. It is used together with **startAbilityForResult**. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#abilitycontextstartabilityforresult), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1097,7 +1185,7 @@ Terminates this ability. This API uses a promise to return the ability result in | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| parameter | [AbilityResult](js-apis-featureAbility.md#abilityresult) | Yes| Information returned to the caller.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| **Return value** @@ -1109,8 +1197,9 @@ Terminates this ability. This API uses a promise to return the ability result in | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1153,12 +1242,14 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to **System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System API**: This is a system API and cannot be called by third-party applications. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Parameters for the connection.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Parameters for the connection.| **Return value** @@ -1170,16 +1261,17 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { onConnect(elementName, remote) { console.log('----------- onConnect -----------') }, @@ -1202,9 +1294,9 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; -Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect this ability to another ability with the account ID specified. +Uses the **AbilityInfo.AbilityType.SERVICE** template to connect this ability to another ability with the account ID specified. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1214,9 +1306,9 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Parameters for the connection.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Parameters for the connection.| **Return value** @@ -1228,16 +1320,17 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1280,13 +1373,14 @@ Disconnects a connection. This API uses a promise to return the result. | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts - // connection is the return value of connectAbility. + // connection is the return value of connectServiceExtensionAbility. var connection = 1; try { @@ -1326,8 +1420,9 @@ Disconnects a connection. This API uses an asynchronous callback to return the r | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** @@ -1359,6 +1454,11 @@ startAbilityByCall(want: Want): Promise<Caller>; Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -1367,7 +1467,7 @@ Starts an ability in the foreground or background and obtains the caller object | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| +| want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| **Return value** @@ -1386,7 +1486,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }; @@ -1417,7 +1517,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "", parameters: { "ohos.aafwk.param.callAbilityToForeground": true @@ -1448,7 +1548,12 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1458,7 +1563,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -1466,16 +1571,17 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -1504,7 +1610,12 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1514,25 +1625,26 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1564,7 +1676,12 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Starts an ability with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1574,24 +1691,25 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-application-startOptions.md) | No| Parameters used for starting the ability.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -1616,65 +1734,6 @@ Starts an ability with the account ID specified. This API uses a promise to retu } ``` -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; - -Requests permissions from the user by displaying a dialog box. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| -| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions,(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); - }); - - ``` - - -## AbilityContext.requestPermissionsFromUser - -requestPermissionsFromUser(permissions: Array<string>) : Promise<PermissionRequestResult>; - -Requests permissions from the user by displaying a dialog box. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| permissions | Array<string> | Yes| Permissions to request.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| - -**Example** - - ```ts - var permissions=['com.example.permission'] - this.context.requestPermissionsFromUser(permissions).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - - ``` - - ## AbilityContext.setMissionLabel setMissionLabel(label: string, callback:AsyncCallback<void>): void; @@ -1694,7 +1753,7 @@ Sets a label for this ability in the mission. This API uses an asynchronous call ```ts this.context.setMissionLabel("test",(result) => { - console.log('requestPermissionsFromUserresult:' + JSON.stringify(result)); + console.log('setMissionLabel result:' + JSON.stringify(result)); }); ``` @@ -1742,7 +1801,7 @@ Sets an icon for this ability in the mission. This API uses an asynchronous call | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | image.PixelMap | Yes| Icon of the ability to set.| +| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** @@ -1784,7 +1843,7 @@ Sets an icon for this ability in the mission. This API uses a promise to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| icon | image.PixelMap | Yes| Icon of the ability to set.| +| icon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Icon of the ability to set.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-DataUriUtils.md b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md similarity index 71% rename from en/application-dev/reference/apis/js-apis-DataUriUtils.md rename to en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md index 18cfa0cdc0c54ea8e8aa85fc43fcf61b3d63fc7a..f1301ad877dcf5a0bd2fec5ad5be10452ee88716 100644 --- a/en/application-dev/reference/apis/js-apis-DataUriUtils.md +++ b/en/application-dev/reference/apis/js-apis-ability-dataUriUtils.md @@ -1,6 +1,6 @@ -# DataUriUtils +# @ohos.ability.dataUriUtils (dataUriUtils) -The **DataUriUtils** module provides APIs to handle utility classes for objects using the **DataAbilityHelper** schema. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. +The **DataUriUtils** module provides APIs to process URI objects. You can use the APIs to attach an ID to the end of a given URI and obtain, delete, or update the ID attached to the end of a given URI. This module will be replaced by the **app.ability.dataUriUtils** module in the near future. You are advised to use the **[@ohos.app.ability.dataUriUtils](js-apis-app-ability-dataUriUtils.md)** module. > **NOTE** > @@ -8,7 +8,7 @@ The **DataUriUtils** module provides APIs to handle utility classes for objects ## Modules to Import -```js +```ts import dataUriUtils from '@ohos.ability.dataUriUtils'; ``` @@ -24,18 +24,18 @@ Obtains the ID attached to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object from which the ID is to be obtained.| +| uri | string | Yes | Target URI object.| **Return value** | Type | Description | | ------ | ------------------------ | -| number | ID obtained from the URI object.| +| number | ID obtained.| **Example** -```js -dataUriUtils.getId("com.example.dataUriUtils/1221") +```ts +let id = dataUriUtils.getId("com.example.dataUriUtils/1221"); ``` @@ -52,7 +52,7 @@ Attaches an ID to the end of a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | --------------------------- | -| uri | string | Yes | URI object to which an ID is to be attached.| +| uri | string | Yes | Target URI object.| | id | number | Yes | ID to be attached. | **Return value** @@ -63,11 +63,11 @@ Attaches an ID to the end of a given URI. **Example** -```js -var idint = 1122; -dataUriUtils.attachId( +```ts +let id = 1122; +let uri = dataUriUtils.attachId( "com.example.dataUriUtils", - idint, + id, ) ``` @@ -95,8 +95,8 @@ Deletes the ID from the end of a given URI. **Example** -```js -dataUriUtils.deleteId("com.example.dataUriUtils/1221") +```ts +let uri = dataUriUtils.deleteId("com.example.dataUriUtils/1221") ``` @@ -113,7 +113,7 @@ Updates the ID in a given URI. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------- | -| uri | string | Yes | URI object to be updated.| +| uri | string | Yes | Target URI object.| | id | number | Yes | New ID. | **Return value** @@ -124,10 +124,10 @@ Updates the ID in a given URI. **Example** -```js -var idint = 1122; -dataUriUtils.updateId( - "com.example.dataUriUtils", - idint +```ts +let id = 1122; +let uri = dataUriUtils.updateId( + "com.example.dataUriUtils/1221", + id ) ``` diff --git a/en/application-dev/reference/apis/js-apis-ability-errorCode.md b/en/application-dev/reference/apis/js-apis-ability-errorCode.md index 6a131521d3c447cfb2df65b53a592c5be89678be..dc0e8ae8928a9191f70b555e84a3f58b09e4b876 100644 --- a/en/application-dev/reference/apis/js-apis-ability-errorCode.md +++ b/en/application-dev/reference/apis/js-apis-ability-errorCode.md @@ -1,6 +1,6 @@ -# ErrorCode +# @ohos.ability.errorCode (ErrorCode) -The **ErrorCode** module defines the error codes that can be used when the ability is started. +The **ErrorCode** module defines the error codes that may be returned when an ability is started. > **NOTE** > @@ -8,19 +8,19 @@ The **ErrorCode** module defines the error codes that can be used when the abili ## Modules to Import -``` +```ts import errorCode from '@ohos.ability.errorCode' ``` ## ErrorCode -Defines the error codes used when the ability is started. +Enumerates the error codes that may be returned when an ability is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ------------------------------ | ---- | ---------------------------------------- | -| NO_ERROR | 0 | No error occurs. | +| NO_ERROR | 0 | No error. | | INVALID_PARAMETER | -1 | Invalid parameter.| | ABILITY_NOT_FOUND | -2 | The ability is not found.| | PERMISSION_DENY | -3 | Permission denied. | diff --git a/en/application-dev/reference/apis/js-apis-featureAbility.md b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md similarity index 63% rename from en/application-dev/reference/apis/js-apis-featureAbility.md rename to en/application-dev/reference/apis/js-apis-ability-featureAbility.md index 66999a98279dc43aa0fee542883a6ed70ad5ee8d..b527edfcf7911fec83b4e8d5a01a2761772e95f1 100644 --- a/en/application-dev/reference/apis/js-apis-featureAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-featureAbility.md @@ -1,6 +1,6 @@ -# FeatureAbility +# @ohos.ability.featureAbility (FeatureAbility) -The **FeatureAbility** module provides a UI for interacting with users. You can use APIs of this module to start a new ability, obtain the **dataAbilityHelper**, set a Page ability, obtain the window corresponding to this ability, and connect to a Service ability. +The **FeatureAbility** module provides APIs that enable user interaction. You can use the APIs to start or terminate an ability, obtain a **dataAbilityHelper** object, obtain the window corresponding to the current ability, and connect to or disconnect from a ServiceAbility. > **NOTE** > @@ -9,11 +9,11 @@ The **FeatureAbility** module provides a UI for interacting with users. You can ## Constraints -APIs of the **FeatureAbility** module can be called only by Page abilities. +The APIs of the **FeatureAbility** module can be called only by PageAbilities. ## Modules to Import -``` +```ts import featureAbility from '@ohos.ability.featureAbility'; ``` @@ -23,18 +23,23 @@ startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\) Starts an ability. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbility( @@ -48,7 +53,7 @@ featureAbility.startAbility( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri: "" }, }, @@ -66,17 +71,28 @@ startAbility(parameter: StartAbilityParameter): Promise\ Starts an ability. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the result.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbility( @@ -90,7 +106,7 @@ featureAbility.startAbility( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri: "" }, } @@ -105,6 +121,12 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper Obtains a **dataAbilityHelper** object. +Observe the following when using this API: + - To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**). + - If an application running in the background needs to call this API to access a DataAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -117,11 +139,11 @@ Obtains a **dataAbilityHelper** object. | Type | Description | | ----------------- | ------------------------------- | -| DataAbilityHelper | A utility class used to help other abilities access the Data ability.| +| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access the Data ability.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" @@ -132,7 +154,12 @@ var dataAbilityHelper = featureAbility.acquireDataAbilityHelper( startAbilityForResult(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts an ability. This API uses an asynchronous callback to return the execution result when the ability is destroyed. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -140,12 +167,12 @@ Starts an ability. This API uses an asynchronous callback to return the executio | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| -| callback | AsyncCallback\<[AbilityResult](#abilityresult)> | Yes | Callback used to return the result. | +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| +| callback | AsyncCallback\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes | Callback used to return the result. | **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbilityForResult( @@ -159,7 +186,7 @@ featureAbility.startAbilityForResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"" }, }, @@ -173,7 +200,12 @@ featureAbility.startAbilityForResult( startAbilityForResult(parameter: StartAbilityParameter): Promise\ -Starts an ability. This API uses a promise to return the execution result when the ability is destroyed. +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#featureabilityterminateselfwithresult7) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -181,17 +213,17 @@ Starts an ability. This API uses a promise to return the execution result when t | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | ------------- | -| parameter | [StartAbilityParameter](#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| **Return value** | Type | Description | | ---------------------------------------- | ------- | -| Promise\<[AbilityResult](#abilityresult)> | Promised returned with the execution result.| +| Promise\<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.startAbilityForResult( @@ -205,7 +237,7 @@ featureAbility.startAbilityForResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { @@ -229,7 +261,7 @@ featureAbility.startAbilityForResult( terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -237,12 +269,12 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | -------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to destroy.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.terminateSelfWithResult( @@ -257,7 +289,7 @@ featureAbility.terminateSelfWithResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { mykey0: 2222, @@ -281,7 +313,7 @@ featureAbility.terminateSelfWithResult( terminateSelfWithResult(parameter: AbilityResult): Promise\ -Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result. +Terminates this ability. If the ability is started by calling [startAbilityForResult](#featureabilitystartabilityforresult7), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -289,7 +321,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th | Name | Type | Mandatory | Description | | --------- | ------------------------------- | ---- | ------------- | -| parameter | [AbilityResult](#abilityresult) | Yes | Ability to destroy.| +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes | Result returned after the ability is terminated.| **Return value** @@ -299,7 +331,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; import wantConstant from '@ohos.ability.wantConstant'; featureAbility.terminateSelfWithResult( @@ -314,7 +346,7 @@ featureAbility.terminateSelfWithResult( deviceId: "", bundleName: "com.example.myapplication", /* In the FA model, abilityName consists of package and ability names. */ - abilityName: "com.example.entry.secondAbility", + abilityName: "com.example.myapplication.secondAbility", uri:"", parameters: { mykey0: 2222, @@ -345,11 +377,11 @@ Checks whether the main window of this ability has the focus. This API uses an a | Name | Type | Mandatory | Description | | -------- | ----------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
If the main window has the focus, **true** is returned. Otherwise, **false** is returned.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus((err, data) => { console.info("hasWindowFocus err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); @@ -368,11 +400,11 @@ Checks whether the main window of this ability has the focus. This API uses a pr | Type | Description | | ----------------- | ------------------------------------- | -| Promise\ | Returns **true** if the main window of this ability has the focus; returns **false** otherwise.| +| Promise\ | Promise used to return the result. If the main window has the focus, **true** is returned. Otherwise, **false** is returned.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.hasWindowFocus().then((data) => { console.info("hasWindowFocus data: " + JSON.stringify(data)); @@ -383,7 +415,7 @@ featureAbility.hasWindowFocus().then((data) => { getWant(callback: AsyncCallback\): void -Obtains the **Want** object sent from this ability. This API uses an asynchronous callback to return the result. +Obtains the Want corresponding to the ability to start. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -391,11 +423,11 @@ Obtains the **Want** object sent from this ability. This API uses an asynchronou | Name | Type | Mandatory | Description | | -------- | ----------------------------- | ---- | --------- | -| callback | AsyncCallback\<[Want](js-apis-application-Want.md)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[Want](js-apis-application-want.md)> | Yes | Callback used to return the Want.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant((err, data) => { console.info("getWant err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); @@ -406,7 +438,7 @@ featureAbility.getWant((err, data) => { getWant(): Promise\ -Obtains the **Want** object sent from this ability. This API uses a promise to return the result. +Obtains the Want corresponding to the ability to start. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -414,11 +446,11 @@ Obtains the **Want** object sent from this ability. This API uses a promise to r | Type | Description | | ----------------------- | ---------------- | -| Promise\<[Want](js-apis-application-Want.md)> | Promise used to return the result.| +| Promise\<[Want](js-apis-application-want.md)> | Promise used to return the Want.| **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.getWant().then((data) => { console.info("getWant data: " + JSON.stringify(data)); @@ -441,7 +473,7 @@ Obtains the application context. **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext() context.getBundleName((err, data) => { @@ -453,7 +485,7 @@ context.getBundleName((err, data) => { terminateSelf(callback: AsyncCallback\): void -Destroys this Page ability, with the result code and data sent to the caller. This API uses an asynchronous callback to return the result. +Terminates this ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -465,7 +497,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf( (err) => { @@ -478,7 +510,7 @@ featureAbility.terminateSelf( terminateSelf(): Promise\ -Destroys this Page ability, with the result code and data sent to the caller. This API uses a promise to return the result. +Terminates this ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -490,7 +522,7 @@ Destroys this Page ability, with the result code and data sent to the caller. Th **Example** -```javascript +```ts import featureAbility from '@ohos.ability.featureAbility'; featureAbility.terminateSelf().then((data) => { console.info("==========================>terminateSelf=======================>"); @@ -501,7 +533,13 @@ featureAbility.terminateSelf().then((data) => { connectAbility(request: Want, options:ConnectOptions): number -Connects this ability to a specific Service ability. This API uses an asynchronous callback to return the result. +Connects this ability to a ServiceAbility. + +Observe the following when using this API: + - To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).. + - If an application running in the background needs to call this API to connect to a ServiceAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -509,30 +547,18 @@ Connects this ability to a specific Service ability. This API uses an asynchrono | Name | Type | Mandatory | Description | | ------- | -------------- | ---- | --------------------- | -| request | [Want](js-apis-application-Want.md) | Yes | Service ability to connect.| -| options | [ConnectOptions](#connectoptions) | Yes | Callback used to return the result. | - -## ConnectOptions - -Describes the connection options. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable|Writable| Type | Mandatory | Description | -| ------------ | -- | -- | -------- | ---- | ------------------------- | -| onConnect7+ | Yes|No | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect7+ | Yes|No | function | Yes | Callback invoked when the connection fails. | -| onFailed7+ | Yes|No | function | Yes | Callback invoked when **connectAbility** fails to be called.| +| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. | **Return value** | Type | Description | | ------ | -------------------- | -| number | ID of the Service ability connected.| +| number | ID of the connected ServiceAbility. The ID starts from 0 and is incremented by 1 each time a connection is set up.| **Example** -```javascript +```ts import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ @@ -548,7 +574,7 @@ var connectId = featureAbility.connectAbility( { deviceId: "", bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -562,7 +588,7 @@ var connectId = featureAbility.connectAbility( disconnectAbility(connection: number, callback:AsyncCallback\): void -Disconnects this ability from a specific Service ability. This API uses an asynchronous callback to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -570,12 +596,12 @@ Disconnects this ability from a specific Service ability. This API uses an async | Name | Type | Mandatory | Description | | ---------- | -------------------- | ---- | ----------------------- | -| connection | number | Yes | ID of the Service ability to disconnect.| +| connection | number | Yes | ID of the ServiceAbility to disconnect.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```javascript +```ts import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ @@ -590,7 +616,7 @@ function onFailedCallback(code){ var connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -609,7 +635,7 @@ var result = featureAbility.disconnectAbility(connectId, disconnectAbility(connection: number): Promise\ -Disconnects this ability from a specific Service ability. This API uses a promise to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -617,7 +643,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis | Name | Type | Mandatory | Description | | ---------- | ------ | ---- | ----------------------- | -| connection | number | Yes | ID of the Service ability to disconnect.| +| connection | number | Yes | ID of the ServiceAbility to disconnect.| **Return value** @@ -627,7 +653,7 @@ Disconnects this ability from a specific Service ability. This API uses a promis **Example** -```javascript +```ts import rpc from '@ohos.rpc'; import featureAbility from '@ohos.ability.featureAbility'; function onConnectCallback(element, remote){ @@ -642,7 +668,7 @@ function onFailedCallback(code){ var connectId = featureAbility.connectAbility( { bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", + abilityName: "com.ix.ServiceAbility.ServiceAbilityA", }, { onConnect: onConnectCallback, @@ -671,11 +697,11 @@ Obtains the window corresponding to this ability. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ----------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the window.| +| callback | AsyncCallback\<[window.Window](js-apis-window.md#window)> | Yes | Callback used to return the window.| **Example** -```javascript +```ts featureAbility.getWindow((err, data) => { console.info("getWindow err: " + JSON.stringify(err) + "data: " + typeof(data)); }); @@ -693,150 +719,19 @@ Obtains the window corresponding to this ability. This API uses a promise to ret | Type | Description | | ----------------------- | ----------------------------- | -| Promise\ | Promise used to return the window.| +| Promise\<[window.Window](js-apis-window.md#window)> | Promise used to return the window.| **Example** -```javascript +```ts featureAbility.getWindow().then((data) => { console.info("getWindow data: " + typeof(data)); }); ``` -## ConnectOptions.onConnect7+ - -onConnect(elementName: ElementName, remote: rpc.IRemoteObject): void; - -Callback invoked when the connection is successful. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ----------------- | ---- | -------- | -| elementName | ElementName | Yes | Element name. | -| remote | rpc.IRemoteObject | Yes | RPC remote object.| - -**Example** - -```javascript -import rpc from '@ohos.rpc'; -import featureAbility from '@ohos.ability.featureAbility'; -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` - -## ConnectOptions.onDisconnect7+ - -onDisconnect(elementName: ElementName): void; - -Callback invoked when the connection fails. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ----------- | ---- | ---- | -| elementName | ElementName | Yes | Element name.| - -**Example** - -```javascript -import rpc from '@ohos.rpc'; -import featureAbility from '@ohos.ability.featureAbility'; -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` - -## ConnectOptions.onFailed7+ - -onFailed(code: number): void; - -Callback invoked when **connectAbility** fails to be called. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | --------- | -| code | number | Yes | Number type.| - -**Example** - -```javascript -import rpc from '@ohos.rpc'; -import featureAbility from '@ohos.ability.featureAbility'; -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); -} -function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) -} -function onFailedCallback(code){ - console.log('featureAbilityTest ConnectAbility onFailed errCode : ' + code) -} -var connectId = featureAbility.connectAbility( - { - deviceId: "", - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, -); -``` - - - - - ## AbilityWindowConfiguration -The value is obtained through the **featureAbility.AbilityWindowConfiguration** API. +Defines the window configuration corresponding to this ability. The configuration is obtained through **featureAbility.AbilityWindowConfiguration**. **Example** @@ -848,18 +743,18 @@ featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED | Name | Value | Description | | ---------------------------------------- | ---- | ---------------------------------------- | -| WINDOW_MODE_UNDEFINED7+ | 0 | The Page ability is in an undefined window display mode.| -| WINDOW_MODE_FULLSCREEN7+ | 1 | The Page ability is in full screen mode. | -| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The Page ability is displayed in the primary window when it is in split-screen mode.| -| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The Page ability is displayed in the secondary window when it is in split-screen mode.| -| WINDOW_MODE_FLOATING7+ | 102 | The Page ability is displayed in floating window mode.| +| WINDOW_MODE_UNDEFINED7+ | 0 | The PageAbility is in an undefined window display mode.| +| WINDOW_MODE_FULLSCREEN7+ | 1 | The PageAbility is in full screen mode. | +| WINDOW_MODE_SPLIT_PRIMARY7+ | 100 | The PageAbility is displayed in the primary window when it is in split-screen mode.| +| WINDOW_MODE_SPLIT_SECONDARY7+ | 101 | The PageAbility is displayed in the secondary window when it is in split-screen mode.| +| WINDOW_MODE_FLOATING7+ | 102 | The PageAbility is displayed in floating window mode.| ## AbilityStartSetting -The **AbilityStartSetting** attribute is an object defined as [key: string]: any. The key is a type of **AbilityStartSetting**, and the value is a type of **AbilityWindowConfiguration**. +Defines the window attribute corresponding to this ability. The **abilityStartSetting** attribute is an object defined in the format of [**key: string]: any**, where **key** is an enumerated value of **AbilityStartSetting** and **value** is an enumerated value of **AbilityWindowConfiguration**. -The value is obtained through the **featureAbility.AbilityStartSetting** API. +The value is obtained through **featureAbility.AbilityStartSetting**. **Example** @@ -877,7 +772,7 @@ featureAbility.AbilityStartSetting.BOUNDS_KEY ## ErrorCode -Enumerates error codes. +Enumerates the error codes. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -886,12 +781,12 @@ Enumerates error codes. | NO_ERROR7+ | 0 | No error occurs.| | INVALID_PARAMETER7+ | -1 | Invalid parameter.| | ABILITY_NOT_FOUND7+ | -2 | The ability is not found.| -| PERMISSION_DENY7+ | -3 | The request is denied.| +| PERMISSION_DENY7+ | -3 | Permission denied.| ## DataAbilityOperationType -Enumerates operation types of the Data ability. +Enumerates the operation types of a DataAbility. The DataAbility can use an enumerated value to specify the operation type when operating data in batches. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -902,45 +797,27 @@ Enumerates operation types of the Data ability. | TYPE_DELETE7+ | 3 | Deletion operation.| | TYPE_ASSERT7+ | 4 | Assert operation.| - - -## AbilityResult - -**System capability**: SystemCapability.Ability.AbilityBase - -| Name | Type | Readable| Writable | Mandatory | Description | -| --------------- |-------- | ------ | ------------- | ---- | ------------------------------------- | -| resultCode7+| number| Yes | No | Yes | Result code returned after the ability is destroyed. The feature for defining error-specific result codes is coming soon.| -| want7+ | [Want](js-apis-application-Want.md)| Yes | No| No | Data returned after the ability is destroyed. You can define the data to be returned. This parameter can be **null**. | - -## StartAbilityParameter - -**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel - -| Name | Type | Readable| Writable | Mandatory | Description | -| ------------------- | -------- | -------------------- | ---- | -------------------------------------- | -| want | [Want](js-apis-application-Want.md)| Yes | No | Yes | Information about the ability to start. | -| abilityStartSetting | {[key: string]: any} | Yes |No | No | Special attribute of the ability to start. This attribute can be passed in the method call.| - ## flags +Enumerates the flags that specify how the Want will be handled. + **System capability**: SystemCapability.Ability.AbilityBase | Name | Value | Description | | ------------------------------------ | ---------- | ---------------------------------------- | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write the URI. | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to the URI. | | FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | -| FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be migrated to a remote device. | +| FLAG_ABILITY_CONTINUATION | 0x00000008 | Continues the ability on a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | -| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether to enable an ability. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates whether the FormAbility is enabled. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ability is started in the foreground regardless of whether the host application is started.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that the migration is reversible. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | | FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| -| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the historical mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on an existing mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-particleAbility.md b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md similarity index 60% rename from en/application-dev/reference/apis/js-apis-particleAbility.md rename to en/application-dev/reference/apis/js-apis-ability-particleAbility.md index 75b6378962fb1f3c25bcf7e12a0a2df20a151628..7d00454ea5ce5b0051c2fff6856f9653be89b455 100644 --- a/en/application-dev/reference/apis/js-apis-particleAbility.md +++ b/en/application-dev/reference/apis/js-apis-ability-particleAbility.md @@ -1,6 +1,6 @@ -# particleAbility +# @ohos.ability.particleAbility (ParticleAbility) -The **particleAbility** module provides APIs for Service abilities. You can use the APIs to start and terminate a Particle ability, obtain a **dataAbilityHelper** object, connect the current ability to a specific Service ability, and disconnect the current ability from a specific Service ability. +The **particleAbility** module provides APIs for operating a ServiceAbility. You can use the APIs to start and terminate a ParticleAbility, obtain a **dataAbilityHelper** object, and connect to or disconnect from a ServiceAbility. > **NOTE** > @@ -13,7 +13,7 @@ The ParticleAbility module is used to perform operations on abilities of the Dat ## Modules to Import -```js +```ts import particleAbility from '@ohos.ability.particleAbility' ``` @@ -21,25 +21,30 @@ import particleAbility from '@ohos.ability.particleAbility' startAbility(parameter: StartAbilityParameter, callback: AsyncCallback\): void -Starts a Particle ability. This API uses an asynchronous callback to return the result. +Starts a ParticleAbility. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** - | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' import wantConstant from '@ohos.ability.wantConstant' + particleAbility.startAbility( - { + { want: { action: "action.system.home", @@ -48,32 +53,34 @@ particleAbility.startAbility( flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, deviceId: "", bundleName: "com.example.Data", - abilityName: "com.example.Data.MainAbility", - uri:"" + abilityName: "EntryAbility", + uri: "" }, }, (error, result) => { - console.log('particleAbility startAbility errCode:' + error + 'result:' + result) + console.log('particleAbility startAbility errCode:' + error + 'result:' + result) }, ) ``` - - ## particleAbility.startAbility startAbility(parameter: StartAbilityParameter): Promise\; -Starts a Particle ability. This API uses a promise to return the result. +Starts a ParticleAbility. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** - | Name | Type | Mandatory| Description | | --------- | ----------------------------------------------- | ---- | ----------------- | -| parameter | [StartAbilityParameter](js-apis-featureAbility.md#startabilityparameter) | Yes | Ability to start.| +| parameter | [StartAbilityParameter](js-apis-inner-ability-startAbilityParameter.md) | Yes | Ability to start.| **Return value** @@ -83,11 +90,12 @@ Starts a Particle ability. This API uses a promise to return the result. **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' import wantConstant from '@ohos.ability.wantConstant' + particleAbility.startAbility( - { + { want: { action: "action.system.home", @@ -96,8 +104,8 @@ particleAbility.startAbility( flags: wantConstant.Flags.FLAG_AUTH_READ_URI_PERMISSION, deviceId: "", bundleName: "com.example.Data", - abilityName: "com.example. Data.MainAbility", - uri:"" + abilityName: "EntryAbility", + uri: "" }, }, ).then((data) => { @@ -105,13 +113,11 @@ particleAbility.startAbility( }); ``` - - ## particleAbility.terminateSelf terminateSelf(callback: AsyncCallback\): void -Terminates this Particle ability. This API uses an asynchronous callback to return the result. +Terminates this ParticleAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -123,22 +129,21 @@ Terminates this Particle ability. This API uses an asynchronous callback to retu **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' + particleAbility.terminateSelf( (error, result) => { - console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) + console.log('particleAbility terminateSelf errCode:' + error + 'result:' + result) } ) ``` - - ## particleAbility.terminateSelf terminateSelf(): Promise\ -Terminates this Particle ability. This API uses a promise to return the result. +Terminates this ParticleAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -150,8 +155,9 @@ Terminates this Particle ability. This API uses a promise to return the result. **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility' + particleAbility.terminateSelf().then((data) => { console.info("particleAbility terminateSelf"); }); @@ -165,6 +171,12 @@ acquireDataAbilityHelper(uri: string): DataAbilityHelper Obtains a **dataAbilityHelper** object. +Observe the following when using this API: + - To access a DataAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**). + - If an application running in the background needs to call this API to access a DataAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** @@ -177,12 +189,13 @@ Obtains a **dataAbilityHelper** object. | Type | Description | | ----------------- | -------------------------------------------- | -| DataAbilityHelper | A utility class used to help other abilities access a Data ability.| +| [DataAbilityHelper](js-apis-inner-ability-dataAbilityHelper.md) | A utility class used to help other abilities access a DataAbility.| **Example** -```js -import particleAbility from '@ohos.ability.particleAbility' +```ts +import particleAbility from '@ohos.ability.particleAbility' + var uri = ""; particleAbility.acquireDataAbilityHelper(uri) ``` @@ -208,7 +221,7 @@ Requests a continuous task from the system. This API uses an asynchronous callba **Example** -```js +```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; import wantAgent from '@ohos.wantAgent'; @@ -225,7 +238,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -277,7 +290,7 @@ Requests a continuous task from the system. This API uses a promise to return th **Example** -```js +```ts import notification from '@ohos.notification'; import particleAbility from '@ohos.ability.particleAbility'; import wantAgent from '@ohos.wantAgent'; @@ -286,7 +299,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -333,7 +346,7 @@ Requests to cancel a continuous task from the system. This API uses an asynchron **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility'; function callback(err, data) { @@ -352,7 +365,7 @@ particleAbility.cancelBackgroundRunning(callback); cancelBackgroundRunning(): Promise<void>; -Requests a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). +Requests to cancel a continuous task from the system. This API uses a promise to return the result. You are advised to use the new API [backgroundTaskManager.stopBackgroundRunning](js-apis-backgroundTaskManager.md#backgroundtaskmanagerstopbackgroundrunning8-1). **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask @@ -364,7 +377,7 @@ Requests a continuous task from the system. This API uses a promise to return th **Example** -```js +```ts import particleAbility from '@ohos.ability.particleAbility'; particleAbility.cancelBackgroundRunning().then(() => { @@ -375,12 +388,17 @@ particleAbility.cancelBackgroundRunning().then(() => { ``` - ## particleAbility.connectAbility connectAbility(request: Want, options:ConnectOptions): number -Connects this ability to a specific Service ability. This API uses a callback to return the result. +Connects this ability to a specific ServiceAbility. + +Observe the following when using this API: + - To connect to a ServiceAbility of another application, the target application must be configured with associated startup (**AssociateWakeUp** set to **true**).. + - If an application running in the background needs to call this API to connect to a ServiceAbility, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the FA model, see [Component Startup Rules (FA Model)](../../application-models/component-startup-rules-fa.md). **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -388,60 +406,53 @@ Connects this ability to a specific Service ability. This API uses a callback to | Name | Type | Mandatory| Description | | ------- | -------------- | ---- | ---------------------------- | -| request | [Want](js-apis-application-Want.md) | Yes | Service ability to connect.| -| options | ConnectOptions | Yes | Callback used to return the result. | +| request | [Want](js-apis-application-want.md) | Yes | ServiceAbility to connect.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes | Connection options. | -ConnectOptions +**Example** -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +```ts +import particleAbility from '@ohos.ability.particleAbility' +import rpc from '@ohos.rpc' -| Name | Readable/Writable| Type | Mandatory | Description | -| ------------ | ---- | -------- | ---- | ------------------------- | -| onConnect | Read only | function | Yes | Callback invoked when the connection is successful. | -| onDisconnect | Read only | function | Yes | Callback invoked when the connection fails. | -| onFailed | Read only | function | Yes | Callback invoked when **connectAbility** fails to be called.| +function onConnectCallback(element, remote) { + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} -**Example** +function onDisconnectCallback(element) { + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} -```js - import rpc from '@ohos.rpc' - function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); - } - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) - } - function onFailedCallback(code){ - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) - } - var connId = particleAbility.connectAbility( - { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, - ); - - particleAbility.disconnectAbility(connId).then((data)=>{ - console.log( " data: " + data); - }).catch((error)=>{ - console.log('particleAbilityTest result errCode : ' + error.code ) - }); - +function onFailedCallback(code) { + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} -``` +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +particleAbility.disconnectAbility(connId).then((data) => { + console.log(" data: " + data); +}).catch((error) => { + console.log('particleAbilityTest result errCode : ' + error.code) +}); + +``` ## particleAbility.disconnectAbility disconnectAbility(connection: number, callback:AsyncCallback\): void; -Disconnects this ability from the Service ability. This API uses a callback to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -453,34 +464,38 @@ Disconnects this ability from the Service ability. This API uses a callback to r **Example** -```js -import rpc from '@ohos.rpc' - function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); - } - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) - } - function onFailedCallback(code){ - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) - } - var connId = particleAbility.connectAbility( - { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, - ); - var result = particleAbility.disconnectAbility(connId).then((data)=>{ - console.log( " data: " + data); - }).catch((error)=>{ - console.log('particleAbilityTest result errCode : ' + error.code ) - }); +```ts +import particleAbility from '@ohos.ability.particleAbility'; +import rpc from '@ohos.rpc'; +function onConnectCallback(element, remote) { + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} + +function onDisconnectCallback(element) { + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} + +function onFailedCallback(code) { + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} + +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); +var result = particleAbility.disconnectAbility(connId).then((data) => { + console.log(" data: " + data); +}).catch((error) => { + console.log('particleAbilityTest result errCode : ' + error.code) +}); ``` @@ -488,7 +503,7 @@ import rpc from '@ohos.rpc' disconnectAbility(connection: number): Promise\; -Disconnects this ability from the Service ability. This API uses a promise to return the result. +Disconnects this ability from a specific ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -500,40 +515,45 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Example** -```js -import rpc from '@ohos.rpc' -function onConnectCallback(element, remote){ - console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); - } - function onDisconnectCallback(element){ - console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) - } - function onFailedCallback(code){ - console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) - } - var connId = particleAbility.connectAbility( - { - bundleName: "com.ix.ServiceAbility", - abilityName: "ServiceAbilityA", - }, - { - onConnect: onConnectCallback, - onDisconnect: onDisconnectCallback, - onFailed: onFailedCallback, - }, - ); - - particleAbility.disconnectAbility(connId).then((data)=>{ - console.log( " data: " + data); - }).catch((error)=>{ - console.log('particleAbilityTest result errCode : ' + error.code ) - }); +```ts +import particleAbility from '@ohos.ability.particleAbility'; +import rpc from '@ohos.rpc'; + +function onConnectCallback(element, remote) { + console.log('ConnectAbility onConnect remote is proxy:' + (remote instanceof rpc.RemoteProxy)); +} + +function onDisconnectCallback(element) { + console.log('ConnectAbility onDisconnect element.deviceId : ' + element.deviceId) +} + +function onFailedCallback(code) { + console.log('particleAbilityTest ConnectAbility onFailed errCode : ' + code) +} + +var connId = particleAbility.connectAbility( + { + bundleName: "com.ix.ServiceAbility", + abilityName: "ServiceAbilityA", + }, + { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback, + onFailed: onFailedCallback, + }, +); + +particleAbility.disconnectAbility(connId).then((data) => { + console.log(" data: " + data); +}).catch((error) => { + console.log('particleAbilityTest result errCode : ' + error.code) +}); ``` ## ErrorCode -Enumerates error codes. +Enumerates the error codes. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel diff --git a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md index 4b1a66f071f464d6662d8429606c48aa025e8ef6..87b52688c5bec0a80bc44d9c8dcba63fe00283f2 100644 --- a/en/application-dev/reference/apis/js-apis-ability-wantConstant.md +++ b/en/application-dev/reference/apis/js-apis-ability-wantConstant.md @@ -1,20 +1,20 @@ -# wantConstant +# @ohos.ability.wantConstant (wantConstant) The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. > **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 6 and deprecated since API version 9. You are advised to use [@ohos.app.ability.wantConstant](js-apis-app-ability-wantConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```js +```ts import wantConstant from '@ohos.ability.wantConstant'; ``` ## wantConstant.Action -Enumerates the action constants of the **Want** object. +Enumerates the action constants of the **Want** object. **action** specifies the operation to execute. **System capability**: SystemCapability.Ability.AbilityBase @@ -46,6 +46,7 @@ Enumerates the action constants of the **Want** object. | ACTION_FILE_SELECT7+ | ohos.action.fileSelect | Action of selecting a file. | | PARAMS_STREAM7+ | ability.params.stream | URI of the data stream associated with the target when the data is sent. | | ACTION_APP_ACCOUNT_OAUTH 8+ | ohos.account.appAccount.action.oauth | Action of providing the OAuth service. | +| ACTION_APP_ACCOUNT_AUTH 9+ | account.appAccount.action.auth | Action of providing the authentication service. | | ACTION_MARKET_DOWNLOAD 9+ | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | | ACTION_MARKET_CROWDTEST 9+ | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | | DLP_PARAMS_SANDBOX9+ |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications. | @@ -56,7 +57,7 @@ Enumerates the action constants of the **Want** object. ## wantConstant.Entity -Enumerates the entity constants of the **Want** object. +Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability. **System capability**: SystemCapability.Ability.AbilityBase @@ -71,25 +72,25 @@ Enumerates the entity constants of the **Want** object. ## wantConstant.Flags -Describes flags. +Enumerates the flags that specify how the Want will be handled. **System capability**: SystemCapability.Ability.AbilityBase | Name | Value | Description | | ------------------------------------ | ---------- | ------------------------------------------------------------ | -| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | -| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Grants the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Grants the permission to write data to the URI. | | FLAG_ABILITY_FORWARD_RESULT | 0x00000004 | Returns the result to the ability. | | FLAG_ABILITY_CONTINUATION | 0x00000008 | Indicates whether the ability on the local device can be continued on a remote device. | | FLAG_NOT_OHOS_COMPONENT | 0x00000010 | Indicates that a component does not belong to OHOS. | | FLAG_ABILITY_FORM_ENABLED | 0x00000020 | Indicates that an ability is enabled. | -| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Indicates the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | -| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Indicates the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| -| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Supports cross-device startup in a distributed scheduler. | -| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the Service ability is started regardless of whether the host application has been started. | +| FLAG_AUTH_PERSISTABLE_URI_PERMISSION | 0x00000040 | Grants the permission to make the URI persistent.
**System API**: This is a system API and cannot be called by third-party applications. | +| FLAG_AUTH_PREFIX_URI_PERMISSION | 0x00000080 | Grants the permission to verify URIs by prefix matching.
**System API**: This is a system API and cannot be called by third-party applications.| +| FLAG_ABILITYSLICE_MULTI_DEVICE | 0x00000100 | Indicates the support for cross-device startup in the distributed scheduler. | +| FLAG_START_FOREGROUND_ABILITY | 0x00000200 | Indicates that the ServiceAbility is started regardless of whether the host application has been started. | | FLAG_ABILITY_CONTINUATION_REVERSIBLE | 0x00000400 | Indicates that ability continuation is reversible.
**System API**: This is a system API and cannot be called by third-party applications. | | FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | | FLAG_INSTALL_WITH_BACKGROUND_MODE | 0x80000000 | Indicates that the specific ability will be installed in the background if it has not been installed. | | FLAG_ABILITY_CLEAR_MISSION | 0x00008000 | Clears other operation missions. This flag can be set for the **Want** object in the **startAbility** API passed to [ohos.app.Context](js-apis-ability-context.md) and must be used together with **flag_ABILITY_NEW_MISSION**.| -| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Indicates the operation of creating a mission on the history mission stack. | -| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Starts the mission on the top of the existing mission stack; creates an ability instance if no mission exists.| +| FLAG_ABILITY_NEW_MISSION | 0x10000000 | Creates a mission on the history mission stack. | +| FLAG_ABILITY_MISSION_TOP | 0x20000000 | Reuses an ability instance if it is on the top of an existing mission stack; creates an ability instance otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index d593cf5a61697773be5837287f0e63d33cff3ce8..88ffbc6255e15705d88259e65392fa9e4f6a3193 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -1,4 +1,4 @@ -# Ability Access Control +# @ohos.abilityAccessCtrl (Application Access Control) The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation. @@ -40,7 +40,7 @@ Implements ability access control. checkAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> -Checks whether an application has the specified permission. This API uses a promise to return the result. +Checks whether a permission is granted to an application. This API uses a promise to return the result. **System capability**: SystemCapability.Security.AccessToken @@ -48,8 +48,8 @@ Checks whether an application has the specified permission. This API uses a prom | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Permission to check.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to check. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -71,7 +71,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { atManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); @@ -87,7 +87,7 @@ try { verifyAccessTokenSync(tokenID: number, permissionName: Permissions): GrantStatus -Verifies whether an application has the specified permission. This API returns the result synchronously. +Verifies whether a permission is granted to an application. This API returns the result synchronously. **System capability**: SystemCapability.Security.AccessToken @@ -95,8 +95,8 @@ Verifies whether an application has the specified permission. This API returns t | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. | -| permissionName | Permissions | Yes | Name of the permission to verify.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -116,7 +116,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e ```js let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let data = atManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); console.log(`data->${JSON.stringify(data)}`); ``` @@ -137,8 +137,8 @@ Grants a user_grant permission to an application. This API uses a promise to ret | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to grant.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** @@ -165,7 +165,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -194,10 +194,10 @@ Grants a user_grant permission to an application. This API uses an asynchronous | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| -| permissionName | Permissions | Yes | Name of the permission to grant.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md).| +| permissionName | Permissions | Yes | Permission to grant. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted successfully, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is granted successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -208,7 +208,8 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | -| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | +| 12100006 | The application specified by the tokenID is not allowed to be granted with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100007 | Service is abnormal. | **Example** @@ -216,7 +217,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -247,8 +248,8 @@ Revokes a user_grant permission from an application. This API uses a promise to | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to revoke.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** @@ -275,7 +276,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { @@ -304,10 +305,10 @@ Revokes a user_grant permission from an application. This API uses an asynchrono | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to revoke.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to revoke. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| | permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is revoked successfully, **err** is **undefine**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the permission is revoked successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Error codes** @@ -318,7 +319,8 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | TokenId does not exist. | | 12100003 | Permission does not exist. | -| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | +| 12100006 | The application specified by the tokenID is not allowed to be revoked with the specified permission. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100007 | Service is abnormal. | **Example** @@ -326,7 +328,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let permissionFlag = 1; try { atManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { @@ -357,8 +359,8 @@ Obtains the flags of the specified permission of an application. This API uses a | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to query.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Target permission. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -375,7 +377,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e | 12100001 | The parameter is invalid. The tokenID is 0 | | 12100002 | The specified tokenID does not exist. | | 12100003 | The specified permission does not exist. | -| 12100006 | The operation is not allowd. Either the application is a sandbox or the tokenID is from a remote device. | +| 12100006 | The operation is not allowed. Either the application is a sandbox or the tokenID is from a remote device. | | 12100007 | Service is abnormal. | **Example** @@ -384,7 +386,7 @@ For details about the error codes, see [Ability Access Control Error Codes](../e import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. try { atManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); @@ -525,7 +527,7 @@ try { verifyAccessToken(tokenID: number, permissionName: Permissions): Promise<GrantStatus> -Verifies whether an application has the specified permission. This API uses a promise to return the result. +Verifies whether a permission is granted to an application. This API uses a promise to return the result. > **NOTE**
You are advised to use [checkAccessToken](#checkaccesstoken9). @@ -535,8 +537,8 @@ Verifies whether an application has the specified permission. This API uses a pr | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | Permissions | Yes | Name of the permission to verify. Only valid permission names are supported.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | Permissions | Yes | Permission to verify. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| **Return value** @@ -550,18 +552,107 @@ Verifies whether an application has the specified permission. This API uses a pr import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); ``` +### requestPermissionsFromUser9+ + +requestPermissionsFromUser(context: Context, permissions: Array<Permissions>, requestCallback: AsyncCallback<PermissionRequestResult>) : void; + +Requests user authorization in a dialog box. This API uses an asynchronous callback to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Ability context of the application that requests the permission.| +| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| +| callback | AsyncCallback<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Yes| Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +| ID| Error Message| +| -------- | -------- | +| 12100001 | Parameter invalid. | + +**Example** + + ```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"], (err, data)=>{ + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} + ``` + +### requestPermissionsFromUser9+ + +requestPermissionsFromUser(context: Context, permissions: Array<Permissions>) : Promise<PermissionRequestResult>; + +Requests user authorization in a dialog box. This API uses a promise to return the result. + +**Model restriction**: This API can be used only in the stage model. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | Context | Yes| Ability context of the application that requests the permission.| +| permissions | Array<Permissions> | Yes| Permissions requested. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[PermissionRequestResult](js-apis-permissionrequestresult.md)> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). +| ID| Error Message| +| -------- | -------- | +| 12100001 | Parameter invalid. | + +**Example** + + ```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }).catch((err) => { + console.info("data:" + JSON.stringify(err)); + }) +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} + ``` + ### verifyAccessToken(deprecated) verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> -Verifies whether an application has the specified permission. This API uses a promise to return the result. +Verifies whether a permission is granted to an application. This API uses a promise to return the result. > NOTE
This API is deprecated since API version 9. You are advised to use [checkAccessToken](#checkaccesstoken9). @@ -571,8 +662,8 @@ Verifies whether an application has the specified permission. This API uses a pr | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | -| permissionName | string | Yes | Name of the permission to verify.| +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundleManager-applicationInfo.md). | +| permissionName | string | Yes | Permission to check.| **Return value** @@ -586,7 +677,7 @@ Verifies whether an application has the specified permission. This API uses a pr import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let atManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let tokenID = 0; // Use bundleManager.getApplicationInfo() to obtain the token ID for a system application, and use bundleManager.getBundleInfoForSelf() to obtain the token ID for a non-system application. let promise = atManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); @@ -629,4 +720,4 @@ Defines the detailed permission grant state change information. | -------------- | ------------------------- | ---- | ---- | ------------------ | | change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | No | Operation that triggers the permission grant state change. | | tokenID | number | Yes | No | Token ID of the application whose permission grant state changes are subscribed.| -| permissionName | Permissions | Yes | No | Name of the permission whose grant state is changed.| +| permissionName | Permissions | Yes | No | permission whose grant state is changed. For details about the permissions, see the [Application Permission List](../../security/permission-list.md).| diff --git a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md b/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md deleted file mode 100644 index 098f4ebba840a13d1f37d6e14256fcc9695f2a8d..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-abilityrunninginfo.md +++ /dev/null @@ -1,33 +0,0 @@ -# AbilityRunningInfo - -The **AbilityRunningInfo** module implements ability running information and ability states. - -> **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. - -## Usage - -The ability running information is obtained by using the **getAbilityRunningInfos** API in **abilityManager**. - -```js -import abilitymanager from '@ohos.application.abilityManager'; -abilitymanager.getAbilityRunningInfos((err,data) => { - console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); -}); -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| ability | ElementName | Yes| No| Information that matches an ability. | -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID. | -| processName | string | Yes| No| Process name. | -| startTime | number | Yes| No| Ability start time. | -| abilityState | [abilityManager.AbilityState](js-apis-application-abilityManager.md#abilitystate) | Yes| No| Ability state. | diff --git a/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md b/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md new file mode 100644 index 0000000000000000000000000000000000000000..34d4df8dd99bb528ae79d8d13de74f491f75f3db --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -0,0 +1,46 @@ +# @ohos.accessibility.GesturePath + + The **GesturePath** module provides APIs for creating gesture path information required for an accessibility application to inject gestures. + +> **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 + +```ts +import GesturePath from '@ohos.accessibility.GesturePath'; +``` + +## GesturePath + +Defines a gesture path. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +### Attributes + +| Name | Type | Readable | Writable | Description | +| ------------ | ---------------------------------------- | ---- | ---- | ------ | +| points | Array<[GesturePoint](js-apis-accessibility-GesturePoint.md#gesturepoint)> | Yes | Yes | Gesture touch point. | +| durationTime | number | Yes | Yes | Total gesture duration, in milliseconds.| + +### constructor + +constructor(durationTime: number); + +Constructor used to create a **GesturePath** object. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| durationTime | number | Yes| Total gesture duration, in milliseconds.| + +**Example** + +```ts +let gesturePath = new GesturePath.GesturePath(20); +``` diff --git a/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md new file mode 100644 index 0000000000000000000000000000000000000000..5792c44cd9fc89cf495e943a4e40463ce89281c4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -0,0 +1,47 @@ +# @ohos.accessibility.GesturePoint + + The **GesturePoint** module provides APIs for creating gesture touch point information required for an accessibility application to inject gestures. + +> **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 + +```ts +import GesturePoint from '@ohos.accessibility.GesturePoint'; +``` + +## GesturePoint + +Defines a gesture touch point. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +### Attributes + +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| positionX | number | Yes | Yes | X coordinate of the touch point.| +| positionY | number | Yes | Yes | Y coordinate of the touch point.| + +### constructor + +constructor(positionX: number, positionY: number); + +Constructor used to create a **GesturePoint** object. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| positionX | number | Yes| X coordinate of the touch point.| +| positionY | number | Yes | Y coordinate of the touch point.| + +**Example** + +```ts +let gesturePoint = new GesturePoint.GesturePoint(1, 2); +``` 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 c33230f7181ce92a50cee6c1417eb5d71a124f68..33b6f586279309125be085e8a28d5423b271fae3 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility-config.md +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -1,17 +1,16 @@ -# System Accessibility Configuration +# @ohos.accessibility.config -The **config** module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. +The System Accessibility Configuration module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs provided by this module are system APIs. +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import -```typescript -import config from "@ohos.accessibility.config"; +```ts +import config from '@ohos.accessibility.config'; ``` ## Attributes @@ -22,20 +21,20 @@ 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| Daltonization filter. | +| daltonizationColorFilter | [Config](#config)<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| Configuration of the 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.| +| animationOff | [Config](#config)\| Yes| Yes| Whether to disable animation.| | brightnessDiscount | [Config](#config)\| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.| | mouseKey | [Config](#config)\| Yes| Yes| Whether to enable the mouse button feature.| -| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for the automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| +| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| | shortkey | [Config](#config)\| Yes| Yes| Whether to enable the accessibility extension shortcut key.| -| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is bundleName/abilityName.| +| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is 'bundleName/abilityName'.| | captions | [Config](#config)\| Yes| Yes| Whether to enable captions.| -| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](./js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| +| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>): Promise<void>; +enableAbility(name: string, capability: Array<accessibility.Capability>): Promise<void>; Enables an accessibility extension ability. This API uses a promise to return the result. @@ -45,29 +44,44 @@ Enables an accessibility extension ability. This API uses a promise to return th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>) | Yes| Capability of the accessibility extension ability.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **Example** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve']) - .then(() => { - console.info('enable succeed'); - }).catch((error) => { - console.error('enable failed'); - }); - ``` +```ts +import accessibility from '@ohos.accessibility'; +let name = 'com.ohos.example/axExtension'; +let capability : accessibility.Capability[] = ['retrieve']; +try { + config.enableAbility(name, capability).then(() => { + console.info('enable ability succeed'); + }).catch((err) => { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` ## enableAbility -enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>, callback: AsyncCallback<void>): void; +enableAbility(name: string, capability: Array<accessibility.Capability>, callback: AsyncCallback<void>): void; Enables an accessibility extension ability. This API uses an asynchronous callback to return the result. @@ -77,21 +91,37 @@ Enables an accessibility extension ability. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| capability | Array<[accessibility.Capability](js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | +| 9300002 | Target ability already enabled. | **Example** - ```typescript - config.enableAbility("com.ohos.example/axExtension", ['retrieve'], (err, data) => { - if (err) { - console.error('enable failed'); - return; - } - console.info('enable succeed'); - }) - ``` +```ts +import accessibility from '@ohos.accessibility'; +let name = 'com.ohos.example/axExtension'; +let capability : accessibility.Capability[] = ['retrieve']; +try { + config.enableAbility(name, capability, (err) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('enable ability succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility @@ -105,24 +135,36 @@ Disables an accessibility extension ability. This API uses a promise to return t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **Example** - ```typescript - config.disableAbility("com.ohos.example/axExtension") - .then(() => { - console.info('disable succeed'); - }).catch((error) => { - console.error('disable failed'); - }); - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.disableAbility(name).then(() => { + console.info('disable ability succeed'); + }).catch((err) => { + console.error('failed to disable ability, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to disable ability, because ' + JSON.stringify(exception)); +}; +``` ## disableAbility @@ -136,26 +178,39 @@ Disables an accessibility extension ability. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| name | string | Yes| Name of the accessibility extension ability. The format is 'bundleName/abilityName'.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300001 | Invalid bundle name or ability name. | **Example** - ```typescript - config.disableAbility("com.ohos.example/axExtension", (err, data) => { - if (err) { - console.error('disable failed'); - return; - } - console.info('disable succeed'); - }) - ``` +```ts +let name = 'com.ohos.example/axExtension'; +try { + config.disableAbility(name, (err, data) => { + if (err) { + console.error('failed to enable ability, because ' + JSON.stringify(err)); + return; + } + console.info('disable succeed'); + }); +} catch (exception) { + console.error('failed to enable ability, because ' + JSON.stringify(exception)); +}; +``` -## on('enableAbilityListsStateChanged') +## on('enabledAccessibilityExtensionListChange') -on(type: 'enableAbilityListsStateChanged', callback: Callback<void>): void; +on(type: 'enabledAccessibilityExtensionListChange', callback: Callback<void>): void; -Adds a listener for changes in the list of enabled accessibility extension abilities. +Adds a listener for changes in the list of enabled accessibility extension abilities. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -163,22 +218,27 @@ 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 the changes in the list of enabled accessibility extension abilities. | +| type | string | Yes| Listening type. The value is fixed at **'enabledAccessibilityExtensionListChange'**, indicating listening for changes in the list of enabled accessibility extension abilities.| | callback | Callback<void> | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.on('enableAbilityListsStateChanged',() => { - console.info('ax extension ability enable list changed'); - }); - ``` +```ts +try { + config.on('enabledAccessibilityExtensionListChange', () => { + console.info('subscribe enabled accessibility extension list change state success'); + }); +} catch (exception) { + console.error('failed to subscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` -## off('enableAbilityListsStateChanged') +## off('enabledAccessibilityExtensionListChange') -off(type: 'enableAbilityListsStateChanged', callback?: Callback<void>): void; +off(type: 'enabledAccessibilityExtensionListChange', callback?: Callback<void>): void; -Cancels the listener for changes in the list of enabled accessibility extension abilities. +Cancels the listener for changes in the list of enabled accessibility extension abilities. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -186,14 +246,21 @@ 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 the changes in the list of enabled accessibility extension abilities. | +| type | string | Yes| Listening type. The value is fixed at **'enabledAccessibilityExtensionListChange'**, indicating listening for changes in the list of enabled accessibility extension abilities.| | callback | Callback<void> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.off('enableAbilityListsStateChanged'); - ``` +```ts +try { + config.off('enabledAccessibilityExtensionListChange', () => { + console.info('Unsubscribe enabled accessibility extension list change state success'); + }); +} catch (exception) { + console.error('failed to Unsubscribe enabled accessibility extension list change state, because ' + + JSON.stringify(exception)); +}; +``` ## Config @@ -203,7 +270,7 @@ Implements configuration, acquisition, and listening for attributes. set(value: T): Promise<void>; -Sets this attribute. This API uses a promise to return the result. +Sets the attribute value. This API uses a promise to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -217,24 +284,28 @@ Sets this attribute. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the execution result.| +| Promise<void> | Promise that returns no value.| **Example** - ```typescript - config.highContrastText.set(true) - .then(() => { - console.info('highContrastText set succeed'); - }).catch((error) => { - console.error('highContrastText set failed'); - }); - ``` +```ts +let value = true; +try { + config.highContrastText.set(value).then(() => { + console.info('set highContrastText succeed'); + }).catch((err) => { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### set set(value: T, callback: AsyncCallback<void>): void; -Sets this attribute. This API uses an asynchronous callback to return the result. +Sets the attribute value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -243,25 +314,30 @@ Sets this attribute. This API uses an asynchronous callback to return the result | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | T | Yes| Attribute value to set.| -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```typescript - config.highContrastText.set(true, (err, data) => { - if (err) { - console.error('highContrastText set failed'); - return; - } - console.info('highContrastText set succeed'); - }) - ``` +```ts +let value = true; +try { + config.highContrastText.set(value, (err, data) => { + if (err) { + console.error('failed to set highContrastText, because ' + JSON.stringify(err)); + return; + } + console.info('set highContrastText succeed'); + }); +} catch (exception) { + console.error('failed to set config, because ' + JSON.stringify(exception)); +}; +``` ### get get(): Promise<T>; -Obtains the value of this attribute. This API uses a promise to return the result. +Obtains the attribute value. This API uses a promise to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -269,24 +345,25 @@ Obtains the value of this attribute. This API uses a promise to return the resul | Type| Description| | -------- | -------- | -| Promise<T> | Promise used to return the attribute value.| +| Promise<T> | Promise used to return the value obtained.| **Example** - ```typescript - config.highContrastText.get() - .then((value) => { - console.info('highContrastText get succeed'); - }).catch((error) => { - console.error('highContrastText get failed'); - }); - ``` +```ts +let value; +config.highContrastText.get().then((data) => { + value = data; + console.info('get highContrastText success'); +}).catch((err) => { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); +}); +``` ### get get(callback: AsyncCallback<T>): void; -Obtains the value of this attribute. This API uses an asynchronous callback to return the result. +Obtains the attribute value. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -294,25 +371,27 @@ Obtains the value of this attribute. This API uses an asynchronous callback to r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the attribute value.| +| callback | AsyncCallback<T> | Yes| Callback used to return the attribute value.| **Example** - ```typescript - config.highContrastText.get((err, data) => { - if (err) { - console.error('highContrastText get failed'); - return; - } - console.info('highContrastText get succeed'); - }) - ``` +```ts +let value; +config.highContrastText.get((err, data) => { + if (err) { + console.error('failed to get highContrastText, because ' + JSON.stringify(err)); + return; + } + value = data; + console.info('get highContrastText success'); +}); +``` ### on on(callback: Callback<T>): void; -Adds a listener for attribute changes. +Adds a listener for attribute changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -324,17 +403,21 @@ Adds a listener for attribute changes. **Example** - ```typescript - config.highContrastText.on(() => { - console.info('highContrastText changed'); - }); - ``` +```ts +try { + config.highContrastText.on((data) => { + console.info('subscribe highContrastText success, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed subscribe highContrastText, because ' + JSON.stringify(exception)); +} +``` ### off off(callback?: Callback<T>): void; -Cancels the listener for attribute changes. +Cancels the listener for attribute changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -342,13 +425,15 @@ Cancels the listener for attribute changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | Callback<T> | No| Callback invoked when the attribute changes.| +| callback | Callback<T> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| **Example** - ```typescript - config.highContrastText.off(); - ``` +```ts +config.highContrastText.off((data) => { + console.info('Unsubscribe highContrastText success, result: ' + JSON.stringify(data)); +}); +``` ## DaltonizationColorFilter 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 deleted file mode 100644 index 9fee7500eae2ec8435f0c3bdc2b48c986b14686a..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ /dev/null @@ -1,379 +0,0 @@ -# AccessibilityExtensionContext - -The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities. - -You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures. - -> **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. - -## Usage - -Before using the **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**. - -```js -import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' -class MainAbility extends AccessibilityExtensionAbility { - onConnect(): void { - console.log("AxExtensionAbility onConnect"); - let axContext = this.context; - } -} -``` - -## FocusDirection - -Enumerates the focus directions. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| -------- | ------- | -| 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 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 the focus types. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| ------------- | ----------- | -| accessibility | Accessibility focus.| -| normal | Normal focus. | - -## Rect - -Defines a rectangle. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Type | Readable | Writable | Description | -| ------ | ------ | ---- | ---- | --------- | -| left | number | Yes | No | Left boundary of the rectangle.| -| top | number | Yes | No | Top boundary of the rectangle.| -| width | number | Yes | No | Width of the rectangle. | -| height | number | Yes | No | Height of the rectangle. | - -## WindowType - -Enumerates the window types. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -| Name | Description | -| ----------- | --------- | -| application | Application window.| -| system | System window.| - -## AccessibilityExtensionContext.setTargetBundleName - -setTargetBundleName(targetNames: Array\): Promise\; - -Sets the concerned target bundle. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ------------------- | ---- | -------- | -| targetNames | Array<string> | Yes | Name of the target bundle.| - -**Return value** - -| Type | Description | -| ---------------------- | --------------------- | -| Promise<boolean> | Promise used to return the result.| - -**Example** - -```ts -this.context.setTargetBundleName(['com.ohos.mms']); -``` - -## AccessibilityExtensionContext.getFocusElement - -getFocusElement(isAccessibilityFocus?: boolean): Promise\; - -Obtains the focus element. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------------------- | ------- | ---- | ------------------- | -| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| - -**Return value** - -| Type | Description | -| ----------------------------------- | ---------------------- | -| Promise<AccessibilityElement> | Promise used to return the current focus element.| - -**Example** - -```ts -this.context.getFocusElement().then(focusElement => { - console.log("AxExtensionAbility getFocusElement success"); -}) -``` - -## AccessibilityExtensionContext.getWindowRootElement - -getWindowRootElement(windowId?: number): Promise\; - -Obtains the root element of a window. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | --------------------------- | -| windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| - -**Return value** - -| Type | Description | -| ----------------------------------- | ----------------------- | -| Promise<AccessibilityElement> | Promise used to return the root element.| - -**Example** - -```ts -this.context.getWindowRootElement().then(rootElement => { - console.log("AxExtensionAbility getWindowRootElement success"); -}) -``` - -## AccessibilityExtensionContext.getWindows - -getWindows(displayId?: number): Promise>; - -Obtains the list of windows visible to users. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | ------------------------- | -| displayId | number | No | Screen from which the window information is obtained. If this parameter is not specified, it indicates the default home screen.| - -**Return value** - -| Type | Description | -| ---------------------------------------- | ------------------------ | -| Promise<Array<AccessibilityElement>> | Promise used to return the window list. | - -**Example** - -```ts -this.context.getWindows().then(windows => { - console.log("AxExtensionAbility getWindows success"); -}) -``` - -## AccessibilityExtensionContext.injectGesture - -injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void - -Injects a gesture. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----------- | ---------------------------------------- | ---- | -------------- | -| gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | Yes | Path of the gesture to inject. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```ts -let gesturePath = new GesturePath(100); -for (let i = 0; i < 10; i++) { - let gesturePoint = new GesturePosition(100, i * 200); - gesturePath.positions.push(gesturePoint); -} -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-accessibility.md b/en/application-dev/reference/apis/js-apis-accessibility.md index 6d318b4ade570aea27b58ca93d37ef0a3992d3bc..cf4443c60f4b58a17986bdb7ae5160fd6a95347c 100644 --- a/en/application-dev/reference/apis/js-apis-accessibility.md +++ b/en/application-dev/reference/apis/js-apis-accessibility.md @@ -1,4 +1,4 @@ -# Accessibility +# @ohos.accessibility The **Accessibility** module implements the accessibility functions, including obtaining the accessibility application list, accessibility application enabled status, and captions configuration. @@ -8,7 +8,7 @@ The **Accessibility** module implements the accessibility functions, including o ## Modules to Import -```typescript +```ts import accessibility from '@ohos.accessibility'; ``` @@ -49,7 +49,7 @@ Provides information about an accessibility application. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| id | number | Yes| No| Ability ID.| +| id | string | Yes| No| Ability ID.| | name | string | Yes| No| Ability name.| | bundleName | string | Yes| No| Bundle name.| | targetBundleNames9+ | Array<string> | Yes| No| Name of the target bundle.| @@ -85,7 +85,7 @@ Describes the target action supported by an accessibility application. ## Capability -Enumerates the capabilities of an auxiliary application. +Enumerates the capabilities of an accessibility application. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -145,7 +145,7 @@ Describes the style of captions. ## CaptionsManager8+ -Implements configuration management for captions. +Implements configuration management for captions. Before calling any API of **CaptionsManager**, you must use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **CaptionsManager** instance. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing @@ -156,87 +156,113 @@ Implements configuration management for captions. | enabled | boolean | Yes| No| Whether to enable captions configuration.| | style | [CaptionsStyle](#captionsstyle8) | Yes| No| Style of captions.| -In the following API examples, you must first use the [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) API to obtain a **captionsManager** instance, and then call the methods using the obtained instance. - ### on('enableChange') on(type: 'enableChange', callback: Callback<boolean>): void; -Enables listening for the enabled status changes of captions configuration. +Enables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback invoked when the enabled status of captions configuration changes.| -- **Example** +**Example** - ```typescript - captionsManager.on('enableChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('enableChange', (data) => { + console.info('subscribe caption manager enable state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### on('styleChange') on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; -Enables listening for captions style changes. +Enables listening for captions style changes. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | Yes| Callback invoked when the style of captions changes.| -- **Example** +**Example** + +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.on('styleChange', (data) => { + captionStyle = data; + console.info('subscribe caption manager style state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` - ```typescript - captionsManager.on('styleChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` - ### off('enableChange') off(type: 'enableChange', callback?: Callback<boolean>): void; -Disables listening for the enabled status changes of captions configuration. +Disables listening for the enabled status changes of captions configuration. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **enableChange** in this API.| - | callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'enableChange'** in this API.| +| callback | Callback<boolean> | No| Callback invoked when the enabled status of captions configuration changes.| -- **Example** +**Example** - ```typescript - captionsManager.off('enableChange') - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('enableChange', (data) => { + console.info('Unsubscribe caption manager enable state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe caption manager enable state change, because ' + JSON.stringify(exception)); +} +``` ### off('styleChange') off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; -Disables listening for captions style changes. +Disables listening for captions style changes. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for, which is set to **styleChange** in this API.| - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'styleChange'** in this API.| +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | No| Callback invoked when the style of captions changes.| -- **Example** +**Example** - ```typescript - captionsManager.off('styleChange') - ``` +```ts +let captionStyle; +let captionsManager = accessibility.getCaptionsManager(); +try { + captionsManager.off('styleChange', (data) => { + captionStyle = data; + console.info('Unsubscribe caption manager style state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe caption manager style state change, because ' + JSON.stringify(exception)); +} +``` ## EventInfo @@ -271,16 +297,20 @@ Implements a constructor. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | jsonObject | string | Yes| JSON string required for creating an object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| jsonObject | string | Yes| JSON string required for creating an object.| -- **Example** +**Example** - ```typescript - let eventInfo = new accessibility.EventInfo({"type":"click","bundleName":"com.example.MyApplication","triggerAction":"click"}) + ```ts + let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' + }); ``` ## EventType @@ -331,153 +361,319 @@ Enumerates window update types. | active | Window activity change.| | focus | Window focus change.| -## accessibility.getAbilityLists +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> Obtains the accessibility application list. 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[getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9). + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| - | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| - -- **Return value** - - | Type| Description| - | -------- | -------- | - | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| - -- **Example** - - ```typescript - accessibility.getAbilityLists("spoken", "enable") - .then((data) => { - console.info('success data:getAbilityList1 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.abilityTypes); - console.info(item.eventTypes); - console.info(item.capabilities); - console.info(item.packageName); - console.info(item.filterBundleNames); - console.info(item.bundleName); - } - }).catch((error) => { - console.error('failed to getAbilityList1 because ' + JSON.stringify(error)); - }) - ``` +**Parameters** -## accessibility.getAbilityLists +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| + +**Example** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAbilityLists(deprecated) getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void Obtains the accessibility application list. 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 [getAccessibilityExtensionList()](#accessibilitygetaccessibilityextensionlist9-1). + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| - | stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| - | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| - -- **Example** - - ```typescript - accessibility.getAbilityLists("visual", "enable", (err, data) => { - if (err) { - console.error('failed to getAbilityList2 because ' + JSON.stringify(err)); - return; - } - console.info('success data:getAbilityList2 : ' + JSON.stringify(data)); - for (let item of data) { - console.info(item.id); - console.info(item.name); - console.info(item.description); - console.info(item.abilityTypes); - console.info(item.eventTypes); - console.info(item.capabilities); - console.info(item.packageName); - console.info(item.filterBundleNames); - console.info(item.bundleName); - } - }) - ``` +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| + +**Example** + +```ts +let abilityType = 'spoken'; +let abilityState = 'enable'; +let abilityList: accessibility.AccessibilityInfo[]; +try { + accessibility.getAbilityLists(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + abilityList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> + +Obtains the accessibility application list. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise used to return the accessibility application list.| + +**Example** + +```ts +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState).then((data) => { + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }).catch((err) => { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` + +## accessibility.getAccessibilityExtensionList9+ + +getAccessibilityExtensionList(abilityType: AbilityType, stateType: AbilityState, callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void + +Obtains the accessibility application list. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | Yes| Accessibility application type.| +| stateType | [AbilityState](#abilitystate) | Yes| Accessibility application status.| +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Yes| Callback used to return the accessibility application list.| + +**Example** + +```ts +let abilityType : accessibility.AbilityType = 'spoken'; +let abilityState : accessibility.AbilityState = 'enable'; +let extensionList: accessibility.AccessibilityAbilityInfo[] = []; +try { + accessibility.getAccessibilityExtensionList(abilityType, abilityState, (err, data) => { + if (err) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(err)); + return; + } + for (let item of data) { + console.info(item.id); + console.info(item.name); + console.info(item.description); + console.info(item.bundleName); + extensionList.push(item); + } + console.info('get accessibility extension list success'); + }); +} catch (exception) { + console.error('failed to get accessibility extension list because ' + JSON.stringify(exception)); +} +``` ## accessibility.getCaptionsManager8+ getCaptionsManager(): CaptionsManager -Obtains the captions configuration. +Obtains a **CaptionsManager** instance. **System capability**: SystemCapability.BarrierFree.Accessibility.Hearing -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | [CaptionsManager](#captionsmanager8) | Captions configuration.| +| Type| Description| +| -------- | -------- | +| [CaptionsManager](#captionsmanager8) | Captions configuration.| -- **Example** +**Example** - ```typescript - captionsManager = accessibility.getCaptionsManager() - ``` +```ts +let captionsManager = accessibility.getCaptionsManager(); +``` -## accessibility.on('accessibilityStateChange' | 'touchGuideStateChange') +## accessibility.on('accessibilityStateChange') -on(type: 'accessibilityStateChange' | 'touchGuideStateChange', callback: Callback<boolean>): void +on(type: 'accessibilityStateChange', callback: Callback<boolean>): void -Enables listening for the enabled status changes of the accessibility application or touch guide mode. +Enables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for the enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for the enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| - | callback | Callback\ | Yes| Callback invoked when the enabled status of captions configuration changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback used to return the result.| -- **Example** +**Example** - ```typescript - accessibility.on('accessibilityStateChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +try { + accessibility.on('accessibilityStateChange', (data) => { + console.info('subscribe accessibility state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe accessibility state change, because ' + JSON.stringify(exception)); +} +``` -## accessibility.off('accessibilityStateChange' | 'touchGuideStateChange') +## accessibility.on('touchGuideStateChange') -off(type: 'accessibilityStateChange ' | 'touchGuideStateChange', callback?: Callback<boolean>): void +on(type: 'touchGuideStateChange', callback: Callback<boolean>): void -Disables listening for the enabled status changes of the accessibility application or touch guide mode. +Enables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | No| Type of the event to listen for.
- **'accessibilityStateChange'** means to listen for the enabled status changes of the accessibility application.
**System capability**: SystemCapability.BarrierFree.Accessibility.Core
- **'touchGuideStateChange'** means to listen for the enabled status changes of the touch guide mode.
**System capability**: SystemCapability.BarrierFree.Accessibility.Vision| - | callback | Callback<boolean> | No| Callback invoked when the enabled status changes.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | Yes| Callback used to return the result.| -- **Example** +**Example** - ```typescript - accessibility.off('accessibilityStateChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```ts +try { + accessibility.on('touchGuideStateChange', (data) => { + console.info('subscribe touch guide state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to subscribe touch guide state change, because ' + JSON.stringify(exception)); +} +``` + +## accessibility.off('accessibilityStateChange') + +off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void + +Disables listening for the enabled status changes of the accessibility application. This API uses an asynchronous callback to return the result. + + + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Type of the event to listen for, which is set to **'accessibilityStateChange'** in this API.| +| callback | Callback<boolean> | No| Callback used to return the result.| + +**Example** + +```ts +try { + accessibility.off('accessibilityStateChange', (data) => { + console.info('Unsubscribe accessibility state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe accessibility state change, because ' + JSON.stringify(exception)); +} +``` + +## accessibility.off('touchGuideStateChange') + +off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void + +Disables listening for the enabled status changes of the touch guide mode. This API uses an asynchronous callback to return the result. + + + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Type of the event to listen for, which is set to **'touchGuideStateChange'** in this API.| +| callback | Callback<boolean> | No| Callback used to return the result.| + +**Example** + +```ts +try { + accessibility.off('touchGuideStateChange', (data) => { + console.info('Unsubscribe touch guide state change, result: ' + JSON.stringify(data)); + }); +} catch (exception) { + console.error('failed to Unsubscribe touch guide state change, because ' + JSON.stringify(exception)); +} +``` ## accessibility.isOpenAccessibility @@ -487,22 +683,21 @@ Checks whether accessibility is enabled. This API uses a promise to return the r **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Returns **true** if accessibility is enabled; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenAccessibility() - .then((data) => { - console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenAccessibility because ' + JSON.stringify(error)); - }) - ``` +```ts +accessibility.isOpenAccessibility().then((data) => { + console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) +}).catch((err) => { + console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); +}); +``` ## accessibility.isOpenAccessibility @@ -512,23 +707,23 @@ Checks whether accessibility is enabled. This API uses an asynchronous callback **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if accessibility is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenAccessibility((err, data) => { - if (err) { - console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); - return; - } - console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) - }) - ``` +```ts +accessibility.isOpenAccessibility((err, data) => { + if (err) { + console.error('failed to isOpenAccessibility because ' + JSON.stringify(err)); + return; + } + console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) +}); +``` ## accessibility.isOpenTouchGuide @@ -538,22 +733,21 @@ Checks whether touch guide mode is enabled. This API uses a promise to return th **System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- **Return value** +**Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Returns **true** if touch guide mode is enabled; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenTouchGuide() - .then((data) => { - console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenTouchGuide because ' + JSON.stringify(error)); - }) - ``` +```ts +accessibility.isOpenTouchGuide().then((data) => { + console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) +}).catch((err) => { + console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); +}); +``` ## accessibility.isOpenTouchGuide @@ -563,78 +757,172 @@ Checks whether touch guide mode is enabled. This API uses an asynchronous callba **System capability**: SystemCapability.BarrierFree.Accessibility.Vision -- **Parameters** +**Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if touch guide mode is enabled; returns **false** otherwise.| -- **Example** +**Example** - ```typescript - accessibility.isOpenTouchGuide((err, data) => { - if (err) { - console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); - return; - } - console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) - }) - ``` +```ts +accessibility.isOpenTouchGuide((err, data) => { + if (err) { + console.error('failed to isOpenTouchGuide because ' + JSON.stringify(err)); + return; + } + console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) +}); +``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo): Promise<void> Sends an accessibility event. This API uses a promise to return the result. -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -- **Parameters** +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. +> You are advised to use **[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9)**. - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +**System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Return value** +**Parameters** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| -- **Example** +**Return value** - ```typescript - accessibility.sendEvent(this.eventInfo) - .then((data) => { - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to sendEvent because ' + JSON.stringify(error)); - }) - ``` +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +accessibility.sendEvent(eventInfo).then(() => { + console.info('send event success'); +}).catch((err) => { + console.error('failed to sendEvent because ' + JSON.stringify(err)); +}); +``` -## accessibility.sendEvent +## accessibility.sendEvent(deprecated) sendEvent(event: EventInfo, callback: AsyncCallback<void>): void Sends an accessibility event. 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 **[sendAccessibilityEvent()](#accessibilitysendaccessibilityevent9-1)**. + **System capability**: SystemCapability.BarrierFree.Accessibility.Core -- **Parameters** +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +accessibility.sendEvent(eventInfo, (err, data) => { + if (err) { + console.error('failed to sendEvent because ' + JSON.stringify(err)); + return; + } + console.info('sendEvent success'); +}); +``` - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | Yes| Accessibility event.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result. Returns data if the accessibility event is sent successfully; returns an error otherwise.| +## accessibility.sendAccessibilityEvent9+ -- **Example** +sendAccessibilityEvent(event: EventInfo): Promise<void> - ```typescript - accessibility.sendEvent(this.eventInfo,(err, data) => { - if (err) { - console.error('failed to sendEvent because ' + JSON.stringify(err)); - return; - } - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }) - ``` +Sends an accessibility event. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendAccessibilityEvent(eventInfo).then(() => { + console.info('send event success'); + }).catch((err) => { + console.error('failed to send event because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` + +## accessibility.sendAccessibilityEvent9+ + +sendAccessibilityEvent(event: EventInfo, callback: AsyncCallback<void>): void + +Sends an accessibility event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | Yes| Accessibility event.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, **error** that contains data is returned. | + +**Example** + +```ts +let eventInfo = new accessibility.EventInfo({ + 'type':'click', + 'bundleName':'com.example.MyApplication', + 'triggerAction':'click' +}); +try { + accessibility.sendEvent(eventInfo, (err, data) => { + if (err) { + console.error('failed to send event because ' + JSON.stringify(err)); + return; + } + console.info('send event success'); + }); +} catch (exception) { + console.error('failed to send event because ' + JSON.stringify(exception)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-animator.md b/en/application-dev/reference/apis/js-apis-animator.md index 9c1088af3a0fa0c7d15b56f51cdcfa49a9addde9..da7ec7d145779eb5044427fdee758a34f6b33fdc 100644 --- a/en/application-dev/reference/apis/js-apis-animator.md +++ b/en/application-dev/reference/apis/js-apis-animator.md @@ -1,4 +1,6 @@ -# Animator +# @ohos.animator + +The **animator** module provides APIs for applying animation effects, including defining animations, starting animations, and playing animations in reverse order. > **NOTE** > @@ -7,98 +9,90 @@ ## Modules to Import -``` +```js import animator from '@ohos.animator'; ``` +## create9+ - -## createAnimator - -createAnimator(options: AnimatorOptions): AnimatorResult +create(options: AnimatorOptions): AnimatorResult Creates an **Animator** object. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.| + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------- | +| options | [AnimatorOptions](#animatoroptions) | Yes | Animator options.| **Return value** -| Type| Description| -| -------- | -------- | + +| Type | Description | +| --------------------------------- | ------------- | | [AnimatorResult](#animatorresult) | Animator result.| **Example** - ``` - -
-
-
-
- ``` - - ``` - // js - export default { - data : { - divWidth: 200, - divHeight: 200, - animator: null - }, - onInit() { - var options = { - duration: 1500, - easing: 'friction', - fill: 'forwards', - iterations: 2, - begin: 200.0, - end: 400.0 - }; - this.animator = animator.createAnimator(options); - }, - Show() { - var options1 = { - duration: 2000, - easing: 'friction', - fill: 'forwards', - iterations: 1, - begin: 200.0, - end: 400.0 - }; - this.animator.update(options1); - var _this = this; - this.animator.onframe = function(value) { - _this.divWidth = value; - _this.divHeight = value; - }; - this.animator.play(); - } - } + ```js + let options = { + duration: 1500, + easing: 'friction', + delay: 0, + fill: 'forwards', + direction: 'normal', + iterations: 3, + begin: 200.0, + end: 400.0 + }; + animator.create(options); ``` ## AnimatorResult Defines the animator result. -### update +### reset9+ -update(options: AnimatorOptions): void +reset(options: AnimatorOptions): void Updates this animator. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| options | [AnimatorOptions](#animatoroptions) | Yes| Animator options.| + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------- | +| options | [AnimatorOptions](#animatoroptions) | Yes | Animator options.| + +**Error codes** + +For details about the error codes, see [Animator Error Codes](../errorcodes/errorcode-animator.md). + +| ID | Error Message| +| --------- | ------- | +| 100001 | If no page is found for pageId or fail to get object property list. | + **Example** -``` -animator.update(options); + +```js +let options = { + duration: 1500, + easing: 'friction', + delay: 0, + fill: 'forwards', + direction: 'normal', + iterations: 3, + begin: 200.0, + end: 400.0 +}; +try { + animator.reset(options); +} catch(error) { + console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`); +} ``` ### play @@ -110,7 +104,8 @@ Plays this animation. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** -``` + +```js animator.play(); ``` @@ -123,7 +118,8 @@ Ends this animation. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** -``` + +```js animator.finish(); ``` @@ -136,7 +132,8 @@ Pauses this animation. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** -``` + +```js animator.pause(); ``` @@ -149,7 +146,8 @@ Cancels this animation. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** -``` + +```js animator.cancel(); ``` @@ -162,7 +160,8 @@ Plays this animation in reverse order. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** -``` + +```js animator.reverse(); ``` @@ -175,13 +174,18 @@ Called when a frame is received. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| progress | number | Yes| Current progress of the animation.| + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | -------- | +| progress | number | Yes | Current progress of the animation.| **Example** -``` -animator.onframe(); + +```js +let animatorResult = animator.create(options) +animatorResult.onframe = function(value) { + console.info("onframe callback") +} ``` ### onfinish @@ -193,8 +197,12 @@ Called when this animation is finished. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** -``` -animator.onfinish(); + +```js +let animatorResult = animator.create(options) +animatorResult.onfinish = function() { + console.info("onfinish callback") +} ``` ### oncancel @@ -206,8 +214,12 @@ Called when this animation is canceled. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** -``` -animator.oncancel(); + +```js +let animatorResult = animator.create(options) +animatorResult.oncancel = function() { + console.info("oncancel callback") +} ``` ### onrepeat @@ -219,9 +231,15 @@ Called when this animation repeats. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Example** + +```js +let animatorResult = animator.create(options) +animatorResult.onrepeat = function() { + console.info("onrepeat callback") +} ``` -animator.onrepeat(); -``` + + ## AnimatorOptions @@ -229,13 +247,279 @@ Defines animator options. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| duration | number | Yes| Duration for playing the animation, in milliseconds. The default value is **0**.| -| easing | string | Yes| Animation interpolation curve. The default value is **'ease'**.| -| delay | number | Yes| Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay.| -| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes| State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed. | -| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes| Animation playback mode. The default value is **normal**.| -| iterations | number | Yes| Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times.| -| begin | number | Yes| Start point of the animation interpolation. If this parameter is not set, the default value **0** is used.| -| end | number | Yes| End point of the animation interpolation. If this parameter is not set, the default value **1** is used.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------------------- | ---- | ---------------------------------------- | +| duration | number | Yes | Duration for playing the animation, in milliseconds. The default value is **0**. | +| easing | string | Yes | Animation interpolation curve. The default value is **ease**. | +| delay | number | Yes | Animation delay duration, in milliseconds. The default value is **0**, indicating that there is no delay. | +| fill | "none" \| "forwards" \| "backwards" \| "both" | Yes | State of the animated target after the animation is executed. The default value is **none**, which means that the target will retain its end state (defined by the last keyframe) after the animation is executed.| +| direction | "normal" \| "reverse" \| "alternate" \| "alternate-reverse" | Yes | Animation playback mode. The default value is **normal**. | +| iterations | number | Yes | Number of times that the animation is played. The default value is **1**. The value **0** means not to play the animation, and **-1** means to play the animation for an unlimited number of times. | +| begin | number | Yes | Start point of the animation interpolation. The default value is 0. | +| end | number | Yes | End point of animation interpolation. The default value is 1. | + + +## Example +### JavaScript-compatible Web-like Development Paradigm + +```html + +
+
+
+
+``` + +```js +export default { + data: { + divWidth: 200, + divHeight: 200, + animator: null + }, + onInit() { + let options = { + duration: 1500, + easing: 'friction', + delay: 0, + fill: 'forwards', + direction: 'normal', + iterations: 2, + begin: 200.0, + end: 400.0 + }; + this.animator = animator.create(options); + }, + Show() { + let options1 = { + duration: 1500, + easing: 'friction', + delay: 0, + fill: 'forwards', + direction: "normal", + iterations: 2, + begin: 0, + end: 400.0, + }; + try { + this.animator.reset(options1); + } catch(error) { + console.error(`Animator reset failed, error code: ${error.code}, message: ${error.message}.`); + } + let _this = this; + this.animator.onframe = function(value) { + _this.divWidth = value; + _this.divHeight = value; + }; + this.animator.play(); + } +} +``` + + ![en-us_image_00007](figures/en-us_image_00007.gif) + +### ArkTS-based Declarative Development Paradigm + +```ts +import animator from '@ohos.animator'; + +@Entry +@Component +struct AnimatorTest { + private TAG: string = '[AnimatorTest]' + private backAnimator: any = undefined + private flag: boolean = false + @State wid: number = 100 + @State hei: number = 100 + + create() { + let _this = this + this.backAnimator = animator.create({ + duration: 2000, + easing: 'ease', + delay: 0, + fill: 'none', + direction: 'normal', + iterations: 1, + begin: 100, + end: 200 + }) + this.backAnimator.onfinish = function () { + _this.flag = true + console.info(_this.TAG, 'backAnimator onfinish') + } + this.backAnimator.onrepeat = function () { + console.info(_this.TAG, 'backAnimator repeat') + } + this.backAnimator.oncancel = function () { + console.info(_this.TAG, 'backAnimator cancel') + } + this.backAnimator.onframe = function (value) { + _this.wid = value + _this.hei = value + } + } + + build() { + Column() { + Column() { + Column() + .width(this.wid) + .height(this.hei) + .backgroundColor(Color.Red) + } + .width('100%') + .height(300) + + Column() { + Row() { + Button('create') + .fontSize(30) + .fontColor(Color.Black) + .onClick(() => { + this.create() + }) + } + .padding(10) + + Row() { + Button('play') + .fontSize(30) + .fontColor(Color.Black) + .onClick(() => { + this.flag = false + this.backAnimator.play() + }) + } + .padding(10) + + Row() { + Button('pause') + .fontSize(30) + .fontColor(Color.Black) + .onClick(() => { + this.backAnimator.pause() + }) + } + .padding(10) + + Row() { + Button('finish') + .fontSize(30) + .fontColor(Color.Black) + .onClick(() => { + this.flag = true + this.backAnimator.finish() + }) + } + .padding(10) + + Row() { + Button('reverse') + .fontSize(30) + .fontColor(Color.Black) + .onClick(() => { + this.flag = false + this.backAnimator.reverse() + }) + } + .padding(10) + + Row() { + Button('cancel') + .fontSize(30) + .fontColor(Color.Black) + .onClick(() => { + this.backAnimator.cancel() + }) + } + .padding(10) + + Row() { + Button('reset') + .fontSize(30) + .fontColor(Color.Black) + .onClick(() => { + if (this.flag) { + this.flag = false + this.backAnimator.reset({ + duration: 5000, + easing: 'ease-in', + delay: 0, + fill: 'none', + direction: 'normal', + iterations: 4, + begin: 100, + end: 300 + }) + } else { + console.info(this.TAG, 'Animation not ended') + } + }) + } + .padding(10) + } + } + } +} +``` + +## update(deprecated) + +update(options: AnimatorOptions): void + +Updates this animator. + +This API is deprecated since API version 9. You are advised to use [reset9+](#reset9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------- | +| options | [AnimatorOptions](#animatoroptions) | Yes | Animator options.| + +**Example** + +```js +animator.update(options); +``` + +## createAnimator(deprecated) + +createAnimator(options: AnimatorOptions): AnimatorResult + +Creates an **Animator** object. + +This API is deprecated since API version 9. You are advised to use [create9+](#create9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ----------------------------------- | ---- | ------- | +| options | [AnimatorOptions](#animatoroptions) | Yes | Animator options.| + +**Return value** + +| Type | Description | +| --------------------------------- | ------------- | +| [AnimatorResult](#animatorresult) | Animator result.| + +**Example** + +```js +let options = { + duration: 1500, + easing: 'friction', + delay: 0, + fill: 'forwards', + direction: 'normal', + iterations: 3, + begin: 200.0, + end: 400.0, +}; +this.animator = animator.createAnimator(options); +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-ability.md b/en/application-dev/reference/apis/js-apis-app-ability-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..cfa11ddc30560c1ffa6a03eb8efccb8ea60b6d5b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-ability.md @@ -0,0 +1,61 @@ +# @ohos.app.ability.Ability (Ability Base Class) + +This is the base class of [UIAbility](js-apis-app-ability-uiAbility.md) and [ExtensionAbility](js-apis-app-ability-extensionAbility.md). It provides the callbacks for system configuration updates and memory level updates. You cannot inherit from this base class. + +> **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. + +## Ability.onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| + +**Example** + ```ts +// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example. +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } +} + ``` + +## Ability.onMemoryLevel + +onMemoryLevel(level: AbilityConstant.MemoryLevel): void; + +Called when the system adjusts the memory level. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| + +**Example** + + ```ts +// You are not allowed to inherit from the top-level base class Ability. Therefore, the derived class UIAbility is used as an example. +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyUIAbility extends UIAbility { + onMemoryLevel(level) { + console.log('onMemoryLevel, level:' + JSON.stringify(level)); + } +} + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..766636a7c7d4cda38cb2b71395fd3f2575e2f784 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityConstant.md @@ -0,0 +1,217 @@ +# @ohos.app.ability.AbilityConstant (AbilityConstant) + +The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes. + +> **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. + +## Modules to Import + +```ts +import AbilityConstant from '@ohos.app.ability.AbilityConstant'; +``` + +## Attributes + +## AbilityConstant.LaunchParam + +Defines the parameters for starting an ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason, which is an enumerated type.| +| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit, which is an enumerated type.| + +## AbilityConstant.LaunchReason + +Enumerates the initial ability launch reasons. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| UNKNOWN | 0 | Unknown reason.| +| START_ABILITY | 1 | The ability is started by calling [startAbility](js-apis-ability-context.md#abilitycontextstartability).| +| CALL | 2 | The ability is started by calling [startAbilityByCall](js-apis-ability-context.md#abilitycontextstartabilitybycall).| +| CONTINUATION | 3 | The ability is started by means of cross-device migration.| +| APP_RECOVERY | 4 | The ability is automatically started when the application is restored from a fault.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onCreate(want, launchParam) { + if (launchParam.launchReason === AbilityConstant.LaunchReason.START_ABILITY) { + console.log("The ability has been started by the way of startAbility."); + } + } +} +``` + +## AbilityConstant.LastExitReason + +Enumerates the reasons for the last exit. You can use it together with [onCreate(want, launchParam)](js-apis-app-ability-uiAbility.md#uiabilityoncreate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| UNKNOWN | 0 | Unknown reason.| +| ABILITY_NOT_RESPONDING | 1 | The ability does not respond.| +| NORMAL | 2 | The ability exits normally.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onCreate(want, launchParam) { + if (launchParam.lastExitReason === AbilityConstant.LastExitReason.ABILITY_NOT_RESPONDING) { + console.log("The ability has exit last because the ability was not responding."); + } + } +} +``` + +## AbilityConstant.OnContinueResult + +Enumerates the ability continuation results. You can use it together with [onContinue(wantParam)](js-apis-app-ability-uiAbility.md#uiabilityoncontinue) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| AGREE | 0 | Continuation agreed.| +| REJECT | 1 | Continuation denied.| +| MISMATCH | 2 | Mismatch.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onContinue(wantParam) { + return AbilityConstant.OnConinueResult.AGREE; + } +} +``` + +## AbilityConstant.WindowMode + +Enumerates the window modes in which an ability can be displayed at startup. It can be used in **startAbility()** to specify the window mode when the ability is started. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value| Description | +| --- | --- | --- | +| WINDOW_MODE_UNDEFINED | 0 | Undefined window mode. | +| WINDOW_MODE_FULLSCREEN | 1 | The ability is displayed in full screen. | +| WINDOW_MODE_SPLIT_PRIMARY | 100 | The ability is displayed in the primary window in split-screen mode. | +| WINDOW_MODE_SPLIT_SECONDARY | 101 | The ability is displayed in the secondary window in split-screen mode. | +| WINDOW_MODE_FLOATING | 102 | The ability is displayed in a floating window.| + +**Example** + +```ts +let want = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" +}; +let option = { + windowMode: AbilityConstant.WindowMode.WINDOW_MODE_FULLSCREEN +}; + +// Ensure that the context is obtained. +this.context.startAbility(want, option).then(()={ + console.log("Succeed to start ability."); +}).catch((error)=>{ + console.log("Failed to start ability with error: " + JSON.stringify(error)); +}); +``` + +## AbilityConstant.MemoryLevel + +Enumerates the memory levels. You can use it in [onMemoryLevel(level)](js-apis-app-ability-ability.md#abilityonmemorylevel) of [Ability](js-apis-app-ability-ability.md) to complete different operations. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value| Description | +| --- | --- | --- | +| MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage.| +| MEMORY_LEVEL_LOW | 1 | Low memory usage. | +| MEMORY_LEVEL_CRITICAL | 2 | High memory usage. | + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onMemoryLevel(level) { + if (level === AbilityConstant.MemoryLevel.MEMORY_LEVEL_CRITICAL) { + console.log("The memory of device is critical, please release some memory."); + } + } +} +``` + +## AbilityConstant.OnSaveResult + +Enumerates the result types for the operation of saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| ALL_AGREE | 0 | Always agreed to save the status.| +| CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.| +| CONTINUATION_MISMATCH | 2 | Continuation mismatch.| +| RECOVERY_AGREE | 3 | Agreed to restore the saved status.| +| RECOVERY_REJECT | 4 | Rejected to restore the saved state.| +| ALL_REJECT | 5 | Always rejected to save the status.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onSaveState(reason, wantParam) { + return AbilityConstant.OnSaveResult.ALL_AGREE; + } +} +``` + +## AbilityConstant.StateType + +Enumerates the scenarios for saving application data. You can use it in [onSaveState(reason, wantParam)](js-apis-app-ability-uiAbility.md#uiabilityonsavestate) of [Ability](js-apis-app-ability-uiAbility.md) to complete different operations. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| CONTINUATION | 0 | Saving the status in continuation.| +| APP_RECOVERY | 1 | Saving the status in application recovery.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class MyAbility extends UIAbility { + onSaveState(reason, wantParam) { + if (reason === AbilityConstant.StateType.CONTINUATION) { + console.log("Save the ability data when the ability continuation."); + } + return AbilityConstant.OnSaveResult.ALL_AGREE; + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md new file mode 100644 index 0000000000000000000000000000000000000000..5cfa437047868a9183ae4bb4f41ff42eec47f5d7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityDelegatorRegistry.md @@ -0,0 +1,88 @@ +# @ohos.app.ability.abilityDelegatorRegistry (AbilityDelegatorRegistry) + +**AbilityDelegatorRegistry**, a module of the [Test Framework](../../ability-deprecated/ability-delegator.md), is used to obtain [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) and [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) objects. **AbilityDelegator** provides APIs for creating **AbilityMonitor** objects, which can be used to listen for ability lifecycle changes. **AbilityDelegatorArgs** provides APIs for obtaining test parameters. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs provided by this module can be used only in the test framework. + +## Modules to Import + +```ts +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; +``` + +## AbilityLifecycleState + +Enumerates the ability lifecycle states. It can be used in [getAbilityState(ability)](js-apis-inner-application-abilityDelegator.md#getabilitystate9) of [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) to return different ability lifecycle states. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------- | ---- | --------------------------- | +| UNINITIALIZED | 0 | The ability is in an invalid state. | +| CREATE | 1 | The ability is created.| +| FOREGROUND | 2 | The ability is running in the foreground. | +| BACKGROUND | 3 | The ability is running in the background. | +| DESTROY | 4 | The ability is destroyed.| + +## AbilityDelegatorRegistry.getAbilityDelegator + +getAbilityDelegator(): AbilityDelegator + +Obtains an [AbilityDelegator](js-apis-inner-application-abilityDelegator.md) object. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule the functionalities of the test framework.| + +**Example** + +```ts +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); + +let want = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" +}; +abilityDelegator.startAbility(want, (err) => { + if (err.code !== 0) { + console.log("Success start ability."); + } else { + console.log("Failed start ability, error: " + JSON.stringify(err)); + } +}) +``` + +## AbilityDelegatorRegistry.getArguments + +getArguments(): AbilityDelegatorArgs + +Obtains an [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) object. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) | [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md) object, which can be used to obtain test parameters.| + +**Example** + +```ts +import AbilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry'; + +let args = AbilityDelegatorRegistry.getArguments(); +console.info("getArguments bundleName:" + args.bundleName); +console.info("getArguments parameters:" + JSON.stringify(args.parameters)); +console.info("getArguments testCaseNames:" + args.testCaseNames); +console.info("getArguments testRunnerClassName:" + args.testRunnerClassName); +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..84be19350707fee37328ff8040b2986588afd2f8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityLifecycleCallback.md @@ -0,0 +1,303 @@ +# @ohos.app.ability.abilityLifecycleCallback (AbilityLifecycleCallback) + +The **AbilityLifecycleCallback** module defines the callbacks to receive lifecycle changes of [ApplicationContext](js-apis-inner-application-applicationContext.md). The callbacks include [onAbilityCreate](#abilitylifecyclecallbackonabilitycreate), [onWindowStageCreate](#abilitylifecyclecallbackonwindowstagecreate), [onWindowStageActive](#abilitylifecyclecallbackonwindowstageactive), [onWindowStageInactive](#abilitylifecyclecallbackonwindowstageinactive), [onWindowStageDestroy](#abilitylifecyclecallbackonwindowstagedestroy), [onAbilityDestroy](#abilitylifecyclecallbackonabilitydestroy), [onAbilityForeground](#abilitylifecyclecallbackonabilityforeground), [onAbilityBackground](#abilitylifecyclecallbackonabilitybackground), and [onAbilityContinue](#abilitylifecyclecallbackonabilitycontinue). + +> **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. + + +## Modules to Import + +```ts +import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; +``` + + +## AbilityLifecycleCallback.onAbilityCreate + +onAbilityCreate(ability: UIAbility): void; + +Called when an ability is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate."); + } +}; +``` + +## AbilityLifecycleCallback.onWindowStageCreate + +onWindowStageCreate(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate."); + } +}; +``` + +## AbilityLifecycleCallback.onWindowStageActive + +onWindowStageActive(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability gains focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive."); + } +}; +``` + +## AbilityLifecycleCallback.onWindowStageInactive + +onWindowStageInactive(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability loses focus. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive."); + } +}; +``` + +## AbilityLifecycleCallback.onWindowStageDestroy + +onWindowStageDestroy(ability: UIAbility, windowStage: window.WindowStage): void; + +Called when the window stage of an ability is destroyed. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy."); + } +}; +``` + +## AbilityLifecycleCallback.onAbilityDestroy + +onAbilityDestroy(ability: UIAbility): void; + +Called when an ability is destroyed. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy."); + } +}; +``` + +## AbilityLifecycleCallback.onAbilityForeground + +onAbilityForeground(ability: UIAbility): void; + +Called when an ability is switched from the background to the foreground. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground."); + } +}; +``` + +## AbilityLifecycleCallback.onAbilityBackground + +onAbilityBackground(ability: UIAbility): void; + +Called when an ability is switched from the foreground to the background. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground."); + } +}; +``` + +## AbilityLifecycleCallback.onAbilityContinue + +onAbilityContinue(ability: UIAbility): void; + +Called when an ability is continued on another device. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes| **Ability** object.| + +**Example** +```ts +let abilityLifecycleCallback = { + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue."); + } +}; +``` + +## Usage of AbilityLifecycleCallback + +**Example** + +MyFirstAbility.ts +```ts +import AbilityLifecycleCallback from "@ohos.app.ability.AbilityLifecycleCallback"; +import AbilityStage from "@ohos.app.ability.AbilityStage"; +import UIAbility from '@ohos.app.ability.UIAbility'; + +// Declare the ability lifecycle callbacks. A listener can be registered in applicationContext only after all the callbacks are configured. +let abilityLifecycleCallback = { + onAbilityCreate(ability){ + console.log("AbilityLifecycleCallback onAbilityCreate."); + }, + onWindowStageCreate(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageCreate."); + }, + onWindowStageActive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageActive."); + }, + onWindowStageInactive(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageInactive."); + }, + onWindowStageDestroy(ability, windowStage){ + console.log("AbilityLifecycleCallback onWindowStageDestroy."); + }, + onAbilityDestroy(ability){ + console.log("AbilityLifecycleCallback onAbilityDestroy."); + }, + onAbilityForeground(ability){ + console.log("AbilityLifecycleCallback onAbilityForeground."); + }, + onAbilityBackground(ability){ + console.log("AbilityLifecycleCallback onAbilityBackground."); + }, + onAbilityContinue(ability){ + console.log("AbilityLifecycleCallback onAbilityContinue."); + } +}; + +export default class MyFirstAbility extends UIAbility { + onCreate() { + console.log("MyAbilityStage onCreate"); + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Register the listener for the ability lifecycle changes through the applicationContext object. + try { + globalThis.lifecycleId = applicationContext.on("abilityLifecycle", abilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + } catch (paramError) { + console.log("error: " + paramError.code + " ," + paramError.message); + } + } +} +``` + +MySecondAbility.ts +```ts +import UIAbility from "ohos.app.ability.UIAbility"; + +export default class MySecondAbility extends UIAbility { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + // 3. Deregister the listener for the environment changes through the applicationContext object. + applicationContext.off("abilityLifecycle", globalThis.lifecycleId, (error) => { + if (error.code != 0) { + console.log("unregisterAbilityLifecycleCallback failed, error: " + JSON.stringify(error)); + } else { + console.log("unregisterAbilityLifecycleCallback success."); + } + }); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md new file mode 100644 index 0000000000000000000000000000000000000000..f7f9c49a4cdf1c9e8c92ad8b7c8bd977df525477 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityManager.md @@ -0,0 +1,388 @@ +# @ohos.app.ability.abilityManager (AbilityManager) + +The **AbilityManager** module provides APIs for obtaining, adding, and updating ability running information and state information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are system APIs and cannot be called by third-party applications. + +## Modules to Import + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; +``` + +## AbilityState + +Enumerates the ability states. This enum can be used together with [AbilityRunningInfo](js-apis-inner-application-abilityRunningInfo.md) to return the ability state. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This enum is an internal definition of a system API and cannot be called by third-party applications. + +| Name| Value| Description| +| -------- | -------- | -------- | +| INITIAL | 0 | The ability is in the initial state.| +| FOREGROUND | 9 | The ability is in the foreground state. | +| BACKGROUND | 10 | The ability is in the background state. | +| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | +| BACKGROUNDING | 12 | The ability is in the state of being switched to the background. | + +## updateConfiguration + +updateConfiguration(config: Configuration, callback: AsyncCallback\): void + +Updates the configuration. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.| +| callback | AsyncCallback\ | Yes | Callback used to return the API call result. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +const config = { + language: 'Zh-Hans', // Simplified Chinese. + colorMode: COLOR_MODE_LIGHT, // Light theme. + direction: DIRECTION_VERTICAL, // Vertical direction. + screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + displayId: 1, // The application is displayed on the display with ID 1. + hasPointerDevice: true, // A pointer device is connected. +}; + +try { + abilityManager.updateConfiguration(config, (err) => { + if (err.code !== 0) { + console.log("updateConfiguration fail, err: " + JSON.stringify(err)); + } else { + console.log("updateConfiguration success."); + } + }) +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## updateConfiguration + +updateConfiguration(config: Configuration): Promise\ + +Updates the configuration. This API uses a promise to return the result. + +**Permission required**: ohos.permission.UPDATE_CONFIGURATION + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes | New configuration. You only need to configure the items to be updated.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +const config = { + language: 'Zh-Hans', // Simplified Chinese. + colorMode: COLOR_MODE_LIGHT, // Light theme. + direction: DIRECTION_VERTICAL, // Vertical direction. + screenDensity: SCREEN_DENSITY_SDPI, // The screen resolution is SDPI. + displayId: 1, // The application is displayed on the display with ID 1. + hasPointerDevice: true, // A pointer device is connected. +}; + +try { + abilityManager.updateConfiguration(config).then(() => { + console.log('updateConfiguration success.'); + }).catch((err) => { + console.log('updateConfiguration fail, err: ' + JSON.stringify(err)); + }) +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(callback: AsyncCallback\>): void + +Obtains the ability running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +try { + abilityManager.getAbilityRunningInfos((err, data) => { + if (err.code !== 0) { + console.log("getAbilityRunningInfos fail, error: " + JSON.stringify(err)); + } else { + console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data)); + } + }); +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getAbilityRunningInfos + +getAbilityRunningInfos(): Promise\> + +Obtains the ability running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Callback used to return the API call result and the ability running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +try { + abilityManager.getAbilityRunningInfos().then((data) => { + console.log("getAbilityRunningInfos success, data: " + JSON.stringify(data)) + }).catch((err) => { + console.log("getAbilityRunningInfos fail, err: " + JSON.stringify(err)); + }); +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getExtensionRunningInfos + +getExtensionRunningInfos(upperLimit: number, callback: AsyncCallback\>): void + +Obtains the ExtensionAbility running information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 231-1.| +| callback | AsyncCallback\> | Yes | Callback used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +let upperLimit = 10; + +try { + abilityManager.getExtensionRunningInfos(upperLimit, (err, data) => { + if (err.code !== 0) { + console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err)); + } else { + console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data)); + } + }); +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getExtensionRunningInfos + +getExtensionRunningInfos(upperLimit: number): Promise\> + +Obtains the ExtensionAbility running information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| upperLimit | number | Yes| Maximum number of messages that can be obtained. The maximum value is 231-1.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\> | Promise used to return the API call result and the ExtensionAbility running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +let upperLimit = 10; + +try { + abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { + console.log("getExtensionRunningInfos success, data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("getExtensionRunningInfos fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); +} +``` + +## getTopAbility9+ + +getTopAbility(callback: AsyncCallback\): void; + +Obtains the top ability, which is the ability that has the window focus. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback. | + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +abilityManager.getTopAbility((err, data) => { + if (err.code !== 0) { + console.log("getTopAbility fail, err: " + JSON.stringify(err)); + } else { + console.log("getTopAbility success, data: " + JSON.stringify(data)); + } +}); +``` + +## getTopAbility + +getTopAbility(): Promise\; + +Obtains the top ability, which is the ability that has the window focus. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------- | +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the API call result and the element name of the top ability. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import abilityManager from '@ohos.app.ability.abilityManager'; + +abilityManager.getTopAbility().then((data) => { + console.log("getTopAbility success, data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getTopAbility fail, err: " + JSON.stringify(err)); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md new file mode 100644 index 0000000000000000000000000000000000000000..50feb82791f8992894641a296d6cb831fdc86680 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-abilityStage.md @@ -0,0 +1,135 @@ +# @ohos.app.ability.AbilityStage (AbilityStage) + +**AbilityStage** is a runtime class for HAP files. + +**AbilityStage** notifies you of when you can perform HAP initialization such as resource pre-loading and thread creation during the HAP loading. + +> **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. + +## Modules to Import + +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; +``` + +## AbilityStage.onCreate + +onCreate(): void + +Called when the application is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Example** + +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage.onCreate is called"); + } +} +``` + + +## AbilityStage.onAcceptWant + +onAcceptWant(want: Want): string; + +Called when a specified ability is started. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| + +**Example** + +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onAcceptWant(want) { + console.log("MyAbilityStage.onAcceptWant called"); + return "com.example.test"; + } +} +``` + + +## AbilityStage.onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the global configuration is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| + +**Example** + +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, language:' + config.language); + } +} +``` + +## AbilityStage.onMemoryLevel + +onMemoryLevel(level: AbilityConstant.MemoryLevel): void; + +Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [AbilityConstant.MemoryLevel](js-apis-app-ability-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| + +**Example** + +```ts +import AbilityStage from '@ohos.app.ability.AbilityStage'; + +class MyAbilityStage extends AbilityStage { + onMemoryLevel(level) { + console.log('onMemoryLevel, level:' + JSON.stringify(level)); + } +} +``` + +## AbilityStage.context + +context: AbilityStageContext; + +Defines the context of **AbilityStage**. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Description | +| ----------- | --------------------------- | ------------------------------------------------------------ | +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | The context is obtained in the callback invoked when initialization is performed during ability startup.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appManager.md b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md new file mode 100644 index 0000000000000000000000000000000000000000..840a395eac9e17558918dd7466aa9e0b178b1c4d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-appManager.md @@ -0,0 +1,983 @@ +# @ohos.app.ability.appManager (appManager) + +The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. + +> **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 + +```ts +import appManager from '@ohos.app.ability.appManager'; +``` + +## appManager.isRunningInStabilityTest + +static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void + +Checks whether this application is undergoing a stability test. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Type| Description| + | -------- | -------- | + |AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRunningInStabilityTest((err, flag) => { + if (err.code !== 0) { + console.log("isRunningInStabilityTest faile, err: " + JSON.stringify(err)); + } else { + console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag)); + } +}) +``` + + +## appManager.isRunningInStabilityTest + +static isRunningInStabilityTest(): Promise<boolean> + +Checks whether this application is undergoing a stability test. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is undergoing a stability test, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRunningInStabilityTest().then((flag) => { + console.log("The result of isRunningInStabilityTest is:" + JSON.stringify(flag)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` + + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(): Promise\; + +Checks whether this application is running on a RAM constrained device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRamConstrainedDevice().then((data) => { + console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(callback: AsyncCallback\): void; + +Checks whether this application is running on a RAM constrained device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Type| Description| + | -------- | -------- | + | AsyncCallback<boolean> |Callback used to return the API call result and the result **true** or **false**. You can perform error handling or custom processing in this callback. The value **true** means that the application is running on a RAM constrained device, and **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.isRamConstrainedDevice((err, data) => { + if (err.code !== 0) { + console.log("isRamConstrainedDevice faile, err: " + JSON.stringify(err)); + } else { + console.log("The result of isRamConstrainedDevice is:" + JSON.stringify(data)); + } +}) +``` + +## appManager.getAppMemorySize + +getAppMemorySize(): Promise\; + +Obtains the memory size of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<number> | Promise used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getAppMemorySize().then((data) => { + console.log("The size of app memory is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` + +## appManager.getAppMemorySize + +getAppMemorySize(callback: AsyncCallback\): void; + +Obtains the memory size of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Type| Description| + | -------- | -------- | + |AsyncCallback<number> |Callback used to return the API call result and the memory size. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getAppMemorySize((err, data) => { + if (err.code !== 0) { + console.log("getAppMemorySize faile, err: " + JSON.stringify(err)); + } else { + console.log("The size of app memory is:" + JSON.stringify(data)); + } +}) +``` + +## appManager.getProcessRunningInformation + +getProcessRunningInformation(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getProcessRunningInformation().then((data) => { + console.log("The process running information is:" + JSON.stringify(data)); +}).catch((error) => { + console.log("error:" + JSON.stringify(error)); +}); +``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Type| Description| +| -------- | -------- | +|AsyncCallback\> | Callback used to return the API call result and the process running information. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getProcessRunningInformation((err, data) => { + if (err.code !== 0) { + console.log("getProcessRunningInformation faile, err: " + JSON.stringify(err)); + } else { + console.log("The process running information is:" + JSON.stringify(data)); + } +}) +``` + +## appManager.on + +on(type: "applicationState", observer: ApplicationStateObserver): number; + +Registers an observer to listen for the state changes of all applications. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| + +**Return value** + +| Type| Description| +| --- | --- | +| number | Digital code of the observer, which will be used in **off()** to deregister the observer.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + } +} +try { + const observerId = appManager.on('applicationState', applicationStateObserver); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} +``` + +## appManager.on + +on(type: "applicationState", observer: ApplicationStateObserver, bundleNameList: Array\): number; + +Registers an observer to listen for the state changes of a specified application. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observer | [ApplicationStateObserver](./js-apis-inner-application-applicationStateObserver.md) | Yes| Application state observer, which is used to observe the lifecycle change of an application.| +| bundleNameList | `Array` | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| + +**Return value** + +| Type| Description| +| --- | --- | +| number | Digital code of the observer, which will be used in **off()** to deregister the observer.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + } +} +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + const observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} +``` + +## appManager.off + +off(type: "applicationState", observerId: number, callback: AsyncCallback\): void; + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observerId | number | Yes| Digital code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let observeId = 0; + +// 1. Register an application state observer. +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + } +} +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} + +// 2. Deregister the application state observer. +function unregisterApplicationStateObserverCallback(err) { + if (err.code !== 0) { + console.log("unregisterApplicationStateObserverCallback faile, err: " + JSON.stringify(err)); + } else { + console.log("unregisterApplicationStateObserverCallback success."); + } +} +try { + appManager.off("applicationState", observerId, unregisterApplicationStateObserverCallback); +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); +} +``` + +## appManager.off + +off(type: "applicationState", observerId: number): Promise\; + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **"applicationState"**.| +| observerId | number | Yes| Digital code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let observeId = 0; + +// 1. Register an application state observer. +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log(`[appManager] onForegroundApplicationChanged: ${JSON.stringify(appStateData)}`); + }, + onAbilityStateChanged(abilityStateData) { + console.log(`[appManager] onAbilityStateChanged: ${JSON.stringify(abilityStateData)}`); + }, + onProcessCreated(processData) { + console.log(`[appManager] onProcessCreated: ${JSON.stringify(processData)}`); + }, + onProcessDied(processData) { + console.log(`[appManager] onProcessDied: ${JSON.stringify(processData)}`); + }, + onProcessStateChanged(processData) { + console.log(`[appManager] onProcessStateChanged: ${JSON.stringify(processData)}`); + } +} +let bundleNameList = ['bundleName1', 'bundleName2']; +try { + observerId = appManager.on("applicationState", applicationStateObserver, bundleNameList); + console.log(`[appManager] observerCode: ${observerId}`); +} catch (paramError) { + console.log(`[appManager] error: ${paramError.code}, ${paramError.message} `); +} + +// 2. Deregister the application state observer. +try { + appManager.off("applicationState", observerId).then((data) => { + console.log("unregisterApplicationStateObserver success, data: " + JSON.stringify(data)); + }).catch((err) => { + console.log("unregisterApplicationStateObserver faile, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log('error: ' + paramError.code + ', ' + paramError.message); +} +``` + +## appManager.getForegroundApplications + +getForegroundApplications(callback: AsyncCallback\>): void; + +Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Callback used to return the API call result and an array holding the application state data. You can perform error handling or custom processing in this callback.| + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +function getForegroundApplicationsCallback(err, data) { + if (err.code !== 0) { + console.log("getForegroundApplicationsCallback fail, err: " + JSON.stringify(err)); + } else { + console.log("getForegroundApplicationsCallback success, data: " + JSON.stringify(data)); + } +} +try { + appManager.getForegroundApplications(getForegroundApplicationsCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## appManager.getForegroundApplications + +getForegroundApplications(): Promise\>; + +Obtains applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return an array holding the application state data| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +appManager.getForegroundApplications().then((data) => { + console.log("getForegroundApplications success, data: " + JSON.stringify(data)); +}).catch((err) => { + console.log("getForegroundApplications fail, err: " + JSON.stringify(err)); +}) +``` + +## appManager.killProcessWithAccount + +killProcessWithAccount(bundleName: string, accountId: number): Promise\ + +Kills a process by bundle name and account ID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +let accountId = 0; +try { + appManager.killProcessWithAccount(bundleName, accountId).then(() => { + console.log("killProcessWithAccount success"); + }).catch((err) => { + console.log("killProcessWithAccount fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + + +## appManager.killProcessWithAccount + +killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void + +Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | bundleName | string | Yes| Bundle name.| + | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + | callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +let accountId = 0; +function killProcessWithAccountCallback(err, data) { + if (err.code !== 0) { + console.log("killProcessWithAccountCallback fail, err: " + JSON.stringify(err)); + } else { + console.log("killProcessWithAccountCallback success."); + } +} +appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +``` + +## appManager.killProcessesByBundleName + +killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); + +Kills a process by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +function killProcessesByBundleNameCallback(err, data) { + if (err.code !== 0) { + console.log("killProcessesByBundleNameCallback fail, err: " + JSON.stringify(err)); + } else { + console.log("killProcessesByBundleNameCallback success."); + } +} +try { + appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## appManager.killProcessesByBundleName + +killProcessesByBundleName(bundleName: string): Promise\; + +Kills a process by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +try { + appManager.killProcessesByBundleName(bundleName).then((data) => { + console.log("killProcessesByBundleName success."); + }).catch((err) => { + console.log("killProcessesByBundleName fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## appManager.clearUpApplicationData + +clearUpApplicationData(bundleName: string, callback: AsyncCallback\); + +Clears application data by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +function clearUpApplicationDataCallback(err, data) { + if (err) { + console.log("clearUpApplicationDataCallback fail, err: " + JSON.stringify(err)); + } else { + console.log("clearUpApplicationDataCallback success."); + } +} +try { + appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## appManager.clearUpApplicationData + +clearUpApplicationData(bundleName: string): Promise\; + +Clears application data by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the API call result. You can perform error handling or custom processing in this callback.| + +**Error codes** + +| ID| Error Message| +| ------- | -------- | +| 16000050 | Internal error. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +import appManager from '@ohos.app.ability.appManager'; + +let bundleName = 'bundleName'; +try { + appManager.clearUpApplicationData(bundleName).then((data) => { + console.log("clearUpApplicationData success."); + }).catch((err) => { + console.log("clearUpApplicationData fail, err: " + JSON.stringify(err)); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## ApplicationState + +Enumerates the application states. This enum can be used together with [AbilityStateData](js-apis-inner-application-appStateData.md) to return the application state. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the application is being created. | +| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the application is active. | +| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | +| STATE_DESTROY | 5 | State indicating that the application is destroyed. | + +## ProcessState + +Enumerates the process states. This enum can be used together with [ProcessData](js-apis-inner-application-processData.md) to return the process state. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the process is being created. | +| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the process is active. | +| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. | +| STATE_DESTROY | 5 | State indicating that the process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md new file mode 100644 index 0000000000000000000000000000000000000000..e066ac119344842ffce617fd7934efa3712d895f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md @@ -0,0 +1,146 @@ +# @ohos.app.ability.appRecovery (appRecovery) + +The **appRecovery** module provides APIs for recovering faulty applications. + +> **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. In the current version, only applications with a single ability in a single process can be recovered. + +## Modules to Import +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +``` + + +## appRecovery.RestartFlag + +Enumerates the application restart flags. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| ALWAYS_RESTART | 0 | The application is restarted in all cases.| +| CPP_CRASH_NO_RESTART | 0x0001 | The application is not restarted in the case of CPP_CRASH.| +| JS_CRASH_NO_RESTART | 0x0002 | The application is not restarted in the case of JS_CRASH.| +| APP_FREEZE_NO_RESTART | 0x0004 | The application is not restarted in the case of APP_FREEZE.| +| NO_RESTART | 0xFFFF | The application is not restarted in any case.| + +## appRecovery.SaveOccasionFlag + +Enumerates the scenarios for saving the application state. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| SAVE_WHEN_ERROR | 0x0001 | Saving the application state when an application fault occurs.| +| SAVE_WHEN_BACKGROUND | 0x0002 | Saving the application state when the application is switched to the background.| + +## appRecovery.SaveModeFlag + +Enumerates the application state saving modes. This enum is used as an input parameter of [enableAppRecovery](#apprecoveryenableapprecovery). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| SAVE_WITH_FILE | 0x0001 | The application state is saved and written to the local file cache.| +| SAVE_WITH_SHARED_MEMORY | 0x0002 | The application state is saved in the memory. When the application exits due to a fault, it is written to the local file cache.| + +## appRecovery.enableAppRecovery + +enableAppRecovery(restart?: [RestartFlag](#apprecoveryrestartflag), saveOccasion?: [SaveOccasionFlag](#apprecoverysaveoccasionflag), saveMode?: [SaveModeFlag](#apprecoverysavemodeflag)) : void; + +Enables application recovery. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| restart | [RestartFlag](#apprecoveryrestartflag) | No| Whether the application is restarted upon a fault. By default, the application is not restarted.| +| saveOccasion | [SaveOccasionFlag](#apprecoverysaveoccasionflag) | No| Scenario for saving the application state. By default, the state is saved when a fault occurs.| +| saveMode | [SaveModeFlag](#apprecoverysavemodeflag) | No| Application state saving mode. By default, the application state is written to the local file cache.| + +**Example** + +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +import AbilityStage from '@ohos.app.ability.AbilityStage'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class MyAbility extends UIAbility { + onCreate() { + appRecovery.enableAppRecovery( + appRecovery.RestartFlag::ALWAYS_RESTART, + appRecovery.SaveOccasionFlag::SAVE_WHEN_ERROR, + appRecovery.SaveModeFlag::SAVE_WITH_FILE + ); + } +} +``` + +## appRecovery.restartApp + +restartApp(): void; + +Restarts the application. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + + +**Example** + +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +import errorManager from '@ohos.app.ability.errorManager'; + +let observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + appRecovery.restartApp(); + } +}; + +try { + errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## appRecovery.saveAppState + +saveAppState(): boolean; + +Saves the application state. This API can be used together with APIs of [errorManager](js-apis-app-ability-errorManager.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether the application state is saved. The value **true** is returned if the application state is saved, and **false** is returned otherwise.| + +**Example** + +```ts +import appRecovery from '@ohos.app.ability.appRecovery'; +import errorManager from '@ohos.app.ability.errorManager'; + +let observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + appRecovery.saveAppState(); + } +}; + +try { + errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-common.md b/en/application-dev/reference/apis/js-apis-app-ability-common.md new file mode 100644 index 0000000000000000000000000000000000000000..5cc9b61b90fb3072aacf530fdaee0ae2633f7ac0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-common.md @@ -0,0 +1,62 @@ +# @ohos.app.ability.common (Context) + +The **Common** module provides all level-2 module APIs for developers to export. + +> **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. + +## Modules to Import + +```ts +import common from '@ohos.app.ability.common' +``` + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Type | Description | +| ----------- | -------------------- | ------------------------------------------------------------ | +| UIAbilityContext | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Level-2 module **UIAbilityContext**. | +| AbilityStageContext | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | Level-2 module **AbilityStageContext**.| +| ApplicationContext | [ApplicationContext](js-apis-inner-application-applicationContext.md) | Level-2 module **ApplicationContext**.| +| BaseContext | [BaseContext](js-apis-inner-application-baseContext.md) | Level-2 module **BaseContext**.| +| Context | [Context](js-apis-inner-application-context.md) | Level-2 module **Context**.| +| ExtensionContext | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Level-2 module **ExtensionContext**.| +| FormExtensionContext | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Level-2 module **FormExtensionContext**.| +| AreaMode | [AreaMode](#areamode) | Enumerated values of **AreaMode**.| +| EventHub | [EventHub](js-apis-inner-application-eventHub.md) | Level-2 module **EventHub**.| +| PermissionRequestResult | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | Level-2 module **PermissionRequestResult**.| +| PacMap | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#PacMap) | Level-2 module **PacMap**.| +| AbilityResult | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Level-2 module **AbilityResult**.| +| ConnectOptions | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Level-2 module **ConnectOptions**.| + +**Example** +```ts +import common from '@ohos.app.ability.common' + +let uiAbilityContext: common.UIAbilityContext; +let abilityStageContext: common.AbilityStageContext; +let applicationContext: common.ApplicationContext; +let baseContext: common.BaseContext; +let context: common.Context; +let extensionContext: common.ExtensionContext; +let formExtensionContext: common.FormExtensionContext; +let areaMode: common.AreaMode; +let eventHub: common.EventHub; +let permissionRequestResult: common.PermissionRequestResult; +let pacMap: common.PacMap; +let abilityResult: common.AbilityResult; +let connectOptions: common.ConnectOptions; +``` + +## AreaMode + +Enumerates the data encryption levels. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| --------------- | ---- | --------------- | +| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on. | +| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configuration.md b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..88aab2d4026afac5edaf8c3c7ff58033976e3e66 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-configuration.md @@ -0,0 +1,55 @@ +# @ohos.app.ability.Configuration (Configuration) + +The **Configuration** module defines environment change information. + +> **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 + +```ts +import Configuration from '@ohos.app.ability.Configuration' +``` + +**System capability**: SystemCapability.Ability.AbilityBase + + | Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| language | string | Yes| Yes| Language of the application, for example, **zh**.| +| colorMode | [ColorMode](js-apis-app-ability-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| +| direction | [Direction](js-apis-app-ability-configurationConstant.md#configurationconstantdirection) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| +| screenDensity | [ScreenDensity](js-apis-app-ability-configurationConstant.md#configurationconstantscreendensity) | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| +| displayId | number | Yes| No| ID of the display where the application is located.| +| hasPointerDevice | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| + +For details about the fields, see the **ohos.app.ability.Configuration.d.ts** file. + +**Example** + + ```ts + import UIAbility from '@ohos.app.ability.UIAbility'; + + export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + let envCallback = { + onConfigurationUpdated(config) { + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + let language = config.language; + let colorMode = config.colorMode; + let direction = config.direction; + let screenDensity = config.screenDensity; + let displayId = config.displayId; + let hasPointerDevice = config.hasPointerDevice; + } + }; + try { + let applicationContext = this.context.getApplicationContext(); + let callbackId = applicationContext.on("environment", envCallback); + console.log("callbackId: " + callbackId); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..bd56e256603930f874c9ba2c064462c8fad594a8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-configurationConstant.md @@ -0,0 +1,55 @@ +# @ohos.app.ability.ConfigurationConstant (ConfigurationConstant) + +The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. + +> **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 + +```ts +import ConfigurationConstant from '@ohos.app.ability.ConfigurationConstant'; +``` + +## ConfigurationConstant.ColorMode + +You can obtain the value of this constant by calling the **ConfigurationConstant.ColorMode** API. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name| Value| Description| +| -------- | -------- | -------- | +| COLOR_MODE_NOT_SET | -1 | Unspecified color mode.| +| COLOR_MODE_DARK | 0 | Dark mode.| +| COLOR_MODE_LIGHT | 1 | Light mode.| + + +## ConfigurationConstant.Direction + +You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name| Value| Description| +| -------- | -------- | -------- | +| DIRECTION_NOT_SET | -1 | Unspecified direction.| +| DIRECTION_VERTICAL | 0 | Vertical direction.| +| DIRECTION_HORIZONTAL | 1 | Horizontal direction.| + + +## ConfigurationConstant.ScreenDensity + +You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name| Value| Description| +| -------- | -------- | -------- | +| SCREEN_DENSITY_NOT_SET | 0 | Unspecified screen resolution.| +| SCREEN_DENSITY_SDPI | 120 | The screen resolution is sdpi.| +| SCREEN_DENSITY_MDPI | 160 | The screen resolution is mdpi.| +| SCREEN_DENSITY_LDPI | 240 | The screen resolution is ldpi.| +| SCREEN_DENSITY_XLDPI | 320 | The screen resolution is xldpi.| +| SCREEN_DENSITY_XXLDPI | 480 | The screen resolution is xxldpi.| +| SCREEN_DENSITY_XXXLDPI | 640 | The screen resolution is xxxldpi.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..0c39c8fa01fe62a537614287f3d27645c8b0f354 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-contextConstant.md @@ -0,0 +1,25 @@ +# @ohos.app.ability.contextConstant (ContextConstant) + +The **ContextConstant** module defines context-related enums. Currently, it defines only the enum of data encryption levels. + +> **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. + +## Modules to Import + +```ts +import contextConstant from '@ohos.app.ability.contextConstant'; +``` + +## ContextConstant.AreaMode + +You can obtain the value of this constant by calling the **ContextConstant.AreaMode** API. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.| +| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..0cb95a9abfd6b90f1efacc431070ef6b3397e1e6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-environmentCallback.md @@ -0,0 +1,62 @@ +# @ohos.app.ability.EnvironmentCallback (EnvironmentCallback) + +The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. + +> **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. + + +## Modules to Import + +```ts +import EnvironmentCallback from "@ohos.app.ability.EnvironmentCallback"; +``` + + +## EnvironmentCallback.onConfigurationUpdated + +onConfigurationUpdated(config: Configuration): void; + +Called when the system environment changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | config | [Configuration](js-apis-app-ability-configuration.md) | Yes| **Configuration** object after the change.| + +**Example** + + + ```ts +import UIAbility from "@ohos.app.ability.Ability"; + +var callbackId; + +export default class MyAbility extends UIAbility { + onCreate() { + console.log("MyAbility onCreate") + globalThis.applicationContext = this.context.getApplicationContext(); + let EnvironmentCallback = { + onConfigurationUpdated(config){ + console.log("onConfigurationUpdated config:" + JSON.stringify(config)); + } + } + // 1. Obtain an applicationContext object. + let applicationContext = globalThis.applicationContext; + // 2. Register a listener for the environment changes through the applicationContext object. + callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); + console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); + } + onDestroy() { + let applicationContext = globalThis.applicationContext; + applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + }); + } +} + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e543a93e9ceb5af52f3cdb939a0cfd5d24145968 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md @@ -0,0 +1,121 @@ +# @ohos.app.ability.errorManager (ErrorManager) + +The **ErrorManager** module provides APIs for registering and deregistering error observers. For example, you can use the APIs to register an observer when your application wants to capture JS crashes. + +> **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 +```ts +import errorManager from '@ohos.app.ability.errorManager' +``` + +## ErrorManager.on + +on(type: "error", observer: ErrorObserver): number; + +Registers an error observer. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observer | [ErrorObserver](./js-apis-inner-application-errorObserver.md) | Yes| Digital code of the observer.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | number | Index of the observer.| + +**Example** + +```ts +var observer = { + onUnhandledException(errorMsg) { + console.log('onUnhandledException, errorMsg: ', errorMsg) + } +} +var observerId = -1; +try { + observerId = errorManager.on("error", observer); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## ErrorManager.off + +off(type: "error", observerId: number, callback: AsyncCallback\): void; + +Deregisters an error observer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observerId | number | Yes| Index of the observer returned by **on()**.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + +```ts +var observerId = 100; + +function unregisterErrorObserverCallback(err) { + if (err) { + console.log('------------ unregisterErrorObserverCallback ------------', err); + } +} +try { + errorManager.off("error", observerId, unregisterErrorObserverCallback); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` + +## ErrorManager.off + +off(type: "error", observerId: number): Promise\; + +Deregisters an error observer. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the API to call. It is fixed at **"error"**.| +| observerId | number | Yes| Index of the observer returned by **on()**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var observerId = 100; +try { + errorManager.off("error", observerId) + .then((data) => { + console.log('----------- unregisterErrorObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- unregisterErrorObserver fail ----------', err); + }) +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} + +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..d532723b43a1c31f2b01b35799747ec689df5099 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-extensionAbility.md @@ -0,0 +1,10 @@ +# @ohos.app.ability.ExtensionAbility (ExtensionAbility Base Class) + +**ExtensionAbility** is the base class for scenario-specific ExtensionAbilities. It is inherited from [Ability](js-apis-app-ability-ability.md), with no attribute or method added. You cannot inherit from this base class. + +> **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. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore diff --git a/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md new file mode 100644 index 0000000000000000000000000000000000000000..434fb19383e072a36352012300c2a755769d6c1f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-missionManager.md @@ -0,0 +1,1027 @@ +# @ohos.app.ability.missionManager (missionManager) + +The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. + +> **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 + +```ts +import missionManager from '@ohos.app.ability.missionManager'; +``` + +## Required Permissions + +ohos.permission.MANAGE_MISSIONS + +## missionManager.on + +on(type:"mission", listener: MissionListener): number; + +Registers a listener to observe the mission status. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +}; + +var listenerId = -1; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("[Demo] EntryAbility onCreate"); + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId != -1) { + missionManager.off("mission", listenerId).catch(function (err) { + console.log(err); + }); + } + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + console.log("[Demo] EntryAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // The main window is created. Set a main page for this ability. + console.log("[Demo] EntryAbility onWindowStageCreate") + try { + listenerId = missionManager.on("mission", listener); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + + windowStage.loadContent("pages/index", (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)) + }); + + if (globalThis.flag) { + return; + } + } +}; +``` + + +## missionManager.off + +off(type: "mission", listenerId: number, callback: AsyncCallback<void>): void; + +Deregisters a mission status listener. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +}; + +var listenerId = -1; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("[Demo] EntryAbility onCreate") + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId != -1) { + missionManager.off("mission", listenerId, (err) => { + console.log(err); + }); + } + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + console.log("[Demo] EntryAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // The main window is created. Set a main page for this ability. + console.log("[Demo] EntryAbility onWindowStageCreate") + try { + listenerId = missionManager.on("mission", listener); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + + windowStage.loadContent("pages/index", (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)) + }); + + if (globalThis.flag) { + return; + } + } +}; +``` + + +## missionManager.off + +off(type: "mission", listenerId: number): Promise<void>; + +Deregisters a mission status listener. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **on()**.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +}; + +var listenerId = -1; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("[Demo] EntryAbility onCreate") + globalThis.abilityWant = want; + globalThis.context = this.context; + } + + onDestroy() { + try { + if (listenerId != -1) { + missionManager.off("mission", listenerId).catch(function (err) { + console.log(err); + }); + } + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + console.log("[Demo] EntryAbility onDestroy") + } + + onWindowStageCreate(windowStage) { + // The main window is created. Set a main page for this ability. + console.log("[Demo] EntryAbility onWindowStageCreate") + try { + listenerId = missionManager.on("mission", listener); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + + windowStage.loadContent("pages/index", (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)) + }); + + if (globalThis.flag) { + return; + } + } +}; +``` + + +## missionManager.getMissionInfo + +getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<MissionInfo>): void; + +Obtains the information about a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionInfo](./js-apis-inner-application-missionInfo.md))> | Yes| Callback used to return the mission information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + let testMissionId = 1; + try { + var allMissions=await missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); + if (allMissions && allMissions.length > 0) { + testMissionId = allMissions[0].missionId; + } + + missionManager.getMissionInfo("", testMissionId, (error, mission) => { + if (error) { + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + } else { + console.log("mission.missionId = " + mission.missionId); + console.log("mission.runningState = " + mission.runningState); + console.log("mission.lockedState = " + mission.lockedState); + console.log("mission.timestamp = " + mission.timestamp); + console.log("mission.label = " + mission.label); + console.log("mission.iconPath = " + mission.iconPath); + } + }); + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getMissionInfo + +getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; + +Obtains the information about a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionInfo](./js-apis-inner-application-missionInfo.md)> | Promise used to return the mission information obtained.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 1; +try { + missionManager.getMissionInfo("", testMissionId).then((data) => { + console.info('getMissionInfo successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionInfo failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getMissionInfo failed. Cause: ' + error.message); +} +``` + +## missionManager.getMissionInfos + +getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Array<MissionInfo>>): void; + +Obtains information about all missions. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | numMax | number | Yes| Maximum number of missions whose information can be obtained.| + | callback | AsyncCallback<Array<[MissionInfo](./js-apis-inner-application-missionInfo.md)>> | Yes| Callback used to return the array of mission information obtained.| + +**Example** + + ```ts + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + if (error) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + } else { + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + } + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` + + +## missionManager.getMissionInfos + +getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionInfo>>; + +Obtains information about all missions. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | numMax | number | Yes| Maximum number of missions whose information can be obtained.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<Array<[MissionInfo](./js-apis-inner-application-missionInfo.md)>> | Promise used to return the array of mission information obtained.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.getMissionInfos("", 10).then((data) => { + console.info('getMissionInfos successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionInfos failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getMissionInfos failed. Cause: ' + error.message); +} +``` + +## missionManager.getMissionSnapShot + +getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback<MissionSnapshot>): void; + +Obtains the snapshot of a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + +**Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.getMissionSnapShot("", testMissionId, (err, data) => { + if (err) { + console.error('getMissionSnapShot failed:' + err.message); + } else { + console.info('getMissionSnapShot successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getMissionSnapShot failed:' + err.message); +} +``` + +## missionManager.getMissionSnapShot + +getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnapshot>; + +Obtains the snapshot of a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| + +**Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.getMissionSnapShot("", testMissionId).then((data) => { + console.info('getMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getMissionSnapShot failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getMissionSnapShot failed. Cause: ' + error.message); +} +``` + +## missionManager.getLowResolutionMissionSnapShot + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback\): void; + +Obtains the low-resolution snapshot of a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + +**Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.getLowResolutionMissionSnapShot("", testMissionId, (err, data) => { + if (err) { + console.error('getLowResolutionMissionSnapShot failed:' + err.message); + } else { + console.info('getLowResolutionMissionSnapShot successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('getLowResolutionMissionSnapShot failed:' + err.message); +} +``` + +## missionManager.getLowResolutionMissionSnapShot + +getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\; + +Obtains the low-resolution snapshot of a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.getLowResolutionMissionSnapShot("", testMissionId).then((data) => { + console.info('getLowResolutionMissionSnapShot successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('getLowResolutionMissionSnapShot failed. Cause: ' + error.message); +} +``` + + +## missionManager.lockMission + +lockMission(missionId: number, callback: AsyncCallback<void>): void; + +Locks a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.lockMission(testMissionId, (err, data) => { + if (err) { + console.error('lockMission failed:' + err.message); + } else { + console.info('lockMission successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('lockMission failed:' + err.message); +} +``` + +## missionManager.lockMission + +lockMission(missionId: number): Promise<void>; + +Locks a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.lockMission(testMissionId).then((data) => { + console.info('lockMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('lockMission failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('lockMission failed. Cause: ' + error.message); +} +``` + +## missionManager.unlockMission + +unlockMission(missionId: number, callback: AsyncCallback<void>): void; + +Unlocks a given mission. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| missionId | number | Yes| Mission ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.unlockMission(testMissionId, (err, data) => { + if (err) { + console.error('unlockMission failed:' + err.message); + } else { + console.info('unlockMission successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('unlockMission failed:' + err.message); +} +``` + +## missionManager.unlockMission + +unlockMission(missionId: number): Promise<void>; + +Unlocks a given mission. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.unlockMission(testMissionId).then((data) => { + console.info('unlockMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('unlockMission failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('unlockMission failed. Cause: ' + error.message); +} +``` + +## missionManager.clearMission + +clearMission(missionId: number, callback: AsyncCallback<void>): void; + +Clears a given mission, regardless of whether it is locked. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.clearMission(testMissionId, (err, data) => { + if (err) { + console.error('clearMission failed:' + err.message); + } else { + console.info('clearMission successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('clearMission failed:' + err.message); +} +``` + + +## missionManager.clearMission + +clearMission(missionId: number): Promise<void>; + +Clears a given mission, regardless of whether it is locked. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.clearMission(testMissionId).then((data) => { + console.info('clearMission successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('clearMission failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('clearMission failed. Cause: ' + error.message); +} +``` + +## missionManager.clearAllMissions + +clearAllMissions(callback: AsyncCallback<void>): void; + +Clears all unlocked missions. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.clearAllMissions(err => { + if (err) { + console.error('clearAllMissions failed:' + err.message); + } else { + console.info('clearAllMissions successfully.'); + } + }); +} catch (err) { + console.error('clearAllMissions failed:' + err.message); +} +``` + +## missionManager.clearAllMissions + +clearAllMissions(): Promise<void>; + +Clears all unlocked missions. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: 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.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +try { + missionManager.clearAllMissions(bundleName).then(() => { + console.info('clearAllMissions successfully.'); + }).catch(err => { + console.error('clearAllMissions failed:' + err.message); + }); +} catch (err) { + console.error('clearAllMissions failed:' + err.message); +} +``` + +## missionManager.moveMissionToFront + +moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void; + +Switches a given mission to the foreground. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId, (err, data) => { + if (err) { + console.error('moveMissionToFront failed:' + err.message); + } else { + console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('moveMissionToFront failed:' + err.message); +} +``` + +## missionManager.moveMissionToFront + +moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCallback<void>): void; + +Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId, {windowMode : 101}, (err, data) => { + if (err) { + console.error('moveMissionToFront failed:' + err.message); + } else { + console.info('moveMissionToFront successfully:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('moveMissionToFront failed:' + err.message); +} +``` + +## missionManager.moveMissionToFront + +moveMissionToFront(missionId: number, options?: StartOptions): Promise<void>; + +Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_MISSIONS + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | missionId | number | Yes| Mission ID.| + | options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + +**Example** + +```ts +import missionManager from '@ohos.app.ability.missionManager'; + +let testMissionId = 2; +try { + missionManager.moveMissionToFront(testMissionId).then((data) => { + console.info('moveMissionToFront successfully. Data: ' + JSON.stringify(data)); + }).catch(error => { + console.error('moveMissionToFront failed. Cause: ' + error.message); + }); +} catch (error) { + console.error('moveMissionToFront failed. Cause: ' + error.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md new file mode 100644 index 0000000000000000000000000000000000000000..a2090ed00e60cac1b5452bf6357f47cfb3c7be2e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-quickFixManager.md @@ -0,0 +1,194 @@ +# @ohos.app.ability.quickFixManager (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 + +```ts +import quickFixManager from '@ohos.app.ability.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 | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| moduleName | string | Yes | Name of the HAP file. | +| originHapHash | string | Yes | Hash value of the HAP file. | +| quickFixFilePath | 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 | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name. | +| bundleVersionCode | number | Yes | Internal version number of the application. | +| bundleVersionName | string | Yes | Version number of the application that is shown to users. | +| quickFixVersionCode | number | Yes | Version code of the quick fix patch package. | +| quickFixVersionName | string | Yes | Text description of the version number of the quick fix patch package. | +| hapModuleQuickFixInfo | 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\ | Yes| Quick fix files, each of which must contain a valid file path.| + | callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + +```ts + try { + 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') + } + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } +``` + +## 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\ | Yes| Quick fix files, each of which must contain a valid file path.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise\ | Promise used to return the result.| + +**Example** + +```ts + let hapModuleQuickFixFiles = ["/data/storage/el2/base/entry.hqf"] + try { + quickFixManager.applyQuickFix(hapModuleQuickFixFiles).then(() => { + console.info('applyQuickFix success') + }).catch((error) => { + console.info(`applyQuickFix err: + ${error}`) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } +``` + +## 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 | Yes|Bundle name. | +| callback | AsyncCallback\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Yes| Callback used to return the quick fix information.| + +**Example** + +```ts + try { + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName, (error, data) => { + if (error) { + console.info(`getApplicationQuickFixInfo error: + ${error}`) + } else { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + } + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } +``` + +## 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 | Yes| Bundle name.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise\<[ApplicationQuickFixInfo](#applicationquickfixinfo)> | Promise used to return the quick fix information.| + +**Example** + + ```ts + try { + let bundleName = "bundleName" + quickFixManager.getApplicationQuickFixInfo(bundleName).then((data) => { + console.info(`getApplicationQuickFixInfo success: + ${data}`) + }).catch((error) => { + console.info(`getApplicationQuickFixInfo err: + ${error}`) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..0efdb59d5eaed4c2b70e5ff666b0c9d63b11212f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-serviceExtensionAbility.md @@ -0,0 +1,252 @@ +# @ohos.app.ability.ServiceExtensionAbility (ServiceExtensionAbility) + +The **ServiceExtensionAbility** module provides lifecycle callbacks when a ServiceExtensionAbility (background service) is created, destroyed, connected, or disconnected. + +> **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. + +## Modules to Import + +```ts +import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility'; +``` + +## Required Permissions + +None. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| ServiceExtensionContext, which is inherited from **ExtensionContext**.| + + +## ServiceExtensionAbility.onCreate + +onCreate(want: Want): void; + +Called when a ServiceExtensionAbility is created to initialize the service logic. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onCreate(want) { + console.log('onCreate, want:' + want.abilityName); + } + } + ``` + + +## ServiceExtensionAbility.onDestroy + +onDestroy(): void; + +Called when this ServiceExtensionAbility is destroyed to clear resources. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onDestroy() { + console.log('onDestroy'); + } + } + ``` + + +## ServiceExtensionAbility.onRequest + +onRequest(want: Want, startId: number): void; + +Called following **onCreate()** when a ServiceExtensionAbility is started by calling **startAbility()**. The value of **startId** is incremented for each ability that is started. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| +| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onRequest(want, startId) { + console.log('onRequest, want:' + want.abilityName); + } + } + ``` + + +## ServiceExtensionAbility.onConnect + +onConnect(want: Want): rpc.RemoteObject; + +Called following **onCreate()** when a ServiceExtensionAbility is started by calling **connectAbility()**. A **RemoteObject** object is returned for communication between the server and client. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| rpc.RemoteObject | A **RemoteObject** object used for communication between the server and client.| + +**Example** + + ```ts + import rpc from '@ohos.rpc' + class StubTest extends rpc.RemoteObject{ + constructor(des) { + super(des); + } + onConnect(code, data, reply, option) { + } + } + class ServiceExt extends ServiceExtension { + onConnect(want) { + console.log('onConnect , want:' + want.abilityName); + return new StubTest("test"); + } + } + ``` + + +## ServiceExtensionAbility.onDisconnect + +onDisconnect(want: Want): void; + +Called when a client is disconnected from this ServiceExtensionAbility. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onDisconnect(want) { + console.log('onDisconnect, want:' + want.abilityName); + } + } + ``` + +## ServiceExtensionAbility.onReconnect + +onReconnect(want: Want): void; + +Called when a new client attempts to connect to this ServiceExtensionAbility after all previous clients are disconnected. This capability is reserved. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-app-ability-want.md)| Yes| Want information related to this ServiceExtensionAbility, including the ability name and bundle name.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onReconnect(want) { + console.log('onReconnect, want:' + want.abilityName); + } + } + ``` + +## ServiceExtensionAbility.onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the configuration of this ServiceExtensionAbility is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-app-ability-configuration.md) | Yes| New configuration.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } + } + ``` + +## ServiceExtensionAbility.onDump + +onDump(params: Array\): Array\; + +Dumps the client information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| + +**Example** + + ```ts + class ServiceExt extends ServiceExtension { + onDump(params) { + console.log('dump, params:' + JSON.stringify(params)); + return ["params"] + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md new file mode 100644 index 0000000000000000000000000000000000000000..3e95fbf541e7ed79834673c2ca97b1398bc73989 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-startOptions.md @@ -0,0 +1,24 @@ +# @ohos.app.ability.StartOptions (StartOptions) + +**StartOptions** is used as an input parameter of [startAbility()](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability-1) to specify the window mode of an ability. + +> **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. + +## Modules to Import + +```ts +import StartOptions from '@ohos.app.ability.StartOptions'; +``` + +## Attributes + + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| +| displayId | number | No| Display ID. The default value is **0**, indicating the current display.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..38d9f5428c37873ae9f786ed0f391142f30a011b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-uiAbility.md @@ -0,0 +1,739 @@ +# @ohos.app.ability.UIAbility (UIAbility) + +UIAbility is an application component that has the UI. The **UIAbility** module provides lifecycle callback such as component creation, destruction, and foreground/background switching. It also provides the following capabilities related to component collaboration: + +- [Caller](#caller): an object returned by [startAbilityByCall](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartabilitybycall). The CallerAbility (caller) uses this object to communicate with the CalleeAbility (callee). +- [Callee](#callee): an internal object of UIAbility. The CalleeAbility (callee) uses this object to communicate with the CallerAbility (caller). + +> **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. + +## Modules to Import + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of the UIAbility.| +| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the UIAbility.| +| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the UIAbility was started last time.| +| callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| + +## UIAbility.onCreate + +onCreate(want: Want, param: AbilityConstant.LaunchParam): void; + +Called to initialize the service logic when a UIAbility is created. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this UIAbility, including the ability name and bundle name.| +| param | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Parameters for starting the UIAbility, and the reason for the last abnormal exit.| + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onCreate(want, param) { + console.log('onCreate, want:' + want.abilityName); + } + } + ``` + + +## UIAbility.onWindowStageCreate + +onWindowStageCreate(windowStage: window.WindowStage): void + +Called when a **WindowStage** is created for this UIAbility. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + console.log('onWindowStageCreate'); + } + } + ``` + + +## UIAbility.onWindowStageDestroy + +onWindowStageDestroy(): void + +Called when the **WindowStage** is destroyed for this UIAbility. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onWindowStageDestroy() { + console.log('onWindowStageDestroy'); + } + } + ``` + + +## UIAbility.onWindowStageRestore + +onWindowStageRestore(windowStage: window.WindowStage): void + +Called when the **WindowStage** is restored during the migration of this UIAbility, which is a multi-instance ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onWindowStageRestore(windowStage) { + console.log('onWindowStageRestore'); + } + } + ``` + + +## UIAbility.onDestroy + +onDestroy(): void; + +Called when this UIAbility is destroyed to clear resources. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onDestroy() { + console.log('onDestroy'); + } + } + ``` + + +## UIAbility.onForeground + +onForeground(): void; + +Called when this UIAbility is switched from the background to the foreground. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onForeground() { + console.log('onForeground'); + } + } + ``` + + +## UIAbility.onBackground + +onBackground(): void; + +Called when this UIAbility is switched from the foreground to the background. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onBackground() { + console.log('onBackground'); + } + } + ``` + + +## UIAbility.onContinue + +onContinue(wantParam : {[key: string]: any}): AbilityConstant.OnContinueResult; + +Called to save data during the ability migration preparation process. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wantParam | {[key: string]: any} | Yes| **want** parameter.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [AbilityConstant.OnContinueResult](js-apis-app-ability-abilityConstant.md#abilityconstantoncontinueresult) | Continuation result.| + +**Example** + + ```ts + import AbilityConstant from "@ohos.app.ability.AbilityConstant" + class MyUIAbility extends UIAbility { + onContinue(wantParams) { + console.log('onContinue'); + wantParams["myData"] = "my1234567"; + return AbilityConstant.OnContinueResult.AGREE; + } + } + ``` + + +## UIAbility.onNewWant + +onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; + +Called when a new Want is passed in and this UIAbility is started again. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-app-ability-want.md) | Yes| Want information, such as the ability name and bundle name.| +| launchParams | [AbilityConstant.LaunchParam](js-apis-app-ability-abilityConstant.md#abilityconstantlaunchparam) | Yes| Reason for the UIAbility startup and the last abnormal exit.| + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onNewWant(want, launchParams) { + console.log('onNewWant, want:' + want.abilityName); + console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); + } + } + ``` + +## UIAbility.onDump + +onDump(params: Array\): Array\; + +Dumps client information. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| + +**Example** + + ```ts + class MyUIAbility extends UIAbility { + onDump(params) { + console.log('dump, params:' + JSON.stringify(params)); + return ["params"] + } + } + ``` + + +## UIAbility.onSaveState + +onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; + +Called when the framework automatically saves the UIAbility state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). If automatic state saving is enabled, **onSaveState** is called to save the state of this UIAbility. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| reason | [AbilityConstant.StateType](js-apis-app-ability-abilityConstant.md#abilityconstantstatetype) | Yes| Reason for triggering the callback to save the UIAbility state.| +| wantParam | {[key: string]: any} | Yes| **want** parameter.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| [AbilityConstant.OnSaveResult](js-apis-app-ability-abilityConstant.md#abilityconstantonsaveresult) | Whether the UIAbility state is saved.| + +**Example** + + ```ts +import AbilityConstant from '@ohos.app.ability.AbilityConstant' + +class MyUIAbility extends UIAbility { + onSaveState(reason, wantParam) { + console.log('onSaveState'); + wantParam["myData"] = "my1234567"; + return AbilityConstant.OnSaveResult.RECOVERY_AGREE; + } +} + ``` + + + +## Caller + +Implements sending of sequenceable data to the target ability when the CallerAbility invokes the target ability (CalleeAbility). + +## Caller.call + +call(method: string, data: rpc.Sequenceable): Promise<void>; + +Sends sequenceable data to the target ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| +| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return a response.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + class MyMessageAble{ // Custom sequenceable data structure. + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + var method = 'call_Function'; // Notification message string negotiated by the two abilities. + var caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startUIAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainUIAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble("msg", "world"); // See the definition of Sequenceable. + caller.call(method, msg) + .then(() => { + console.log('Caller call() called'); + }) + .catch((callErr) => { + console.log('Caller.call catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + + +## Caller.callWithResult + +callWithResult(method: string, data: rpc.Sequenceable): Promise<rpc.MessageParcel>; + +Sends sequenceable data to the target ability and obtains the sequenceable data returned by the target ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities. The message is used to instruct the callee to register a function to receive the sequenceable data.| +| data | [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Yes| Sequenceable data. You need to customize the data.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[rpc.MessageParcel](js-apis-rpc.md#sequenceabledeprecated)> | Promise used to return the sequenceable data from the target ability.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + var method = 'call_Function'; + var caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startUIAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainUIAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + let msg = new MyMessageAble(1, "world"); + caller.callWithResult(method, msg) + .then((data) => { + console.log('Caller callWithResult() called'); + let retmsg = new MyMessageAble(0, ""); + data.readSequenceable(retmsg); + }) + .catch((callErr) => { + console.log('Caller.callWithResult catch error, error.code: ' + JSON.stringify(callErr.code) + + ' error.message: ' + JSON.stringify(callErr.message)); + }); + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + + +## Caller.release + +release(): void; + +Releases the caller interface of the target ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | Invalid input parameter. | +| 16200001 | Caller released. The caller has been released. | +| 16200002 | Callee invalid. The callee does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startUIAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainUIAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.release(); + } catch (releaseErr) { + console.log('Caller.release catch error, error.code: ' + JSON.stringify(releaseErr.code) + + ' error.message: ' + JSON.stringify(releaseErr.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + +## Caller.onRelease + + onRelease(callback: OnReleaseCallBack): void; + +Registers a callback that is invoked when the stub on the target ability is disconnected. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| + +**Example** + + ```ts + var caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startUIAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainUIAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.onRelease((str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }); + } catch (error) { + console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + +## Caller.on + + on(type: "release", callback: OnReleaseCallback): void; + +Registers a callback that is invoked when the stub on the target ability is disconnected. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is fixed at **release**.| +| callback | [OnReleaseCallBack](#onreleasecallback) | Yes| Callback used for the **onRelease** API.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + var caller; + export default class MainUIAbility extends UIAbility { + onWindowStageCreate(windowStage) { + this.context.startUIAbilityByCall({ + bundleName: "com.example.myservice", + abilityName: "MainUIAbility", + deviceId: "" + }).then((obj) => { + caller = obj; + try { + caller.on("release", (str) => { + console.log(' Caller OnRelease CallBack is called ' + str); + }); + } catch (error) { + console.log('Caller.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + }).catch((err) => { + console.log('Caller GetCaller error, error.code: ' + JSON.stringify(err.code) + + ' error.message: ' + JSON.stringify(err.message)); + }); + } + } + ``` + + +## Callee + +Implements callbacks for caller notification registration and deregistration. + +## Callee.on + +on(method: string, callback: CalleeCallback): void; + +Registers a caller notification callback, which is invoked when the target ability registers a function. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Notification message string negotiated between the two abilities.| +| callback | [CalleeCallback](#calleecallback) | Yes| JS notification synchronization callback of the [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated) type. The callback must return at least one empty [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) object. Otherwise, the function execution fails.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + + ```ts + class MyMessageAble{ + name:"" + str:"" + num: 1 + constructor(name, str) { + this.name = name; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + console.log('MyMessageAble marshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + console.log('MyMessageAble unmarshalling num[' + this.num + '] str[' + this.str + ']'); + return true; + } + }; + var method = 'call_Function'; + function funcCallBack(pdata) { + console.log('Callee funcCallBack is called ' + pdata); + let msg = new MyMessageAble("test", ""); + pdata.readSequenceable(msg); + return new MyMessageAble("test1", "Callee test"); + } + export default class MainUIAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.on(method, funcCallBack); + } catch (error) { + console.log('Callee.on catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } + ``` + +## Callee.off + +off(method: string): void; + +Deregisters a caller notification callback, which is invoked when the target ability registers a function. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| method | string | Yes| Registered notification message string.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + + +**Example** + + ```ts + var method = 'call_Function'; + export default class MainUIAbility extends UIAbility { + onCreate(want, launchParam) { + console.log('Callee onCreate is called'); + try { + this.callee.off(method); + } catch (error) { + console.log('Callee.off catch error, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + } + } + ``` + +## OnReleaseCallback + +(msg: string): void; + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name| Readable| Writable| Type| Description| +| -------- | -------- | -------- | -------- | -------- | +| (msg: string) | Yes| No| function | Prototype of the listener function registered by the caller.| + +## CalleeCallback + +(indata: rpc.MessageParcel): rpc.Sequenceable; + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +| Name| Readable| Writable| Type| Description| +| -------- | -------- | -------- | -------- | -------- | +| (indata: [rpc.MessageParcel](js-apis-rpc.md#messageparceldeprecated)) | Yes| No| [rpc.Sequenceable](js-apis-rpc.md#sequenceabledeprecated) | Prototype of the listener function registered by the callee.| diff --git a/en/application-dev/reference/apis/js-apis-app-ability-want.md b/en/application-dev/reference/apis/js-apis-app-ability-want.md new file mode 100644 index 0000000000000000000000000000000000000000..c96e29d90f3a10a563df41bc8a545cb42dfdeba4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-want.md @@ -0,0 +1,136 @@ +# @ohos.app.ability.Want (Want) + +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When UIAbility A needs to start UIAbility B and transfer some data to UIAbility B, it can use Want a carrier to transfer the data. + +> **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 + +```ts +import Want from '@ohos.app.ability.Want'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| bundleName | string | No | Bundle name of the ability.| +| moduleName | string | No| Name of the module to which the ability belongs.| +| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| +| [action](js-apis-app-ability-wantConstant.md#wantconstantaction) | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | +| [entities](js-apis-app-ability-wantConstant.md#wantconstantentity) | Array\ | No| Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types.| +| uri | string | No| Data carried. This field is used together with **type** to specify the data type. If **uri** is specified in a Want, the Want will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | string | No| MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com.| +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
- **ohos.aafwk.callerPid**: PID of the caller.
- **ohos.aafwk.param.callerToken**: token of the caller.
- **ohos.aafwk.param.callerUid**: UID in [BundleInfo](js-apis-bundleManager-bundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| [flags](js-apis-ability-wantConstant.md#wantconstantflags) | number | No| How the **Want** object will be handled. By default, a number is passed in.
For example, **wantConstant.Flags.FLAG_ABILITY_CONTINUATION** specifies whether to start the ability in cross-device migration scenarios.| + +**Example** + +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). + + ```ts + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", + "moduleName": "entry" // moduleName is optional. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility): + + * String + ```ts + let want = { + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", + parameters: { + keyForString: "str", + }, + } + ``` + * Number + ```ts + let want = { + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", + parameters: { + keyForInt: 100, + keyForDouble: 99.99, + }, + } + ``` + * Boolean + ```ts + let want = { + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", + parameters: { + keyForBool: true, + }, + } + ``` + * Object + ```ts + let want = { + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", + parameters: { + keyForObject: { + keyForObjectString: "str", + keyForObjectInt: -200, + keyForObjectDouble: 35.5, + keyForObjectBool: false, + }, + }, + } + ``` + * Array + ```ts + let want = { + bundleName: "com.example.myapplication", + abilityName: "FuncAbility", + parameters: { + keyForArrayString: ["str1", "str2", "str3"], + keyForArrayInt: [100, 200, 300, 400], + keyForArrayDouble: [0.1, 0.2], + keyForArrayObject: [{obj1: "aaa"}, {obj2: 100}], + }, + } + ``` + * File descriptor (FD) + ```ts + import fileio from '@ohos.fileio'; + let fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "FuncAbility", + "moduleName": "entry", // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- For more details and examples, see [Want](../../application-models/want-overview.md). + + diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md new file mode 100644 index 0000000000000000000000000000000000000000..43b95743b25c34bdae9457c1e1ed1cf01f8e986e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantAgent.md @@ -0,0 +1,1619 @@ +# @ohos.app.ability.wantAgent (WantAgent) + +The **app.ability.WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. You are advised to use this module, since it will replace the [@ohos.wantAgent](js-apis-wantAgent.md) module in the near future. + +> **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 + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +``` + +## WantAgent.getWantAgent + +getWantAgent(info: WantAgentInfo, callback: AsyncCallback\): void + +Obtains a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ----------------------- | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(err)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getWantAgent + +getWantAgent(info: WantAgentInfo): Promise\ + +Obtains a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ------------- | ---- | ------------- | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the **WantAgent** object.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +try { + WantAgent.getWantAgent(wantAgentInfo).then((data) => { + wantAgent = data; +}).catch((err) => { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +}); +} catch (err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getBundleName + +getBundleName(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getBundleName callback + function getBundleNameCallback(err, data) { + if(err) { + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getBundleName ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getBundleName(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getBundleName + +getBundleName(agent: WantAgent): Promise\ + +Obtains the bundle name of a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the bundle name.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts + // WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getBundleName(wantAgent).then((data)=>{ + console.info('getBundleName ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getBundleName failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getUid + +getUid(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the user ID of a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ----------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the user ID.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +import WantAgent from '@ohos.app.ability.wantAgent'; +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(err)); + } + // getUid callback + function getUidCallback(err, data) { + if(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getUid ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getUid(wantAgent, getUidCallback); + } catch(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getUid + +getUid(agent: WantAgent): Promise\ + +Obtains the user ID of a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the user ID.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getUid(wantAgent).then((data)=>{ + console.info('getUid ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + +## WantAgent.getWant + +getWant(agent: WantAgent, callback: AsyncCallback\): void + +Obtains the want in a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\<[Want](js-apis-app-ability-want.md)\> | Yes | Callback used to return the want.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function getWantCallback(err, data) { + if(err) { + console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getWant ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getWant(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('getWant failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.getWant + +getWant(agent: WantAgent): Promise\ + +Obtains the want in a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the want.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getUid(wantAgent).then((data)=>{ + console.info('getUid ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.cancel + +cancel(agent: WantAgent, callback: AsyncCallback\): void + +Cancels a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | --------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function cancelCallback(err, data) { + if(err) { + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('cancel ok!'); + } + } + try { + WantAgent.cancel(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.cancel + +cancel(agent: WantAgent): Promise\ + +Cancels a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.cancel(wantAgent).then((data)=>{ + console.info('cancel ok!'); + }).catch((err)=>{ + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('cancel failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + +## WantAgent.trigger + +trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: AsyncCallback\): void + +Triggers a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------- | ---- | ------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. | +| callback | AsyncCallback\<[CompleteData](#completedata)\> | No | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// triggerInfo +let triggerInfo = { + code: 0 // Custom result code. + } +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function triggerCallback(err, data) { + if(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getUid ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.trigger(wantAgent, triggerInfo, triggerCallback); + } catch(err) { + console.info('getUid failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.equal + +equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void + +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | The first **WantAgent** object. | +| otherAgent | WantAgent | Yes | The second **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent1; +let wantAgent2; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent1 = data; + wantAgent2 = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function equalCallback(err, data) { + if(err) { + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('equal ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.equal(wantAgent1,wantAgent2,equalCallback); + } catch(err) { + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + + + +## WantAgent.equal + +equal(agent: WantAgent, otherAgent: WantAgent): Promise\ + +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | The first **WantAgent** object.| +| otherAgent | WantAgent | Yes | The second **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent1; +let wantAgent2; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent1 = data; + wantAgent2 = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.equal(wantAgent1,wantAgent2).then((data)=>{ + console.info('equal ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('equal failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + +## WantAgent.getOperationType + +getOperationType(agent: WantAgent, callback: AsyncCallback\): void; + +Obtains the operation type of a **WantAgent** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the operation type.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed' + JSON.stringify(wantAgent)); + } + // getUid callback + function getOperationTypeCallback(err, data) { + if(err) { + console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } else { + console.info('getOperationType ok!' + JSON.stringify(data)); + } + } + try { + WantAgent.getOperationTypeCallback(wantAgent, getBundleNameCallback); + } catch(err) { + console.info('getOperationTypeCallback failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + +## WantAgent.getOperationType + +getOperationType(agent: WantAgent): Promise\; + +Obtains the operation type of a **WantAgent** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the operation type.| + +**Error codes** +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). +| ID | Error Message | +|-----------|--------------------| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong.| +| 16000003 | Input error. The specified id does not exist.| +| 16000004 | Visibility verification failed.| +| 16000006 | Can not cross user operations.| +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry.| +| 16000008 | Crowdtest App Expiration.| +| 16000009 | Can not start ability in wukong mode.| +| 16000010 | Can not operation with continue flag.| +| 16000011 | Context does not exist.| +| 16000050 | Internal Error.| +| 16000051 | Network error. The network is abnormal.| +| 16000052 | Free install not support. The application does not support free install.| +| 16000053 | Not top ability. The application is not top ability.| +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry.| +| 16000055 | Free install timeout.| +| 16000056 | Can not free install other ability.| +| 16000057 | Not support cross device free install.| +| 16000101 | execute shell command failed.| +| 16000151 | Invalid wantagent object.| +| 16000152 | wantAgent object not found.| +| 16000153 | wangAgent object canceled.| + +**Example** + +```ts +// WantAgent object +let wantAgent; +// WantAgentInfo object +let wantAgentInfo = { + wants: [ + { + deviceId: 'deviceId', + bundleName: 'com.example.myapplication', + abilityName: 'EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', + parameters: + { + mykey0: 2222, + mykey1: [1, 2, 3], + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', + mykey4: [false, true, false], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], + mykey6: true, + } + } + ], + operationType: WantAgent.OperationType.START_ABILITIES, + requestCode: 0, + wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] +} + +// getWantAgent callback +function getWantAgentCallback(err, data) { + if (err === undefined) { + wantAgent = data; + } else { + console.info('getWantAgent failed!' + JSON.stringify(wantAgent)); + } + try { + WantAgent.getOperationType(wantAgent).then((data)=>{ + console.info('getOperationType ok!' + JSON.stringify(data)); + }).catch((err)=>{ + console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + }) + } catch(err){ + console.info('getOperationType failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); + } +} +try { + WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); +} catch(err) { + console.info('getWantAgent failed!' + JSON.stringify(err.code) + JSON.stringify(err.message)); +} +``` + +## WantAgentFlags + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ------------------- | -------------- | ------------------------------------------------------------ | +| ONE_TIME_FLAG | 0 | The **WantAgent** object can be used only once. | +| NO_BUILD_FLAG | 1 | The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned. | +| CANCEL_PRESENT_FLAG | 2 | The existing **WantAgent** object should be canceled before a new object is generated.| +| UPDATE_PRESENT_FLAG | 3 | Extra information of the existing **WantAgent** object is replaced with that of the new object.| +| CONSTANT_FLAG | 4 | The **WantAgent** object is immutable. | +| REPLACE_ELEMENT | 5 | The **element** attribute of the current **Want** can be replaced by the **element** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ACTION | 6 | The **action** attribute of the current **Want** can be replaced by the **action** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_URI | 7 | The **uri** attribute of the current **Want** can be replaced by the **uri** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ENTITIES | 8 | The **entities** attribute of the current **Want** can be replaced by the **entities** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_BUNDLE | 9 | The **bundleName** attribute of the current **Want** can be replaced by the **bundleName** attribute of **Want** in **WantAgent.trigger()**.| + + + +## OperationType + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------- | ------------- | ------------------------- | +| UNKNOWN_TYPE | 0 | Unknown operation type. | +| START_ABILITY | 1 | Starts an ability with a UI.| +| START_ABILITIES | 2 | Starts multiple abilities with a UI.| +| START_SERVICE | 3 | Starts an ability without a UI.| +| SEND_COMMON_EVENT | 4 | Sends a common event. | + + + +## CompleteData + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------ | ---- | ---------------------- | +| info | WantAgent | Yes | A triggered **WantAgent** object. | +| want | Want | Yes | An existing triggered **want**. | +| finalCode | number | Yes | Request code that triggers the **WantAgent** object.| +| finalData | string | No | Final data collected by the common event. | +| extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md new file mode 100644 index 0000000000000000000000000000000000000000..4d7a483eab8a55c91d4dbb89287fa611f980ef34 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-ability-wantConstant.md @@ -0,0 +1,82 @@ +# @ohos.app.ability.wantConstant (wantConstant) + +The **wantConstant** module provides the actions, entities, and flags used in **Want** objects. + +> **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 wantConstant from '@ohos.app.ability.wantConstant'; +``` + +## wantConstant.Action + +Enumerates the action constants of the **Want** object. **action** specifies the operation to execute. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------ | ------------------ | ---------------------- | +| ACTION_HOME | ohos.want.action.home | Action of returning to the home page. | +| ACTION_DIAL | ohos.want.action.dial | Action of launching the numeric keypad. | +| ACTION_SEARCH | ohos.want.action.search | Action of launching the search function. | +| ACTION_WIRELESS_SETTINGS | ohos.settings.wireless | Action of launching the UI that provides wireless network settings, for example, Wi-Fi options. | +| ACTION_MANAGE_APPLICATIONS_SETTINGS | ohos.settings.manage.applications | Action of launching the UI for managing installed applications. | +| ACTION_APPLICATION_DETAILS_SETTINGS | ohos.settings.application.details | Action of launching the UI that displays the details of an application. | +| ACTION_SET_ALARM | ohos.want.action.setAlarm | Action of launching the UI for setting the alarm clock. | +| ACTION_SHOW_ALARMS | ohos.want.action.showAlarms | Action of launching the UI that displays all alarms. | +| ACTION_SNOOZE_ALARM | ohos.want.action.snoozeAlarm | Action of launching the UI for snoozing an alarm. | +| ACTION_DISMISS_ALARM | ohos.want.action.dismissAlarm | Action of launching the UI for deleting an alarm. | +| ACTION_DISMISS_TIMER | ohos.want.action.dismissTimer | Action of launching the UI for dismissing a timer. | +| ACTION_SEND_SMS | ohos.want.action.sendSms | Action of launching the UI for sending an SMS message. | +| ACTION_CHOOSE | ohos.want.action.choose | Action of launching the UI for opening a contact or picture. | +| ACTION_IMAGE_CAPTURE | ohos.want.action.imageCapture | Action of launching the UI for photographing. | +| ACTION_VIDEO_CAPTURE | ohos.want.action.videoCapture | Action of launching the UI for shooting a video. | +| ACTION_SELECT | ohos.want.action.select | Action of launching the UI for application selection. | +| ACTION_SEND_DATA | ohos.want.action.sendData | Action of launching the UI for sending a single data record. | +| ACTION_SEND_MULTIPLE_DATA | ohos.want.action.sendMultipleData | Action of launching the UI for sending multiple data records. | +| ACTION_SCAN_MEDIA_FILE | ohos.want.action.scanMediaFile | Action of requesting a media scanner to scan a file and add the file to the media library. | +| ACTION_VIEW_DATA | ohos.want.action.viewData | Action of viewing data. | +| ACTION_EDIT_DATA | ohos.want.action.editData | Action of editing data. | +| INTENT_PARAMS_INTENT | ability.want.params.INTENT | Action of displaying selection options with an action selector. | +| INTENT_PARAMS_TITLE | ability.want.params.TITLE | Title of the character sequence dialog box used with the action selector. | +| ACTION_FILE_SELECT | ohos.action.fileSelect | Action of selecting a file. | +| PARAMS_STREAM | ability.params.stream | URI of the data stream associated with the target when the data is sent. | +| ACTION_APP_ACCOUNT_AUTH | account.appAccount.action.auth | Action of providing the authentication service. | +| ACTION_MARKET_DOWNLOAD | ohos.want.action.marketDownload | Action of downloading an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | +| ACTION_MARKET_CROWDTEST | ohos.want.action.marketCrowdTest | Action of crowdtesting an application from the application market.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_SANDBOX |ohos.dlp.params.sandbox | Action of obtaining the sandbox flag.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_BUNDLE_NAME |ohos.dlp.params.bundleName |Action of obtaining the DLP bundle name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_MODULE_NAME |ohos.dlp.params.moduleName |Action of obtaining the DLP module name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_ABILITY_NAME |ohos.dlp.params.abilityName |Action of obtaining the DLP ability name.
**System API**: This is a system API and cannot be called by third-party applications. | +| DLP_PARAMS_INDEX |ohos.dlp.params.index |Action of obtaining the DLP index.
**System API**: This is a system API and cannot be called by third-party applications. | + +## wantConstant.Entity + +Enumerates the entity constants of the **Want** object. **entity** specifies additional information of the target ability. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------ | ------------------ | ---------------------- | +| ENTITY_DEFAULT | entity.system.default | Default entity. The default entity is used if no entity is specified. | +| ENTITY_HOME | entity.system.home | Home screen entity. | +| ENTITY_VOICE | entity.system.voice | Voice interaction entity. | +| ENTITY_BROWSABLE | entity.system.browsable | Browser type entity. | +| ENTITY_VIDEO | entity.system.video | Video type entity. | + + +## wantConstant.Flags + + Enumerates the flags that specify how the Want will be handled. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Value | Description | +| ------------------------------------ | ---------- | ------------------------------------------------------------ | +| FLAG_AUTH_READ_URI_PERMISSION | 0x00000001 | Indicates the permission to read the URI. | +| FLAG_AUTH_WRITE_URI_PERMISSION | 0x00000002 | Indicates the permission to write data to the URI. | +| FLAG_INSTALL_ON_DEMAND | 0x00000800 | Indicates that the specific ability will be installed if it has not been installed. | diff --git a/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md new file mode 100644 index 0000000000000000000000000000000000000000..51637975d72ea807f428f235aec90310f69b197f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formBindingData.md @@ -0,0 +1,64 @@ +# @ohos.application.formBindingData (formBindingData) + +The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. + +> **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 + +```ts +import formBindingData from '@ohos.app.form.formBindingData'; +``` + +## FormBindingData + +Describes a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| + + +## createFormBindingData + +createFormBindingData(obj?: Object | string): FormBindingData + +Creates a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| + + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------------------------- | +| [FormBindingData](#formbindingdata) | **FormBindingData** object created based on the passed data.| + + +**Example** + +```ts +import fs from '@ohos.file.fs'; +import formBindingData from '@ohos.app.form.formBindingData'; + +try { + let fd = fs.openSync('/path/to/form.png') + let obj = { + "temperature": "21°", + "formImages": { "image": fd } + }; + formBindingData.createFormBindingData(obj); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..ef4e93e215b868013f025722737472735a1016f7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formExtensionAbility.md @@ -0,0 +1,311 @@ +# @ohos.app.form.FormExtensionAbility (FormExtensionAbility) + +The **FormExtensionAbility** module provides lifecycle callbacks invoked when a widget is created, destroyed, or updated. + +> **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. + +## Modules to Import + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | +| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the FormExtensionAbility. This context is inherited from [ExtensionContext](js-apis-inner-application-extensionContext.md).| + +## onAddForm + +onAddForm(want: Want): formBindingData.FormBindingData + +Called to notify the widget provider that a **Form** instance (widget) has been created. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Want information related to the FormExtensionAbility, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onAddForm(want) { + console.log('FormExtensionAbility onAddForm, want:' + want.abilityName); + let dataObj1 = { + temperature: "11c", + "time": "11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +}; +``` + +## onCastToNormalForm + +onCastToNormalForm(formId: string): void + +Called to notify the widget provider that a temporary widget has been converted to a normal one. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onCastToNormalForm(formId) { + console.log('FormExtensionAbility onCastToNormalForm, formId:' + formId); + } +}; +``` + +## onUpdateForm + +onUpdateForm(formId: string): void + +Called to notify the widget provider that a widget has been updated. After obtaining the latest data, your application should call [updateForm](js-apis-app-form-formProvider.md#updateform) of **formProvider** to update the widget data. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget that requests to be updated.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; +import formProvider from '@ohos.app.form.formProvider'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onUpdateForm(formId) { + console.log('FormExtensionAbility onUpdateForm, formId:' + formId); + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + formProvider.updateForm(formId, obj2).then((data) => { + console.log('FormExtensionAbility context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error); + }); + } +}; +``` + +## onChangeFormVisibility + +onChangeFormVisibility(newStatus: { [key: string]: number }): void + +Called to notify the widget provider of the change of visibility. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ---------------------------- | +| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData' +import formProvider from '@ohos.app.form.formProvider'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onChangeFormVisibility(newStatus) { + console.log('FormExtensionAbility onChangeFormVisibility, newStatus:' + newStatus); + let obj2 = formBindingData.createFormBindingData({ + temperature: "22c", + time: "22:00" + }); + + for (let key in newStatus) { + console.log('FormExtensionAbility onChangeFormVisibility, key:' + key + ", value=" + newStatus[key]); + formProvider.updateForm(key, obj2).then((data) => { + console.log('FormExtensionAbility context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error); + }); + } + } +}; +``` + +## onFormEvent + +onFormEvent(formId: string, message: string): void + +Called to instruct the widget provider to receive and process the widget event. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------- | +| formId | string | Yes | ID of the widget that requests the event.| +| message | string | Yes | Event message. | + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onFormEvent(formId, message) { + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + } +}; +``` + +## onRemoveForm + +onRemoveForm(formId: string): void + +Called to notify the widget provider that a **Form** instance (widget) has been destroyed. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget to be destroyed.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onRemoveForm(formId) { + console.log('FormExtensionAbility onRemoveForm, formId:' + formId); + } +}; +``` + +## onConfigurationUpdate + +onConfigurationUpdate(newConfig: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| newConfig | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onConfigurationUpdate(config) { + console.log('onConfigurationUpdate, config:' + JSON.stringify(config)); + } +}; +``` + +## onAcquireFormState + +onAcquireFormState?(want: Want): formInfo.FormState; + +Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formInfo from '@ohos.app.form.formInfo'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onAcquireFormState(want) { + console.log('FormExtensionAbility onAcquireFormState, want:' + want); + return formInfo.FormState.UNKNOWN; + } +}; +``` + +## onShareForm + +onShareForm?(formId: string): { [key: string]: any } + +Called by the widget provider to receive shared widget data. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onShareForm(formId) { + console.log('FormExtensionAbility onShareForm, formId:' + formId); + let wantParams = { + "temperature": "20", + "time": "2022-8-8 09:59", + }; + return wantParams; + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formHost.md b/en/application-dev/reference/apis/js-apis-app-form-formHost.md new file mode 100644 index 0000000000000000000000000000000000000000..e78cf3647a1298ed77b4993d811393ede4e2e5b6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formHost.md @@ -0,0 +1,1603 @@ +# @ohos.app.form.formHost (formHost) + +The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs provided by this module are system APIs. + +## Modules to Import + +```ts +import formHost from '@ohos.app.form.formHost'; +``` + +## deleteForm + +deleteForm(formId: string, callback: AsyncCallback<void>): void + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.deleteForm(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost deleteForm success'); + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## deleteForm + +deleteForm(formId: string): Promise<void> + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Parameters** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.deleteForm(formId).then(() => { + console.log('formHost deleteForm success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## releaseForm + +releaseForm(formId: string, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.releaseForm(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | Yes | Whether to release the cache.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.releaseForm(formId, true, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | No | Whether to release the cache.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.releaseForm(formId, true).then(() => { + console.log('formHost releaseForm success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## requestForm + +requestForm(formId: string, callback: AsyncCallback<void>): void + +Requests a widget update. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.requestForm(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## requestForm + +requestForm(formId: string): Promise<void> + +Requests a widget update. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.requestForm(formId).then(() => { + console.log('formHost requestForm success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} + +``` + +## castToNormalForm + +castToNormalForm(formId: string, callback: AsyncCallback<void>): void + +Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.castToNormalForm(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## castToNormalForm + +castToNormalForm(formId: string): Promise<void> + +Converts a temporary widget to a normal one. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = "12400633174999288"; + formHost.castToNormalForm(formId).then(() => { + console.log('formHost castTempForm success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.notifyVisibleForms(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.notifyVisibleForms(formId).then(() => { + console.log('formHost notifyVisibleForms success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.notifyInvisibleForms(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.notifyInvisibleForms(formId).then(() => { + console.log('formHost notifyInvisibleForms success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.enableFormsUpdate(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.enableFormsUpdate(formId).then(() => { + console.log('formHost enableFormsUpdate success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.disableFormsUpdate(formId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formId = ["12400633174999288"]; + formHost.disableFormsUpdate(formId).then(() => { + console.log('formHost disableFormsUpdate success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## isSystemReady + +isSystemReady(callback: AsyncCallback<void>): void + +Checks whether the system is ready. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + formHost.isSystemReady((error, data) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## isSystemReady + +isSystemReady(): Promise<void> + +Checks whether the system is ready. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + formHost.isSystemReady().then(() => { + console.log('formHost isSystemReady success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getAllFormsInfo + +getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + formHost.getAllFormsInfo((error, data) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getAllFormsInfo + +getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + formHost.getAllFormsInfo().then((data) => { + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | Yes| Module name.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | No| Module name.| + +**Return value** + +| Type | Description | +| :----------------------------------------------------------- | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void + +Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds, (error, data) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>): Promise<number> + +Deletes invalid widgets from the list. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the number of widgets deleted.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +try { + let formIds = new Array("12400633174999288", "12400633174999289"); + formHost.deleteInvalidForms(formIds).then((data) => { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## acquireFormState + +acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo>): void + +Obtains the widget state. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| +| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +try { + formHost.acquireFormState(want, (error, data) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } else { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## acquireFormState + +acquireFormState(want: Want): Promise<formInfo.FormStateInfo> + +Obtains the widget state. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[formInfo.FormStateInfo](js-apis-app-form-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +try { + formHost.acquireFormState(want).then((data) => { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## on("formUninstall") + +on(type: "formUninstall", callback: Callback<string>): void + +Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | Yes| Callback used to return the widget ID.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.on("formUninstall", callback); +``` + +## off("formUninstall") + +off(type: "formUninstall", callback?: Callback<string>): void + +Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on("formUninstall")**.| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.off("formUninstall", callback); +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsVisible(formIds, true, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void> + +Instructs the widgets to make themselves visible. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsVisible(formIds, true).then(() => { + console.log('formHost notifyFormsVisible success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to enable or disable updates. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsEnableUpdate(formIds, true, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void> + +Instructs the widgets to enable or disable updates. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsEnableUpdate(formIds, true).then(() => { + console.log('formHost notifyFormsEnableUpdate success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` +## shareForm + +shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void + +Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +try { + formHost.shareForm(formId, deviceId, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## shareForm + +shareForm(formId: string, deviceId: string): Promise<void> + +Shares a specified widget with a remote device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +try { + formHost.shareForm(formId, deviceId).then(() => { + console.log('formHost shareForm success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyFormsPrivacyProtected + +notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean, callback: AsyncCallback\): void + +Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array\ | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If privacy protection is set successfully, **error** is undefined; otherwise, **error** is an error object.| + +**Error codes** + +| Error Code ID | Error Message | +| ------------------------------------------------------------ | ------------------ | +| 401 | Incorrect input parameter.| +| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| | + +**Example** + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true, (error) => { + if (error) { + console.log(`error, code: ${error.code}, message: ${error.message}`); + } + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` + +## notifyFormsPrivacyProtected + +function notifyFormsPrivacyProtected(formIds: Array\, isProtected: boolean): Promise\; + +Notifies that the privacy protection status of the specified widgets changes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------- | ---- | -------------------------------- | +| formIds | Array\ | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| Error Code ID | Error Message | +| ------------------------------------------------------------ | ------------------ | +| 401 | Incorrect input parameter.| +| For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| | + +```ts +import formHost from '@ohos.app.form.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { + console.log('formHost notifyFormsPrivacyProtected success'); + }).catch((error) => { + console.log(`error, code: ${error.code}, message: ${error.message}`); + }); +} catch(error) { + console.log(`catch error, code: ${error.code}, message: ${error.message}`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-app-form-formInfo.md b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..84b40a57a56038b89ddf7ee06caef5f492e252f0 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formInfo.md @@ -0,0 +1,141 @@ +# @ohos.app.form.formInfo (formInfo) + +The **formInfo** module provides types and enums related to the widget information and state. + +> **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 + +```ts +import formInfo from '@ohos.app.form.formInfo'; +``` + +## FormInfo + +Describes widget information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| moduleName | string | Yes | No | Name of the module to which the widget belongs. | +| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | +| name | string | Yes | No | Widget name. | +| description | string | Yes | No | Description of the widget. | +| type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, only JS widgets are supported.| +| jsComponentName | string | Yes | No | Name of the component used in the JS widget. | +| colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | +| isDefault | boolean | Yes | No | Whether the widget is the default one. | +| updateEnabled | boolean | Yes | No | Whether the widget is updatable. | +| formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. | +| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | +| scheduledUpdateTime | string | Yes | No | Time when the widget was updated. | +| formConfigAbility | string | Yes | No | Configuration ability of the widget, that is, the ability corresponding to the option in the selection box displayed when the widget is long pressed. | +| updateDuration | number | Yes | No | Update period of the widget.| +| defaultDimension | number | Yes | No | Default dimension of the widget. | +| supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. For details, see [FormDimension](#formdimension). | +| customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | + +## FormType + +Enumerates the widget types. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| JS | 1 | JS widget. | +| eTS | 2 | eTS widget.| + +## ColorMode + +Enumerates the color modes supported by the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| MODE_AUTO | -1 | Auto mode. | +| MODE_DARK | 0 | Dark mode. | +| MODE_LIGHT | 1 | Light mode. | + +## FormStateInfo + +Describes the widget state information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- | -------- | -------------------- | ------------------------------------------------------------ | +| formState | [FormState](#formstate) | Yes | No | Widget state. | +| want | Want | Yes | No | Want text. | + +## FormState + +Enumerates the widget states. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| UNKNOWN | -1 | Unknown state. | +| DEFAULT | 0 | Default state. | +| READY | 1 | Ready state. | + +## FormParam + +Enumerates the widget parameters. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| IDENTITY_KEY | "ohos.extra.param.key.form_identity" | Widget ID. | +| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | +| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | +| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | +| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | +| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | +| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | +| ABILITY_NAME_KEY | "ohos.extra.param.key.ability_name" | Ability name. | +| DEVICE_ID_KEY | "ohos.extra.param.key.device_id" | Device ID. | +| BUNDLE_NAME_KEY | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| + +## FormDimension + +Enumerates the widget dimensions. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| Dimension_1_2 | 1 | 1 x 2. | +| Dimension_2_2 | 2 | 2 x 2. | +| Dimension_2_4 | 3 | 2 x 4. | +| Dimension_4_4 | 4 | 4 x 4. | +| Dimension_2_1 | 5 | 2 x 1. | + + +## FormInfoFilter + +Defines the widget information filter. Only the widget information that meets the filter is returned. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Description | +| ----------- | ---- | ------------ | +| moduleName | string | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.
If this parameter is not set, **moduleName** is not used for filtering. | + +## VisibilityType + +Enumerates the visibility types of the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| FORM_VISIBLE | 1 | The widget is visible.| +| FORM_INVISIBLE | 2 | The widget is invisible.| diff --git a/en/application-dev/reference/apis/js-apis-app-form-formProvider.md b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md new file mode 100644 index 0000000000000000000000000000000000000000..d61484f86b36bafd74ded1860272ac1a4b86089a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-app-form-formProvider.md @@ -0,0 +1,583 @@ +# @ohos.app.form.formProvider (formProvider) + +The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. + +> **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 + +```ts +import formProvider from '@ohos.app.form.formProvider'; +``` + +## setFormNextRefreshTime + +setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void + +Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| formId | string | Yes | Widget ID. | +| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; +try { + formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log(`formProvider setFormNextRefreshTime success`); + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## setFormNextRefreshTime + +setFormNextRefreshTime(formId: string, minute: number): Promise<void> + +Sets the next refresh time for a widget. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| formId | string | Yes | Widget ID. | +| minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | + +**Return value** + +| Type | Description | +| ------------- | ---------------------------------- | +| Promise\ | Promise that returns no value. | + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; +try { + formProvider.setFormNextRefreshTime(formId, 5).then(() => { + console.log(`formProvider setFormNextRefreshTime success`); + }).catch((error) => { + console.log(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## updateForm + +updateForm(formId: string, formBindingData: formBindingData.FormBindingData,callback: AsyncCallback<void>): void + +Updates a widget. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| formId | string | Yes | ID of the widget to update.| +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData'; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; +try { + let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + formProvider.updateForm(formId, obj, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log(`formProvider updateForm success`); + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## updateForm + +updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void> + +Updates a widget. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| formId | string | Yes | ID of the widget to update.| +| formBindingData.FormBindingData | [FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | + +**Return value** + +| Type | Description | +| -------------- | ----------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData'; +import formProvider from '@ohos.app.form.formProvider'; + +let formId = "12400633174999288"; +let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); +try { + formProvider.updateForm(formId, obj).then(() => { + console.log(`formProvider updateForm success`); + }).catch((error) => { + console.log(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## getFormsInfo + +getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the application's widget information on the device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + + +**Example** + +```ts +import formProvider from '@ohos.app.form.formProvider'; + +try { + formProvider.getFormsInfo((error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` +## getFormsInfo + +getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the application's widget information that meets a filter criterion on the device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | Yes| Filter criterion.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Yes| Callback used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" +}; +try { + formProvider.getFormsInfo(filter, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider getFormsInfo, data: ' + JSON.stringify(data)); + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## getFormsInfo + +getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>> + +Obtains the application's widget information on the device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| filter | [formInfo.FormInfoFilter](js-apis-app-form-formInfo.md#forminfofilter) | No| Filter criterion.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-app-form-formInfo.md)>> | Promise used to return the information obtained.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formInfo from '@ohos.app.form.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + +const filter: formInfo.FormInfoFilter = { + // get info of forms belong to module entry. + moduleName: "entry" +}; +try { + formProvider.getFormsInfo(filter).then((data) => { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + }).catch((error) => { + console.log(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## requestPublishForm + +requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void + +Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------------------------- | ---- | ---------------- | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| +| callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData'; +import formProvider from '@ohos.app.form.formProvider'; + +let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } +}; +try { + let obj = formBindingData.createFormBindingData({ temperature: "22c", time: "22:00" }); + formProvider.requestPublishForm(want, obj, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## requestPublishForm + +requestPublishForm(want: Want, callback: AsyncCallback<string>): void + +Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| callback | AsyncCallback<string> | Yes | Callback used to return the widget ID.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formProvider from '@ohos.app.form.formProvider'; + +let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } +}; +try { + formProvider.requestPublishForm(want, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## requestPublishForm + +requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string> + +Requests to publish a widget to the widget host. This API uses a promise to return the result. This API is usually called by the home screen. + +**System capability**: SystemCapability.Ability.Form + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData | [formBindingData.FormBindingData](js-apis-app-form-formBindingData.md#formbindingdata) | No | Data used for creating the widget. | + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<string> | Promise used to return the widget ID.| + +**Error codes** + +| Error Code ID| Error Message| +| -------- | -------- | +| 401 | Incorrect input parameter.| +|For details about the error codes, see [Form Error Codes](../errorcodes/errorcode-form.md).| + +**Example** + +```ts +import formProvider from '@ohos.app.form.formProvider'; + +let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } +}; +try { + formProvider.requestPublishForm(want).then((data) => { + console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + }).catch((error) => { + console.log(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## isRequestPublishFormSupported + +isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void + +Checks whether a widget can be published to the widget host. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the widget can be published to the widget host.| + +**Example** + +```ts +import formProvider from '@ohos.app.form.formProvider'; + +try { + formProvider.isRequestPublishFormSupported((error, isSupported) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + if (isSupported) { + var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } + }; + try { + formProvider.requestPublishForm(want, (error, data) => { + if (error) { + console.log(`callback error, code: ${error.code}, message: ${error.message})`); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } + }); + } catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); + } + } + } + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` + +## isRequestPublishFormSupported + +isRequestPublishFormSupported(): Promise<boolean> + +Checks whether a widget can be published to the widget host. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<boolean> | Promise used to return whether the widget can be published to the widget host.| + +**Example** + +```ts +import formProvider from '@ohos.app.form.formProvider'; + +try { + formProvider.isRequestPublishFormSupported().then((isSupported) => { + if (isSupported) { + var want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } + }; + try { + formProvider.requestPublishForm(want).then((data) => { + console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + }).catch((error) => { + console.log(`promise error, code: ${error.code}, message: ${error.message})`); + }); + } catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); + } + } + }).catch((error) => { + console.log(`promise error, code: ${error.code}, message: ${error.message})`); + }); +} catch (error) { + console.log(`catch error, code: ${error.code}, message: ${error.message})`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-appAccount.md b/en/application-dev/reference/apis/js-apis-appAccount.md index c98d603c0092e8f2fd9e1f9a2ce0d33ecd9cc1a7..0d2aef3e25aa21eb724c8f74f977d901ea12b290 100644 --- a/en/application-dev/reference/apis/js-apis-appAccount.md +++ b/en/application-dev/reference/apis/js-apis-appAccount.md @@ -1,8 +1,9 @@ -# App Account Management +# @ohos.account.appAccount -The **appAccount** module provides APIs for app account management. You can use the APIs to add, delete, query, modify, and authorize app accounts, write data to disks, and synchronize data. +The **appAccount** module provides APIs for adding, deleting, modifying, and querying app account information, and supports inter-app authentication and distributed data synchronization. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,7 +18,7 @@ import account_appAccount from '@ohos.account.appAccount'; createAppAccountManager(): AppAccountManager -Creates an **AppAccountManager** instance. +Creates an **AppAccountManager** object. **System capability**: SystemCapability.Account.AppAccount @@ -25,46 +26,59 @@ Creates an **AppAccountManager** instance. | Type | Description | | ----------------- | ------------ | -| AppAccountManager | **AppAccountManager** instance created.| +| AppAccountManager | **AppAccountManager** object created.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); ``` ## AppAccountManager -Provides methods to manage app accounts. +Implements app account management. -### addAccount +### createAccount9+ -addAccount(name: string, callback: AsyncCallback<void>): void +createAccount(name: string, callback: AsyncCallback<void>): void; -Adds an app account to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. +Creates an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | -------------------- | -| name | string | Yes | Name of the app account to add. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is added.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ----- | -------------------- | +| name | string | Yes | Name of the app account to create. | +| 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 name. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccount("WangWu", (err) => { - console.log("addAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.createAccount("WangWu", (err) => { + console.log("createAccount err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("createAccount err: " + JSON.stringify(err)); + } ``` -### addAccount +### createAccount9+ -addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void +createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallback<void>): void -Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses an asynchronous callback to return the result. +Creates an app account with custom data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -72,26 +86,46 @@ Adds an app account name and additional information (information that can be con | Name | Type | Mandatory | Description | | --------- | ------------------------- | ---- | ---------------------------------------- | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | Yes | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account name and additional information are added. | +| name | string | Yes | Name of the app account to create. | +| options | [CreateAccountOptions](#createaccountoptions9) | Yes | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens).| +| 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 name or options. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccount("LiSi", "token101", (err) => { - console.log("addAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + customData: { + "age": "10" + } + } + try { + appAccountManager.createAccount("LiSi", options, (err) => { + if (err) { + console.log("createAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("createAccount successfully"); + } + }); + } catch(err) { + console.log("createAccount exception: " + JSON.stringify(err)); + } ``` +### createAccount9+ +createAccount(name: string, options?: CreateAccountOptions): Promise<void> -### addAccount - -addAccount(name: string, extraInfo?: string): Promise<void> - -Adds an app account name and additional information (information that can be converted into the string type, such as token) to the **AppAccountManager** service. This API uses a promise to return the result. +Creates an app account with custom data. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -99,31 +133,104 @@ Adds an app account name and additional information (information that can be con | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | -| name | string | Yes | Name of the app account to add. | -| extraInfo | string | No | Additional information to add. The additional information cannot contain sensitive information, such as the app account password.| +| name | string | Yes | Name of the app account to create. | +| options | [CreateAccountOptions](#createaccountoptions9) | No | Options for creating the app account. You can customize data based on service requirements, but do not add sensitive data (such as passwords and tokens). This parameter can be left empty.| **Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300004 | Account already exists. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12400003 | The number of custom data reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccount("LiSi", "token101").then(()=> { - console.log('addAccount Success'); - }).catch((err) => { - console.log("addAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + customData: { + "age": "10" + } + } + try { + appAccountManager.createAccount("LiSi", options).then(() => { + console.log("createAccount successfully"); + }).catch((err) => { + console.log("createAccount failed, error: " + JSON.stringify(err)); + }); + } catch(err) { + console.log("createAccount exception: " + JSON.stringify(err)); + } ``` -### addAccountImplicitly8+ +### createAccountImplicitly9+ -addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void +createAccountImplicitly(owner: string, callback: AuthCallback): void + +Creates an app account implicitly based on the specified account owner. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ----------------------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; -Implicitly adds an app account based on the specified account owner, authentication type, and options. This API uses an asynchronous callback to return the result. + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.createAccountImplicitly("com.example.accountjsdemo", { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + } catch (err) { + console.log("createAccountImplicitly exception: " + JSON.stringify(err)); + } + ``` + +### createAccountImplicitly9+ + +createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, callback: AuthCallback): void + +Creates an app account implicitly based on the specified account owner and options. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -131,10 +238,20 @@ Implicitly adds an app account based on the specified account owner, authenticat | Name | Type | Mandatory | Description | | -------- | --------------------- | ---- | ----------------------- | -| owner | string | Yes | Owner of the app account to add. The value is the bundle name of the app. | -| authType | string | Yes | Authentication type of the app account to add. The authentication type is customized. | -| options | {[key: string]: any} | Yes | Authentication options, which can be set as required.| -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback used to return the result. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or options. | +| 12300007 | The number of accounts reaches the upper limit. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **Example** @@ -142,29 +259,37 @@ Implicitly adds an app account based on the specified account owner, authenticat import featureAbility from '@ohos.ability.featureAbility'; function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + authType: "getSocialData", + requiredLabels: [ "student" ] + }; + try { + appAccountManager.createAccountImplicitly("com.example.accountjsdemo", options, { onResult: onResultCallback, onRequestRedirected: onRequestRedirectedCallback - }); + }); + } catch (err) { + console.log("createAccountImplicitly exception: " + JSON.stringify(err)); + } ``` -### deleteAccount +### removeAccount9+ -deleteAccount(name: string, callback: AsyncCallback<void>): void +removeAccount(name: string, callback: AsyncCallback<void>): void -Deletes an app account from the **AppAccountManager** service. This API uses an asynchronous callback to return the result. +Removes an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -172,23 +297,39 @@ Deletes an app account from the **AppAccountManager** service. This API uses an | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------- | -| name | string | Yes | Name of the app account to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the app account is deleted.| +| name | string | Yes | Name of the app account to remove. | +| 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 name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccount("ZhaoLiu", (err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.removeAccount("ZhaoLiu", (err) => { + if (err) { + console.log("removeAccount failed, error: " + JSON.stringify(err)); + } else { + console.log("removeAccount successfully"); + } }); + } catch(err) { + console.log("removeAccount exception: " + JSON.stringify(err)); + } ``` -### deleteAccount +### removeAccount9+ -deleteAccount(name: string): Promise<void> +removeAccount(name: string): Promise<void> -Deletes an app account from the **AppAccountManager** service. This API uses a promise to return the result. +Removes an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -196,87 +337,131 @@ Deletes an app account from the **AppAccountManager** service. This API uses a p | Name | Type | Mandatory | Description | | ---- | ------ | ---- | ----------- | -| name | string | Yes | Name of the app account to delete.| +| name | string | Yes | Name of the app account to remove.| **Return value** | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccount("ZhaoLiu").then(() => { - console.log('deleteAccount Success'); - }).catch((err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.removeAccount("Lisi").then(() => { + console.log("removeAccount successfully"); + }).catch((err) => { + console.log("removeAccount failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("removeAccount exception: " + JSON.stringify(err)); + } ``` -### disableAppAccess +### setAppAccess9+ -disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void +setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback: AsyncCallback<void>): void -Disables an app account from accessing an app with the given bundle name. This API uses an asynchronous callback to return the result. +Sets the access to the data of an account for an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| ------------ | ------------------------- | ---- | --------------------------------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | +| isAccessible | boolean | Yes | Whether the access is allowed. The value **true** means to allow the access; the value **false** means the opposite.| +| 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 name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("disableAppAccess err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true, (err) => { + if (err) { + console.log("setAppAccess failed: " + JSON.stringify(err)); + } else { + console.log("setAppAccess successfully"); + } + }); + } catch (err) { + console.log("setAppAccess exception: " + JSON.stringify(err)); + } ``` -### disableAppAccess +### setAppAccess9+ -disableAppAccess(name: string, bundleName: string): Promise<void> +setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise<void> -Disables an app account from accessing an app with the given bundle name. This API uses a promise to return the result. +Sets the access to the data of an account for an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------ | ---- | ---------------- | -| name | string | Yes | Name of the target app account.| -| bundleName | string | Yes | Bundle name of the app. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app.| +| isAccessible | boolean | Yes | Whether the access is allowed. The value **true** means to allow the access; the value **false** means the opposite.| **Return value** | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { - console.log('disableAppAccess Success'); - }).catch((err) => { - console.log("disableAppAccess err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAppAccess("ZhangSan", "com.example.accountjsdemo", true).then(() => { + console.log("setAppAccess successfully"); + }).catch((err) => { + console.log("setAppAccess failed: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setAppAccess exception: " + JSON.stringify(err)); + } ``` -### enableAppAccess +### checkAppAccess9+ -enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void +checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<boolean>): void -Enables an app account to access an app with the given bundle name. This API uses an asynchronous callback to return the result. +Checks whether an app can access the data of an account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -286,22 +471,39 @@ Enables an app account to access an app with the given bundle name. This API use | ---------- | ------------------------- | ---- | --------------------------------- | | name | string | Yes | Name of the target app account. | | bundleName | string | Yes | Bundle name of the app. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the app can access the account data; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("enableAppAccess: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo", (err, isAccessible) => { + if (err) { + console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAppAccess successfully"); + } + }); + } catch (err) { + console.log("checkAppAccess exception: " + JSON.stringify(err)); + } ``` -### enableAppAccess +### checkAppAccess9+ -enableAppAccess(name: string, bundleName: string): Promise<void> +checkAppAccess(name: string, bundleName: string): Promise<boolean> -Enables an app account to access an app with the given bundle name. This API uses a promise to return the result. +Checks whether an app can access the data of an account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -314,26 +516,124 @@ Enables an app account to access an app with the given bundle name. This API use **Return value** +| Type | Description | +| ------------------- | --------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means the app can access the account data; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or bundleName. | +| 12300003 | Account not found. | +| 12400001 | Application not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAppAccess("ZhangSan", "com.example.accountjsdemo").then((isAccessible) => { + console.log("checkAppAccess successfully, isAccessible: " + isAccessible); + }).catch((err) => { + console.log("checkAppAccess failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkAppAccess exception: " + JSON.stringify(err)); + } + ``` + +### setDataSyncEnabled9+ + +setDataSyncEnabled(name: string, isEnabled: boolean, callback: AsyncCallback<void>): void + +Sets data synchronization for an app account. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| isEnabled | boolean | Yes | Whether to enable data synchronization. | +| 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 name. | +| 12300003 | Account not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + } + ``` + +### setDataSyncEnabled9+ + +setDataSyncEnabled(name: string, isEnabled: boolean): Promise<void> + +Sets data synchronization for an app account. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| isEnabled | boolean | Yes | Whether to enable data synchronization.| + +**Return value** + | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { - console.log('enableAppAccess Success'); - }).catch((err) => { - console.log("enableAppAccess err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => { + console.log('setDataSyncEnabled Success'); + }).catch((err) => { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + } ``` -### checkAppAccountSyncEnable +### checkDataSyncEnabled9+ -checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void +checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void -Checks whether an app account allows app data synchronization. This API uses an asynchronous callback to return the result. +Checks whether data synchronization is enabled for an app account. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -344,23 +644,38 @@ Checks whether an app account allows app data synchronization. This API uses an | Name | Type | Mandatory | Description | | -------- | ---------------------------- | ---- | --------------------- | | name | string | Yes | Name of the target app account. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { - console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); - console.log('checkAppAccountSyncEnable result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkDataSyncEnabled("ZhangSan", (err, isEnabled) => { + if (err) { + console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + } else { + console.log('checkDataSyncEnabled successfully, isEnabled: ' + isEnabled); + } + }); + } catch (err) { + console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + } ``` -### checkAppAccountSyncEnable +### checkDataSyncEnabled9+ -checkAppAccountSyncEnable(name: string): Promise<boolean> +checkDataSyncEnabled(name: string): Promise<boolean> -Checks whether an app account allows app data synchronization. This API uses a promise to return the result. +Checks whether data synchronization is enabled for an app account. This API uses a promise to return the result. **Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC @@ -376,22 +691,34 @@ Checks whether an app account allows app data synchronization. This API uses a p | Type | Description | | :--------------------- | :-------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { - console.log('checkAppAccountSyncEnable, result: ' + data); - }).catch((err) => { - console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkDataSyncEnabled("ZhangSan").then((isEnabled) => { + console.log("checkDataSyncEnabled successfully, isEnabled: " + isEnabled); + }).catch((err) => { + console.log("checkDataSyncEnabled failed, err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkDataSyncEnabled err: " + JSON.stringify(err)); + } ``` -### setAccountCredential +### setCredential9+ -setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void +setCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void Sets a credential for an app account. This API uses an asynchronous callback to return the result. @@ -403,21 +730,37 @@ Sets a credential for an app account. This API uses an asynchronous callback to | -------------- | ------------------------- | ---- | ------------- | | name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to set. | -| credential | string | Yes | Credential to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| credential | string | Yes | Credential value. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the credential is set successfully, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType or credential. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { - console.log("setAccountCredential err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx", (err) => { + if (err) { + console.log("setCredential failed, error: " + JSON.stringify(err)); + } else { + console.log("setCredential successfully"); + } + }); + } catch (err) { + console.log("setCredential exception: " + JSON.stringify(err)); + } ``` -### setAccountCredential +### setCredential9+ -setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> +setCredential(name: string, credentialType: string, credential: string): Promise<void> Sets a credential for an app account. This API uses a promise to return the result. @@ -429,587 +772,648 @@ Sets a credential for an app account. This API uses a promise to return the resu | -------------- | ------ | ---- | ---------- | | name | string | Yes | Name of the target app account. | | credentialType | string | Yes | Type of the credential to set.| -| credential | string | Yes | Credential to set. | +| credential | string | Yes | Credential value. | **Return value** -| Type | Description | +| Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType or credential. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { - console.log('setAccountCredential Success'); - }).catch((err) => { - console.log("setAccountCredential err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCredential("ZhangSan", "PIN_SIX", "xxxxxx").then(() => { + console.log("setCredential successfully"); + }).catch((err) => { + console.log("setCredential failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setCredential exception: " + JSON.stringify(err)); + } ``` -### setAccountExtraInfo +### getCredential9+ -setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void +getCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void -Sets additional information for an app account. This API uses an asynchronous callback to return the result. +Obtains the credential of an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------------------------- | ---- | --------------- | -| name | string | Yes | Name of the target app account. | -| extraInfo | string | Yes | Additional information to set. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to obtain.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCredential("ZhangSan", "PIN_SIX", (err, result) => { + if (err) { + console.log("getCredential failed, error: " + JSON.stringify(err)); + } else { + console.log('getCredential successfully, result: ' + result); + } + }); + } catch (err) { + console.log("getCredential err: " + JSON.stringify(err)); + } ``` -### setAccountExtraInfo +### getCredential9+ -setAccountExtraInfo(name: string, extraInfo: string): Promise<void> +getCredential(name: string, credentialType: string): Promise<string> -Sets additional information for an app account. This API uses a promise to return the result. +Obtains the credential of an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | --------- | -| name | string | Yes | Name of the target app account. | -| extraInfo | string | Yes | Additional information to set.| +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | Name of the target app account.| +| credentialType | string | Yes | Type of the credential to obtain.| **Return value** -| Type | Description | -| :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the credential obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { - console.log('setAccountExtraInfo Success'); - }).catch((err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCredential("ZhangSan", "PIN_SIX").then((credential) => { + console.log("getCredential successfully, credential: " + credential); + }).catch((err) => { + console.log("getCredential failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getCredential exception: " + JSON.stringify(err)); + } ``` -### setAppAccountSyncEnable - -setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void +### setCustomData9+ -Sets whether to enable app data synchronization for an app account. This API uses an asynchronous callback to return the result. +setCustomData(name: string, key: string, value: string, callback: AsyncCallback<void>): void -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Sets custom data for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ------------------------- | -| name | string | Yes | Name of the target app account. | -| isEnable | boolean | Yes | Whether to enable app data synchronization. | -| callback | AsyncCallback<void> | Yes | Callback invoked when app data synchronization is enabled or disabled for the app account.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the target app account.| +| key | string | Yes | Key of the custom data to set.| +| value | string | Yes | Value of the custom data to set.| +| 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 name or key or value. | +| 12300003 | Account not found. | +| 12400003 | The number of custom data reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCustomData("ZhangSan", "age", "12", (err) => { + if (err) { + console.log("setCustomData failed, error: " + JSON.stringify(err)); + } else { + console.log("setCustomData successfully"); + } + }); + } catch (err) { + console.log("setCustomData exception: " + JSON.stringify(err)); + } ``` -### setAppAccountSyncEnable - -setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> +### setCustomData9+ -Sets whether to enable app data synchronization for an app account. This API uses a promise to return the result. +setCustomData(name: string, key: string, value: string): Promise<void> -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Sets custom data for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------- | ---- | ----------- | -| name | string | Yes | Name of the target app account. | -| isEnable | boolean | Yes | Whether to enable app data synchronization.| +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to set.| +| value | string | Yes | Value of the custom data to set.| **Return value** | Type | Description | | :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key or value. | +| 12300003 | Account not found. | +| 12400003 | The number of custom data reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { - console.log('setAppAccountSyncEnable Success'); - }).catch((err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setCustomData("ZhangSan", "age", "12").then(() => { + console.log("setCustomData successfully"); + }).catch((err) => { + console.log("setCustomData failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setCustomData exception: " + JSON.stringify(err)); + } ``` -### setAssociatedData +### getCustomData9+ -setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void +getCustomData(name: string, key: string, callback: AsyncCallback<string>): void -Sets data to be associated with an app account. This API uses an asynchronous callback to return the result. +Obtains the custom data of an app account based on the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | ----------------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | -| callback | AsyncCallback<void> | Yes | Callback invoked when the data associated with the specified app account is set.| +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ----- | ------------------------ | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the custom data value obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { - console.log("setAssociatedData err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCustomData("ZhangSan", "age", (err, data) => { + if (err) { + console.log('getCustomData failed, error: ' + err); + } else { + console.log("getCustomData successfully, data: " + data); + } + }); + } catch (err) { + console.log("getCustomData exception: " + JSON.stringify(err)); + } ``` -### setAssociatedData +### getCustomData9+ -setAssociatedData(name: string, key: string, value: string): Promise<void> +getCustomData(name: string, key: string): Promise<string> -Sets data to be associated with an app account. This API uses a promise to return the result. +Obtains the custom data of an app account based on the specified key. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----------------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to set. The private key can be customized.| -| value | string | Yes | Value of the data to be set. | +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to obtain.| **Return value** -| Type | Description | -| :------------------ | :-------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | --------------------- | +| Promise<string> | Promise used to return the custom data value obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { - console.log('setAssociatedData Success'); - }).catch((err) => { - console.log("setAssociatedData err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getCustomData("ZhangSan", "age").then((data) => { + console.log("getCustomData successfully, data: " + data); + }).catch((err) => { + console.log("getCustomData failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getCustomData exception: " + JSON.stringify(err)); + } ``` -### getAccountCredential +### getCustomDataSync9+ -getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void +getCustomDataSync(name: string, key: string): string; -Obtains the credentials (such as the digital password, face image, and PIN) of an app account. This API uses an asynchronous callback to return the result. +Obtains the custom data of an app account based on the specified key. The API returns the result synchronously. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | --------------------------- | ---- | -------------- | -| name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to obtain.| -| callback | AsyncCallback<string> | Yes | Callback invoked to return the credential obtained.| +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the custom data to obtain.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------- | +| string | Value of the custom data obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or key. | +| 12300003 | Account not found. | +| 12400002 | Custom data not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { - console.log("getAccountCredential err: " + JSON.stringify(err)); - console.log('getAccountCredential result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + let value = appAccountManager.getCustomDataSync("ZhangSan", "age"); + console.info("getCustomDataSync successfully, vaue:" + value); + } catch (err) { + console.error("getCustomDataSync failed, error: " + JSON.stringify(err)); + } ``` -### getAccountCredential +### getAllAccounts9+ -getAccountCredential(name: string, credentialType: string): Promise<string> +getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void -Obtains the credential of an app account. This API uses a promise to return the result. +Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | ---- | ---------- | -| name | string | Yes | Name of the target app account. | -| credentialType | string | Yes | Type of the credential to obtain.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of accessible app accounts. Otherwise, **err** is an error object.| -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| Promise<string> | Promise used to return the result.| +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { - console.log('getAccountCredential, result: ' + data); - }).catch((err) => { - console.log("getAccountCredential err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAccounts((err, data) => { + if (err) { + console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + } else { + console.debug("getAllAccounts successfully"); + } + }); + } catch (err) { + console.debug("getAllAccounts exception: " + JSON.stringify(err)); + } ``` -### getAccountExtraInfo +### getAllAccounts9+ -getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void +getAllAccounts(): Promise<Array<AppAccountInfo>> + +Obtains information about all accessible app accounts. This API uses a promise to return the result. -Obtains additional information (information that can be converted into the string type) about an app account. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | --------------- | -| name | string | Yes | Name of the target app account. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the additional information of the specified app account.| +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return information about all accessible accounts.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { - console.log("getAccountExtraInfo err: " + JSON.stringify(err)); - console.log('getAccountExtraInfo result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAccounts().then((data) => { + console.debug("getAllAccounts successfully"); + }).catch((err) => { + console.debug("getAllAccounts failed, error:" + JSON.stringify(err)); + }); + } catch (err) { + console.debug("getAllAccounts exception: " + JSON.stringify(err)); + } ``` -### getAccountExtraInfo +### getAccountsByOwner9+ -getAccountExtraInfo(name: string): Promise<string> +getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void + +Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses an asynchronous callback to return the result. -Obtains additional information of an app account. This API uses a promise to return the result. +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | ------- | -| name | string | Yes | Name of the target app account.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is null and **data** is the app account information obtained. Otherwise, **err** is an error object.| -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| Promise<string> | Promise used to return the result.| +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { - console.log('getAccountExtraInfo, result: ' + data); - }).catch((err) => { - console.log("getAccountExtraInfo err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAccountsByOwner("com.example.accountjsdemo2", (err, data) => { + if (err) { + console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + } else { + console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + } + }); + } catch (err) { + console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); + } ``` -### getAssociatedData +### getAccountsByOwner9+ -getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void +getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> -Obtains data associated with an app account. This API uses an asynchronous callback to return the result. +Obtains the app accounts that can be accessed by the invoker based on the app account owner. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------- | ---- | ----------------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to obtain. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the data associated with the specified app account.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------ | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the app account information obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { - console.log("getAssociatedData err: " + JSON.stringify(err)); - console.log('getAssociatedData result: ' + result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAccountsByOwner("com.example.accountjsdemo2").then((data) => { + console.debug("getAccountsByOwner successfully, data:" + JSON.stringify(data)); + }).catch((err) => { + console.debug("getAccountsByOwner failed, error:" + JSON.stringify(err)); + }); + } catch (err) { + console.debug("getAccountsByOwner exception:" + JSON.stringify(err)); + } ``` -### getAssociatedData +### on('accountChange')9+ -getAssociatedData(name: string, key: string): Promise<string> +on(type: 'accountChange', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void -Obtains data associated with an app account. This API uses a promise to return the result. +Subscribes to account information changes of apps. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | --------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to obtain.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'accountChange' | Yes | Event type to subscribe to. The value is **'accountChange'**. An event will be reported when the account information of the target app changes.| +| owners | Array<string> | Yes | App bundle names of the account. | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return a list of app accounts whose information is changed. | -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| Promise<string> | Promise used to return the result.| +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid type or owners. | +| 12300011 | Callback has been registered. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { - console.log('getAssociatedData: ' + data); - }).catch((err) => { - console.log("getAssociatedData err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.log("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + } catch(err) { + console.error("on accountChange failed, error:" + JSON.stringify(err)); + } ``` -### getAssociatedDataSync9+ +### off('accountChange')9+ -getAssociatedDataSync(name: string, key: string): string; +off(type: 'accountChange', callback?: Callback>): void -Obtains the data associated with this app account. This API returns the result synchronously. +Unsubscribes from account information changes. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------ | ---- | --------- | -| name | string | Yes | Name of the target app account. | -| key | string | Yes | Key of the data to obtain.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'accountChange' | Yes | Event type to unsubscribe from. The value is **'accountChange'**. | +| callback | Callback> | No | Callback to unregister.| -**Return value** +**Error codes** -| Type | Description | -| :-------------------- | :-------------------- | -| string | Data obtained.| +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid type. | +| 12300012 | Callback has not been registered. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var backData = appAccountManager.getAssociatedDataSync("ZhangSan", "k001"); - console.info("getAssociatedDataSync backData:" + JSON.stringify(backData)); + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.log("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on("accountChange", ["com.example.actsaccounttest"], changeOnCallback); + } catch(err) { + console.error("on accountChange failed, error:" + JSON.stringify(err)); + } + try{ + appAccountManager.off('accountChange', changeOnCallback); + } + catch(err){ + console.error("off accountChange failed, error:" + JSON.stringify(err)); + } ``` -### getAllAccessibleAccounts - -getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void +### auth9+ -Obtains information about all accessible app accounts. This API uses an asynchronous callback to return the result. +auth(name: string, owner: string, authType: string, callback: AuthCallback): void -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) +Authenticates an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return information about all accessible app accounts.| +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the authentication result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllAccessibleAccounts((err, data)=>{ - console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); - }); - ``` + import featureAbility from '@ohos.ability.featureAbility'; -### getAllAccessibleAccounts + function onResultCallback(code, authResult) { + console.log("resultCode: " + code); + console.log("authResult: " + JSON.stringify(authResult)); + } -getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); + } -Obtains information about all accessible app accounts. This API uses a promise to return the result. + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + } catch (err) { + console.log("auth exception: " + JSON.stringify(err)); + } + ``` -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) +### auth9+ -**System capability**: SystemCapability.Account.AppAccount +auth(name: string, owner: string, authType: string, options: {[key: string]: Object}, callback: AuthCallback): void -**Parameters** - -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the result.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllAccessibleAccounts().then((data) => { - console.log('getAllAccessibleAccounts: ' + data); - }).catch((err) => { - console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); - }); - ``` - -### getAllAccounts - -getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void - -Obtains information about all app accounts of the specified app. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | --------- | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return information about all accessible app accounts.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; - appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ - console.debug("getAllAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccounts data:" + JSON.stringify(data)); - }); - ``` - -### getAllAccounts - -getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> - -Obtains information about all app accounts of the specified app. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ------ | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| - -**Parameters** - -| Type | Description | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the result.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; - appAccountManager.getAllAccounts(selfBundle).then((data) => { - console.log('getAllAccounts: ' + data); - }).catch((err) => { - console.log("getAllAccounts err: " + JSON.stringify(err)); - }); - ``` - -### on('change') - -on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void - -Subscribes to the account change events of the specified account owners. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | 'change' | Yes | Account change events to subscribe to. The subscriber will receive a notification when the account owners update their accounts.| -| owners | Array<string> | Yes | Account owners. | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the account changes. | - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); - } - try{ - appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); - } - catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); - } - ``` - -### off('change') - -off(type: 'change', callback?: Callback>): void - -Unsubscribes from the account change events. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Account.AppAccount - -**Parameters** - -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | ---- | ------------ | -| type | 'change' | Yes | Account change events to unsubscribe from. | -| callback | Callback> | No | Callback used to report the account changes.| - -**Example** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); - appAccountManager.off('change', function(){ - console.debug("off finish"); - }) - } - try{ - appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); - } - catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); - } - ``` - -### authenticate8+ - -authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void - -Authenticates an app account to obtain an Open Authorization (OAuth) token. This API uses an asynchronous callback to return the result. +Authenticates an app account with customized options. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1020,38 +1424,56 @@ Authenticates an app account to obtain an Open Authorization (OAuth) token. This | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | authType | string | Yes | Authentication type. | -| options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.| +| options | {[key: string]: Object} | Yes | Options for the authentication. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the authentication result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not exist. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | **Example** ```js import featureAbility from '@ohos.ability.featureAbility'; - function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); + function onResultCallback(code, authResult) { + console.log("resultCode: " + code); + console.log("authResult: " + JSON.stringify(authResult)); } function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err) => { + console.log("startAbility err: " + JSON.stringify(err)); + }); } - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); + let options = { + "password": "xxxx", + }; + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.auth("LiSi", "com.example.accountjsdemo", "getSocialData", options, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + } catch (err) { + console.log("auth exception: " + JSON.stringify(err)); + } ``` -### getOAuthToken8+ +### getAuthToken9+ -getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void +getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -Obtains the OAuth token of an app account based on the specified authentication type. This API uses an asynchronous callback to return the result. +Obtains the authorization token of the specified authentication type for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1062,23 +1484,39 @@ Obtains the OAuth token of an app account based on the specified authentication | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| | authType | string | Yes | Authentication type. | -| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authorization token value obtained. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name, owner or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getOAuthToken err: ' + JSON.stringify(err)); - console.log('getOAuthToken token: ' + data); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, token) => { + if (err) { + console.log("getAuthToken failed, error: " + JSON.stringify(err)); + } else { + console.log("getAuthToken successfully, token: " + token); + } + }); + } catch (err) { + console.log("getAuthToken exception: " + JSON.stringify(err)); + } ``` -### getOAuthToken8+ +### getAuthToken9+ -getOAuthToken(name: string, owner: string, authType: string): Promise<string> +getAuthToken(name: string, owner: string, authType: string): Promise<string> -Obtains the OAuth token of an app account based on the specified authentication type. This API uses a promise to return the result. +Obtains the authorization token of the specified authentication type for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1090,28 +1528,41 @@ Obtains the OAuth token of an app account based on the specified authentication | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| | authType | string | Yes | Authentication type. | -**Parameters** +**Return value** -| Type | Description | +| Type | Description | | --------------------- | --------------------- | -| Promise<string> | Promise used to return the result.| +| Promise<string> | Promise used to return the authorization token obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getOAuthToken token: ' + data); - }).catch((err) => { - console.log("getOAuthToken err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((token) => { + console.log("getAuthToken successfully, token: " + token); + }).catch((err) => { + console.log("getAuthToken failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthToken exception: " + JSON.stringify(err)); + } ``` -### setOAuthToken8+ +### setAuthToken9+ -setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void +setAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -Sets an OAuth token for an app account. This API uses an asynchronous callback to return the result. +Sets an authorization token of the specific authentication type for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1121,23 +1572,40 @@ Sets an OAuth token for an app account. This API uses an asynchronous callback t | -------- | ------------------------- | ---- | -------- | | name | string | Yes | Name of the target app account.| | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to set.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| token | string | Yes | Token to set.| +| 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 name or authType or token. | +| 12300003 | Account not found. | +| 12400004 | The number of token reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { - console.log('setOAuthToken err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + if (err) { + console.log("setAuthToken failed, error: " + JSON.stringify(err)); + } else { + console.log("setAuthToken successfully"); + } + }); + } catch (err) { + console.log('setAuthToken exception: ' + JSON.stringify(err)); + } ``` -### setOAuthToken8+ +### setAuthToken9+ -setOAuthToken(name: string, authType: string, token: string): Promise<void> +setAuthToken(name: string, authType: string, token: string): Promise<void> -Sets an OAuth token for an app account. This API uses a promise to return the result. +Sets an authorization token of the specific authentication type for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1147,30 +1615,43 @@ Sets an OAuth token for an app account. This API uses a promise to return the re | -------- | ------ | ---- | -------- | | name | string | Yes | Name of the target app account.| | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to set.| +| token | string | Yes | Token to set.| -**Parameters** +**Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or token. | +| 12300003 | Account not found. | +| 12400004 | The number of token reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { - console.log('setOAuthToken successfully'); - }).catch((err) => { - console.log('setOAuthToken err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { + console.log("setAuthToken successfully"); + }).catch((err) => { + console.log("setAuthToken failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setAuthToken exception: " + JSON.stringify(err)); + } ``` -### deleteOAuthToken8+ +### deleteAuthToken9+ -deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void +deleteAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void -Deletes the specified OAuth token for an app account. This API uses an asynchronous callback to return the result. +Deletes the authorization token of the specified authentication type for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1181,23 +1662,40 @@ Deletes the specified OAuth token for an app account. This API uses an asynchron | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to delete.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| token | string | Yes | Token to delete.| +| 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 name or owner or authType or token. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { - console.log('deleteOAuthToken err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { + if (err) { + console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + } else { + console.log("deleteAuthToken successfully"); + } + }); + } catch (err) { + console.log('deleteAuthToken exception: ' + JSON.stringify(err)); + } ``` -### deleteOAuthToken8+ +### deleteAuthToken9+ -deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> +deleteAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> -Deletes the specified OAuth token for an app account. This API uses a promise to return the result. +Deletes the authorization token of the specified authentication type for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1208,30 +1706,43 @@ Deletes the specified OAuth token for an app account. This API uses a promise to | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | | authType | string | Yes | Authentication type. | -| token | string | Yes | OAuth token to delete.| +| token | string | Yes | Token to delete.| -**Parameters** +**Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or authType or token. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { - console.log('deleteOAuthToken successfully'); - }).catch((err) => { - console.log("deleteOAuthToken err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { + console.log("deleteAuthToken successfully"); + }).catch((err) => { + console.log('deleteAuthToken failed, error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('deleteAuthToken exception: ' + JSON.stringify(err)); + } ``` -### setOAuthTokenVisibility8+ +### setAuthTokenVisibility9+ -setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void +setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void -Sets the visibility of an OAuth token to an app. This API uses an asynchronous callback to return the result. +Sets the visibility of an authorization token to an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1242,57 +1753,91 @@ Sets the visibility of an OAuth token to an app. This API uses an asynchronous c | name | string | Yes | Name of the target app account. | | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app. | -| isVisible | boolean | Yes | Whether the OAuth token is visible to the app. The value **true** means visible, and the value **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| +| 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 name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | +| 12400005 | The size of authorization list reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { + if (err) { + console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + } else { + console.log("setAuthTokenVisibility successfully"); + } + }); + } catch (err) { + console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### setOAuthTokenVisibility8+ +### setAuthTokenVisibility9+ -setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> +setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> -Sets the visibility of an OAuth token to an app. This API uses a promise to return the result. +Sets the visibility of an authorization token to an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------- | ---- | ------------ | -| name | string | Yes | Name of the target app account. | -| authType | string | Yes | Authentication type. | -| bundleName | string | Yes | Bundle name of the app.| -| isVisible | boolean | Yes | Whether the OAuth token is visible to the app. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app. | +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| -**Parameters** +**Return value** | Type | Description | | ------------------- | --------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | +| 12400005 | The size of authorization list reaches the upper limit. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { - console.log('setOAuthTokenVisibility successfully'); - }).catch((err) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { + console.log("setAuthTokenVisibility successfully"); + }).catch((err) => { + console.log("setAuthTokenVisibility failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### checkOAuthTokenVisibility8+ +### checkAuthTokenVisibility9+ -checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void +checkAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void -Checks whether an OAuth token is visible to an app. This API uses an asynchronous callback to return the result. +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1303,23 +1848,40 @@ Checks whether an OAuth token is visible to an app. This API uses an asynchronou | name | string | Yes | Name of the target app account. | | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app.| -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** can be **true** (the authorization token is visible to the app) or **false** (the authorization token is not visible to the app). If the operation fails, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); - console.log('checkOAuthTokenVisibility isVisible: ' + data); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, isVisible) => { + if (err) { + console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + } + }); + } catch (err) { + console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### checkOAuthTokenVisibility8+ +### checkAuthTokenVisibility9+ -checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> +checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -Checks whether an OAuth token is visible to an app. This API uses a promise to return the result. +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1331,28 +1893,42 @@ Checks whether an OAuth token is visible to an app. This API uses a promise to r | authType | string | Yes | Authentication type. | | bundleName | string | Yes | Bundle name of the app.| -**Parameters** +**Return value** | Type | Description | | ---------------------- | --------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return the result. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType or bundleName. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | +| 12400001 | Application not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { - console.log('checkOAuthTokenVisibility isVisible: ' + data); - }).catch((err) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((isVisible) => { + console.log("checkAuthTokenVisibility successfully, isVisible: " + isVisible); + }).catch((err) => { + console.log("checkAuthTokenVisibility failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkAuthTokenVisibility exception: " + JSON.stringify(err)); + } ``` -### getAllOAuthTokens8+ +### getAllAuthTokens9+ -getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void +getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<AuthTokenInfo>>): void -Obtains all OAuth tokens visible to the caller for an app account. This API uses an asynchronous callback to return the result. +Obtains all tokens visible to the invoker for an app account. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1362,23 +1938,38 @@ Obtains all OAuth tokens visible to the caller for an app account. This API uses | -------- | ---------------------------------------- | ---- | ----------- | | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| callback | AsyncCallback<Array< [OAuthTokenInfo](#oauthtokeninfo8)>> | Yes | Callback invoked to return the result. | +| callback | AsyncCallback<Array<[AuthTokenInfo](#authtokeninfo9)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of all tokens visible to the invoker. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo", (err, data) => { - console.log("getAllOAuthTokens err: " + JSON.stringify(err)); - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo", (err, tokenArr) => { + if (err) { + console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + } else { + console.log('getAllAuthTokens successfully, tokenArr: ' + tokenArr); + } + }); + } catch (err) { + console.log("getAllAuthTokens exception: " + JSON.stringify(err)); + } ``` -### getAllOAuthTokens8+ +### getAllAuthTokens9+ -getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> +getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo>> -Obtains all OAuth tokens visible to the caller for an app account. This API uses a promise to return the result. +Obtains all tokens visible to the invoker for an app account. This API uses a promise to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -1389,584 +1980,2519 @@ Obtains all OAuth tokens visible to the caller for an app account. This API uses | name | string | Yes | Name of the target app account. | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -**Parameters** +**Return value** | Type | Description | | ---------------------------------------- | --------------------- | -| Promise<Array< [OAuthTokenInfo](#oauthtokeninfo8)>> | Promise used to return the result.| +| Promise<Array<[AuthTokenInfo](#authtokeninfo9)>> | Promise used to return the tokens obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAllAuthTokens("LiSi", "com.example.accountjsdemo").then((tokenArr) => { + console.log('getAllAuthTokens successfully, tokenArr: ' + JSON.stringify(tokenArr)); + }).catch((err) => { + console.log("getAllAuthTokens failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAllAuthTokens exception: " + JSON.stringify(err)); + } + ``` + +### getAuthList9+ + +getAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void + +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by [setAuthTokenVisibility](#setauthtokenvisibility9). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| +| 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 authorized bundles obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData", (err, authList) => { + if (err) { + console.log("getAuthList failed, error: " + JSON.stringify(err)); + } else { + console.log("getAuthList successfully, authList: " + authList); + } + }); + } catch (err) { + console.log('getAuthList exception: ' + JSON.stringify(err)); + } + ``` + +### getAuthList9+ + +getAuthList(name: string, authType: string): Promise<Array<string>> + +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by [setAuthTokenVisibility](#setauthtokenvisibility9). This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------------------------ | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| + +**Return value** + +| Type | Description | +| ---------------------------------- | --------------------- | +| Promise<Array<string>> | Promise used to return a list of authorized bundles.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or authType. | +| 12300003 | Account not found. | +| 12300107 | AuthType not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.getAuthList("com.example.accountjsdemo", "getSocialData").then((authList) => { + console.log("getAuthList successfully, authList: " + authList); + }).catch((err) => { + console.log("getAuthList failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthList exception: " + JSON.stringify(err)); + } + ``` + +### getAuthCallback9+ + +getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): void + +Obtains the authenticator callback for the authentication session. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| +| callback | AsyncCallback<[AuthCallback](#authcallback9)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator callback object obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid sessionId. | +| 12300108 | Session not found. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant((err, want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + try { + appAccountManager.getAuthCallback(sessionId, (err, callback) => { + if (err.code != account_appAccount.ResultCode.SUCCESS) { + console.log("getAuthCallback err: " + JSON.stringify(err)); + return; + } + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }); + } catch (err) { + console.log("getAuthCallback exception: " + JSON.stringify(err)); + } + }); + ``` + +### getAuthCallback9+ + +getAuthCallback(sessionId: string): Promise<AuthCallback> + +Obtains the authenticator callback for the authentication session. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| + +**Return value** + +| Type | Description | +| ------------------------------------ | --------------------- | +| Promise<[AuthCallback](#authcallback9)> | Promise used to return the authenticator callback obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid sessionId. | +| 12300108 | Session not found. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant().then((want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + try { + appAccountManager.getAuthCallback(sessionId).then((callback) => { + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthCallback err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthCallback exception: " + JSON.stringify(err)); + } + }).catch((err) => { + console.log("getWant err: " + JSON.stringify(err)); + }); + ``` + +### queryAuthenticatorInfo9+ + +queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void + +Obtains the authenticator information of an app. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator information obtained. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300113 | Authenticator service not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo", (err, info) => { + if (err) { + console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + } else { + console.log('queryAuthenticatorInfo successfully, info: ' + JSON.stringify(info)); + } + }); + } catch (err) { + console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); + } + ``` + +### queryAuthenticatorInfo9+ + +queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> + +Obtains the authenticator information of an app. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Bundle name of the app.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise used to return the authenticator information obtained.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300113 | Authenticator service not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.queryAuthenticatorInfo("com.example.accountjsdemo").then((info) => { + console.log("queryAuthenticatorInfo successfully, info: " + JSON.stringify(info)); + }).catch((err) => { + console.log("queryAuthenticatorInfo failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("queryAuthenticatorInfo exception: " + JSON.stringify(err)); + } + ``` + +### checkAccountLabels9+ + +checkAccountLabels(name: string, owner: string, labels: Array<string>, callback: AsyncCallback<boolean>): void; + +Checks whether an app account has specific labels. This API uses an asynchronous callback to return the result. The labels are checked by the authenticator of the target app. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| labels | Array<string> | Yes | Labels to check. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** can be **true** or **false**. The value **true** means the app account has the labels; the value **false** means the opposite. If the operation fails, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or labels. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let labels = ["student"]; + try { + appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels, (err, hasAllLabels) => { + if (err) { + console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + } else { + console.log("checkAccountLabels successfully, hasAllLabels: " + hasAllLabels); + } + }); + } catch (err) { + console.log("checkAccountLabels exception: " + JSON.stringify(err)); + } + ``` + +### checkAccountLabels9+ + +checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> + +Checks whether an app account has specific labels. This API uses a promise to return the result. The labels are checked by the authenticator of the target app. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| labels | Array<string> | Yes | Labels to check. | + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means the app account has the labels; the value **false** means the opposite.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or labels. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let labels = ["student"]; + try { + appAccountManager.checkAccountLabels("zhangsan", "com.example.accountjsdemo", labels).then((hasAllLabels) => { + console.log('checkAccountLabels successfully: ' + hasAllLabels); + }).catch((err) => { + console.log("checkAccountLabels failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkAccountLabels exception: " + JSON.stringify(err)); + } + ``` + +### deleteCredential9+ + +deleteCredential(name: string, credentialType: string, callback: AsyncCallback<void>): void + +Deletes the credential of the specified type from an app account. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | -------------- | +| name | string | Yes | Name of the target app account.| +| credentialType | string | Yes | Type of the credential to delete. | +| 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 name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | **Example** - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteCredential("zhangsan", "PIN_SIX", (err) => { + if (err) { + console.log("deleteCredential failed, error: " + JSON.stringify(err)); + } else { + console.log("deleteCredential successfully"); + } + }); + } catch (err) { + console.log("deleteCredential exception: " + JSON.stringify(err)); + } + ``` + +### deleteCredential9+ + +deleteCredential(name: string, credentialType: string): Promise<void> + +Deletes the credential of the specified type from an app account. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | ----- | --------------- | +| name | string | Yes | Name of the target app account.| +| credentialType | string | Yes | Type of the credential to delete. | + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid name or credentialType. | +| 12300003 | Account not found. | +| 12300102 | Credential not found. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.deleteCredential("zhangsan", "PIN_SIX").then(() => { + console.log("deleteCredential successfully"); + }).catch((err) => { + console.log("deleteCredential failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("deleteCredential exception: " + JSON.stringify(err)); + } + ``` + +### selectAccountsByOptions9+ + +selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>): void + +Selects the accounts that can be accessed by the invoker based on the options. This API uses an asynchronous callback to return the result. If the options contain label constraints, the authenticator of the target app provides the capability of checking the labels. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ----- | --------------- | +| options | SelectAccountsOptions | Yes | Options for selecting accounts. | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of accounts selected. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid options. | +| 12300010 | Account service busy. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + allowedOwners: [ "com.example.accountjsdemo" ], + requiredLabels: [ "student" ] + }; + try { + appAccountManager.selectAccountsByOptions(options, (err, accountArr) => { + if (err) { + console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + } else { + console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + } + }); + } catch (err) { + console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); + } + ``` + +### selectAccountsByOptions9+ + +selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> + +Selects the accounts that can be accessed by the invoker based on the options. This API uses a promise to return the result. If the options contain label constraints, the authenticator of the target app provides the capability of checking the labels. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ----- | --------------- | +| options | [SelectAccountsOptions](#selectaccountsoptions9) | Yes | Options for selecting accounts. | + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| Promise<[AppAccountInfo](#appaccountinfo)> | Promise used to return the accounts selected.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid options. | +| 12300010 | Account service busy. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + allowedOwners: ["com.example.accountjsdemo"] + }; + try { + appAccountManager.selectAccountsByOptions(options).then((accountArr) => { + console.log("selectAccountsByOptions successfully, accountArr: " + JSON.stringify(accountArr)); + }).catch((err) => { + console.log("selectAccountsByOptions failed, error: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("selectAccountsByOptions exception: " + JSON.stringify(err)); + } + ``` + +### verifyCredential9+ + +verifyCredential(name: string, owner: string, callback: AuthCallback): void; + +Verifies the credential of an app account. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ----- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", { + onResult: (resultCode, result) => { + console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("verifyCredential onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("verifyCredential err: " + JSON.stringify(err)); + } + ``` + +### verifyCredential9+ + +verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthCallback): void; + +Verifies the user credential. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------- | ----- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for verifying the user credential. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------| +| 12300001 | System service exception. | +| 12300002 | Invalid name or owner or options. | +| 12300003 | Account not found. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + credentialType: "pin", + credential: "123456" + }; + try { + appAccountManager.verifyCredential("zhangsan", "com.example.accountjsdemo", options, { + onResult: (resultCode, result) => { + console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("verifyCredential onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("verifyCredential err: " + JSON.stringify(err)); + } + ``` + +### setAuthenticatorProperties9+ + +setAuthenticatorProperties(owner: string, callback: AuthCallback): void; + +Sets the authenticator attributes of an app. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ----- | ----------------------- | +| owner | string | Yes | Owner of the authenticator. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid owner. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + try { + appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", { + onResult: (resultCode, result) => { + console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + } + ``` + +### setAuthenticatorProperties9+ + +setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callback: AuthCallback): void; + +Set authenticator properties. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ----- | ----------------------- | +| owner | string | Yes | Owner of the authenticator. | +| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | ------- | +| 12300001 | System service exception. | +| 12300002 | Invalid owner or options. | +| 12300010 | Account service busy. | +| 12300113 | Authenticator service not found. | +| 12300114 | Authenticator service exception. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + let options = { + properties: {"prop1": "value1"} + }; + try { + appAccountManager.setAuthenticatorProperties("com.example.accountjsdemo", options, { + onResult: (resultCode, result) => { + console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); + console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); + }, + onRequestRedirected: (request) => { + console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); + } + }); + } catch (err) { + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + } + + ``` + +### addAccount(deprecated) + +addAccount(name: string, callback: AsyncCallback<void>): void + +Adds an app 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 [createAccount](#createaccount9). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------------------- | +| name | string | Yes | Name of the target app 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.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("WangWu", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### addAccount(deprecated) + +addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void + +Adds an app account name and additional information. 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 [createAccount](#createaccount9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | Yes | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("LiSi", "token101", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### addAccount(deprecated) + +addAccount(name: string, extraInfo?: string): Promise<void> + +Adds an app account name and additional information. This API uses an asynchronous callback to return the result. 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 [createAccount](#createaccount9-2). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ---------------------------------------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | No | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token.| + +**Return value** + +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccount("LiSi", "token101").then(()=> { + console.log('addAccount Success'); + }).catch((err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); + ``` + +### addAccountImplicitly(deprecated) + +addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void + +Adds an app account implicitly based on the specified owner. 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 [createAccountImplicitly](#createaccountimplicitly9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | ----------------------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. The authentication type is customized. | +| options | {[key: string]: any} | Yes | Authentication options, which can be set as required.| +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Authenticator callback invoked to return the result. | + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err)=>{ + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccountImplicitly("com.example.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); + ``` + +### deleteAccount(deprecated) + +deleteAccount(name: string, callback: AsyncCallback<void>): void + +Deletes an app 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 [removeAccount](#removeaccount9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ---------------- | +| name | string | Yes | Name of the target app 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.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteAccount("ZhaoLiu", (err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); + }); + ``` + +### deleteAccount(deprecated) + +deleteAccount(name: string): Promise<void> + +Deletes an app 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 [removeAccount](#removeaccount9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ----------- | +| name | string | Yes | Name of the target app account.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteAccount("ZhaoLiu").then(() => { + console.log('deleteAccount Success'); + }).catch((err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); + }); + ``` +### disableAppAccess(deprecated) + +disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void + +Disables an app account from accessing an app. 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 [setAppAccess](#setappaccess9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | --------------------------------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### disableAppAccess(deprecated) + +disableAppAccess(name: string, bundleName: string): Promise<void> + +Disables an app account from accessing an app. 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 [setAppAccess](#setappaccess9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ---------------- | +| name | string | Yes | Name of the target app account.| +| bundleName | string | Yes | Bundle name of the app. | + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.disableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { + console.log('disableAppAccess Success'); + }).catch((err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### enableAppAccess(deprecated) + +enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void + +Enables an app account to access an app. 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 [setAppAccess](#setappaccess9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | --------------------------------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo", (err) => { + console.log("enableAppAccess: " + JSON.stringify(err)); + }); + ``` + +### enableAppAccess(deprecated) + +enableAppAccess(name: string, bundleName: string): Promise<void> + +Enables an app account to access an app. 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 [setAppAccess](#setappaccess9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| bundleName | string | Yes | Bundle name of the app.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.enableAppAccess("ZhangSan", "com.example.accountjsdemo").then(() => { + console.log('enableAppAccess Success'); + }).catch((err) => { + console.log("enableAppAccess err: " + JSON.stringify(err)); + }); + ``` + +### checkAppAccountSyncEnable(deprecated) + +checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void + +Checks whether data synchronization is enabled for an app 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 [checkDataSyncEnabled](#checkdatasyncenabled9). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------- | ---- | --------------------- | +| name | string | Yes | Name of the target app account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + console.log('checkAppAccountSyncEnable result: ' + result); + }); + ``` + +### checkAppAccountSyncEnable(deprecated) + +checkAppAccountSyncEnable(name: string): Promise<boolean> + +Checks whether data synchronization is enabled for an app 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 [checkDataSyncEnabled](#checkdatasyncenabled9-1). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | Name of the target app account.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means data synchronization is enabled for the app account; the value **false** means the opposite.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { + console.log('checkAppAccountSyncEnable, result: ' + data); + }).catch((err) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAccountCredential(deprecated) + +setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void + +Set credentials for an app 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 [setCredential](#setcredential9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------------------------- | ---- | ------------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to set. | +| credential | string | Yes | Credential value. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { + console.log("setAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### setAccountCredential(deprecated) + +setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> + +Set credentials for an app 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 [setCredential](#setcredential9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to set.| +| credential | string | Yes | Credential value.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { + console.log('setAccountCredential Success'); + }).catch((err) => { + console.log("setAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### setAccountExtraInfo(deprecated) + +setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void + +Sets additional information for an app 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 [setCustomData](#setcustomdata9). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | Yes | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### setAccountExtraInfo(deprecated) + +setAccountExtraInfo(name: string, extraInfo: string): Promise<void> + +Sets additional information for an app 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 [setCustomData](#setcustomdata9-1). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| extraInfo | string | Yes | Additional information (information that can be converted to the string type). It cannot contain sensitive information, such as the app account password and token.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { + console.log('setAccountExtraInfo Success'); + }).catch((err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### setAppAccountSyncEnable(deprecated) + +setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void + +Sets data synchronization for an app 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 [setDataSyncEnabled](#setdatasyncenabled9). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| isEnable | boolean | Yes | Whether to enable data synchronization. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAppAccountSyncEnable(deprecated) + +setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> + +Sets data synchronization for an app 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 [setDataSyncEnabled](#setdatasyncenabled9-1). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| isEnable | boolean | Yes | Whether to enable data synchronization.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { + console.log('setAppAccountSyncEnable Success'); + }).catch((err) => { + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); + }); + ``` + +### setAssociatedData(deprecated) + +setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void + +Sets data to be associated with an app 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 [setCustomData](#setcustomdata9). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to set.| +| value | string | Yes | Value of the data to set. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { + console.log("setAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### setAssociatedData(deprecated) + +setAssociatedData(name: string, key: string, value: string): Promise<void> + +Sets data to be associated with an app 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 [setCustomData](#setcustomdata9-1). + + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to set.| +| value | string | Yes | Value of the data to set.| + +**Return value** + +| Type | Description | +| :------------------ | :-------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { + console.log('setAssociatedData Success'); + }).catch((err) => { + console.log("setAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### getAllAccessibleAccounts(deprecated) + +getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void + +Obtains information about all accessible app accounts. 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 [getAllAccounts](#getallaccounts9). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of accessible app accounts. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllAccessibleAccounts((err, data)=>{ + console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); + }); + ``` + +### getAllAccessibleAccounts(deprecated) + +getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> + +Obtains information about all accessible app accounts. 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 [getAllAccounts](#getallaccounts9-1). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS + +**System capability**: SystemCapability.Account.AppAccount + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise used to return the accessible app accounts.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllAccessibleAccounts().then((data) => { + console.log('getAllAccessibleAccounts: ' + data); + }).catch((err) => { + console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); + }); + ``` + +### getAllAccounts(deprecated) + +getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void + +Obtains the app accounts that can be accessed by the invoker based on the app account owner. 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 [getAccountsByOwner](#getaccountsbyowner9). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | --------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return information about all accessible app accounts.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ + console.debug("getAllAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccounts data:" + JSON.stringify(data)); + }); + ``` + +### getAllAccounts(deprecated) + +getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> + +Obtains the app accounts that can be accessed by the invoker based on the app account owner. 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 [getAccountsByOwner](#getaccountsbyowner9-1). + +**Required permissions**: ohos.permission.GET_ALL_APP_ACCOUNTS (available only to system applications) + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ------ | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise use to return the app accounts that can be accessed by the invoker.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle).then((data) => { + console.log('getAllAccounts: ' + data); + }).catch((err) => { + console.log("getAllAccounts err: " + JSON.stringify(err)); + }); + ``` + +### getAccountCredential(deprecated) + +getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void + +Obtains the credential of an app 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 [getCredential](#getcredential9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to obtain.| +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the credential obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { + console.log("getAccountCredential err: " + JSON.stringify(err)); + console.log('getAccountCredential result: ' + result); + }); + ``` + +### getAccountCredential(deprecated) + +getAccountCredential(name: string, credentialType: string): Promise<string> + +Obtains the credential of an app 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 [getCredential](#getcredential9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ------ | ---- | ---------- | +| name | string | Yes | Name of the target app account. | +| credentialType | string | Yes | Type of the credential to obtain.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the credential obtained.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { + console.log('getAccountCredential, result: ' + data); + }).catch((err) => { + console.log("getAccountCredential err: " + JSON.stringify(err)); + }); + ``` + +### getAccountExtraInfo(deprecated) + +getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void + +Obtains additional information of an app account. Additional information refers to other information that can be converted to the string type. It cannot contain sensitive information, such as the app account password and token. 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 [getCustomData](#getcustomdata9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the additional information obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + console.log('getAccountExtraInfo result: ' + result); + }); + ``` + +### getAccountExtraInfo(deprecated) + +getAccountExtraInfo(name: string): Promise<string> + +Obtains additional information of an app account. Additional information refers to other information that can be converted to the string type. It cannot contain sensitive information, such as the app account password and token. 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 [getCustomData](#getcustomdata9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | ------- | +| name | string | Yes | Name of the target app account.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the additional information obtained.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { + console.log('getAccountExtraInfo, result: ' + data); + }).catch((err) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + }); + ``` + +### getAssociatedData(deprecated) + +getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void + +Obtains data associated with an app 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 [getCustomData](#getcustomdata9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to obtain. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the data obtained. Otherwise, **err** is an error object.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + console.log('getAssociatedData result: ' + result); + }); + ``` + +### getAssociatedData(deprecated) + +getAssociatedData(name: string, key: string): Promise<string> + +Obtains data associated with an app 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 [getCustomData](#getcustomdata9-1). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | --------- | +| name | string | Yes | Name of the target app account. | +| key | string | Yes | Key of the data to obtain.| + +**Return value** + +| Type | Description | +| :-------------------- | :-------------------- | +| Promise<string> | Promise used to return the data obtained.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { + console.log('getAssociatedData: ' + data); + }).catch((err) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + }); + ``` + +### on('change')(deprecated) + +on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void + +Subscribes to account information changes of apps. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on('accountChange')](#onaccountchange9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'change' | Yes | Event type to subscribe to. The value is **'change'**. An event will be reported when the account information changes.| +| owners | Array<string> | Yes | App bundle names of the account. | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | Yes | Callback invoked to return the account changes. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } + ``` + +### off('change')(deprecated) + +off(type: 'change', callback?: Callback>): void + +Unsubscribes from account information changes. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off('accountChange')](#offaccountchange9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'change' | Yes | Event type to unsubscribe from. The value is **'change'**, which indicates the account change event. | +| callback | Callback> | No | Callback to unregister.| + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + appAccountManager.off('change', function(){ + console.debug("off finish"); + }) + } + try{ + appAccountManager.on('change', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } + ``` + +### authenticate(deprecated) + +authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void + +Authenticates an app account with customized options. 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 [auth](#auth9). + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| options | {[key: string]: any} | Yes | Options for the authentication. | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Callback invoked to return the result.| + +**Example** + + ```js + import featureAbility from '@ohos.ability.featureAbility'; + + function onResultCallback(code, result) { + console.log("resultCode: " + code); + console.log("result: " + JSON.stringify(result)); + } + + function onRequestRedirectedCallback(request) { + let abilityStartSetting = {want: request}; + featureAbility.startAbility(abilityStartSetting, (err)=>{ + console.log("startAbility err: " + JSON.stringify(err)); + }); + } + + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.authenticate("LiSi", "com.example.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback }); ``` -### getOAuthList8+ +### getOAuthToken(deprecated) -getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void +getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -Obtains a list of authorized OAuth tokens of an app account. This API uses an asynchronous callback to return the result. +Obtains the authorization token of the specified authentication type for an app account. 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 [getAuthToken](#getauthtoken9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| authType | string | Yes | Authorization type.| -| callback | AsyncCallback<Array<string>> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | --------------------------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| authType | string | Yes | Authentication type. | +| callback | AsyncCallback<string> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authorization token value obtained. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getOAuthList err: ' + JSON.stringify(err)); - console.log('getOAuthList data: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", (err, data) => { + console.log('getOAuthToken err: ' + JSON.stringify(err)); + console.log('getOAuthToken token: ' + data); }); ``` -### getOAuthList8+ +### getOAuthToken(deprecated) -getOAuthList(name: string, authType: string): Promise<Array<string>> +getOAuthToken(name: string, owner: string, authType: string): Promise<string> -Obtains a list of authorized OAuth tokens of an app account. This API uses a promise to return the result. +Obtains the authorization token of the specified authentication type for an app account. 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 [getAuthToken](#getauthtoken9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------ | ---- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| authType | string | Yes | Authorization type.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| authType | string | Yes | Authentication type. | -**Parameters** +**Return value** -| Type | Description | -| ---------------------------------- | --------------------- | -| Promise<Array<string>> | Promise used to return the result.| +| Type | Description | +| --------------------- | --------------------- | +| Promise<string> | Promise used to return the result.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getOAuthList data: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData").then((data) => { + console.log('getOAuthToken token: ' + data); }).catch((err) => { - console.log("getOAuthList err: " + JSON.stringify(err)); + console.log("getOAuthToken err: " + JSON.stringify(err)); }); ``` -### getAuthenticatorCallback8+ +### setOAuthToken(deprecated) -getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void +setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -Obtains the authenticator callback for an authentication session. This API uses an asynchronous callback to return the result. +Sets an authorization token of the specific authentication type for an app account. 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 [setAuthToken](#setauthtoken9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------------- | ---- | -------- | -| sessionId | string | Yes | ID of the authentication session.| -| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallback8)> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | -------- | +| name | string | Yes | Name of the target app account.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | Token to set.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object.| **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; - const appAccountManager = account_appAccount.createAppAccountManager(); - featureAbility.getWant((err, want) => { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; - appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { - if (err.code != account_appAccount.ResultCode.SUCCESS) { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); - return; - } - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` -### getAuthenticatorCallback8+ +### setOAuthToken(deprecated) -getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> +setOAuthToken(name: string, authType: string, token: string): Promise<void> -Obtains the authenticator callback for an authentication session. This API uses a promise to return the result. +Sets an authorization token of the specific authentication type for an app account. 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 [setAuthToken](#setauthtoken9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ------ | ---- | -------- | -| sessionId | string | Yes | ID of the authentication session.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | -------- | +| name | string | Yes | Name of the target app account.| +| authType | string | Yes | Authentication type. | +| token | string | Yes | Authorization token to set.| -**Parameters** +**Return value** -| Type | Description | -| ------------------------------------ | --------------------- | -| Promise<[AuthenticatorCallback](#authenticatorcallback8)> | Promise used to return the result.| +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - import featureAbility from '@ohos.ability.featureAbility'; - - const appAccountManager = account_appAccount.createAppAccountManager(); - featureAbility.getWant().then((want) => { - var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; - appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { - var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", - [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - }).catch((err) => { - console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); - }); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx").then(() => { + console.log('setOAuthToken successfully'); }).catch((err) => { - console.log("getWant err: " + JSON.stringify(err)); + console.log('setOAuthToken err: ' + JSON.stringify(err)); }); ``` -### getAuthenticatorInfo8+ +### deleteOAuthToken(deprecated) -getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void +deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void + +Deletes the authorization token of the specified authentication type for an app account. This API uses an asynchronous callback to return the result. -Obtains authenticator information of an app account. 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 [deleteAuthToken](#deleteauthtoken9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | ---- | ----------- | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ------------ | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | Authorization token to delete.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { - console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); - console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx", (err) => { + console.log('deleteOAuthToken err: ' + JSON.stringify(err)); }); ``` -### getAuthenticatorInfo8+ +### deleteOAuthToken(deprecated) -getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> +deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> + +Deletes the authorization token of the specified authentication type for an app account. This API uses a promise to return the result. -Obtains authenticator information of an app account. 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 [deleteAuthToken](#deleteauthtoken9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----------- | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ------------ | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | +| authType | string | Yes | Authentication type. | +| token | string | Yes | Authorization token to delete.| -**Parameters** +**Return value** -| Type | Description | -| -------------------------------- | --------------------- | -| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise used to return the result.| +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { - console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.accountjsdemo", "getSocialData", "xxxxx").then(() => { + console.log('deleteOAuthToken successfully'); }).catch((err) => { - console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log("deleteOAuthToken err: " + JSON.stringify(err)); }); ``` -### checkAppAccess9+ +### setOAuthTokenVisibility(deprecated) -checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<boolean>): void +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void + +Sets the visibility of an authorization token to an app. This API uses an asynchronous callback to return the result. -Checks whether an app account is authorized to access an app. 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 [setAuthTokenVisibility](#setauthtokenvisibility9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------- | ----- | ---------------- | -| name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to access. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ------------------------- | ---- | ------------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app. | +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null**. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccess("zhangsan", "com.example.ohos.accountjsdemo", (err, data) => { - console.log('checkAppAccess: ' + JSON.stringify(data)); - console.log("checkAppAccess err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true, (err) => { + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` -### checkAppAccess9+ +### setOAuthTokenVisibility(deprecated) -checkAppAccess(name: string, bundleName: string): Promise<boolean> +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> + +Sets the visibility of an authorization token to an app. This API uses a promise to return the result. -Checks whether an app account is authorized to access an app. 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 [setAuthTokenVisibility](#setauthtokenvisibility9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------ | ----- | ---------------- | -| name | string | Yes | Name of the target app account. | -| bundleName | string | Yes | Bundle name of the app to access. | +| Name | Type | Mandatory | Description | +| ---------- | ------- | ---- | ------------ | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| isVisible | boolean | Yes | Whether the authorization token is visible to the app. The value **true** means the authorization token is visible to the app; the value **false** means the opposite. | -**Parameters** +**Return value** -| Type | Description | -| ---------------------- | --------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Type | Description | +| ------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkAppAccess("zhangsan", "com.example.ohos.accountjsdemo").then((data) => { - console.log('checkAppAccess: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", true).then(() => { + console.log('setOAuthTokenVisibility successfully'); }).catch((err) => { - console.log("checkAppAccess err: " + JSON.stringify(err)); + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` -### deleteAccountCredential9+ +### checkOAuthTokenVisibility(deprecated) -deleteAccountCredential(name: string, credentialType: string, callback: AsyncCallback<void>): void +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void + +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses an asynchronous callback to return the result. -Deletes the credential of an app account. 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 [checkAuthTokenVisibility](#checkauthtokenvisibility9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | -------------- | -| name | string | Yes | Name of the target app account.| -| credentialType | string | Yes | Type of the credential to delete. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| ---------- | ---------------------------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** can be **true** (the authorization token is visible to the app) or **false** (the authorization token is not visible to the app). If the operation fails, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccountCredential("zhangsan", "pin", (err, data) => { - console.log('deleteAccountCredential: ' + JSON.stringify(data)); - console.log("deleteAccountCredential err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo", (err, data) => { + console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log('checkOAuthTokenVisibility isVisible: ' + data); }); ``` -### deleteAccountCredential9+ +### checkOAuthTokenVisibility(deprecated) + +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -deleteAccountCredential(name: string, credentialType: string): Promise<void> +Checks the visibility of an authorization token of the specified authentication type to an app. This API uses a promise to return the result. -Deletes the credential of an app account. 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 [checkAuthTokenVisibility](#checkauthtokenvisibility9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | ----- | --------------- | -| name | string | Yes | Name of the target app account.| -| credentialType | string | Yes | Type of the credential to delete. | +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| bundleName | string | Yes | Bundle name of the app.| -**Parameters** +**Return value** -| Type | Description | -| ------------------- | -------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ---------------------- | --------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means the authorization token is visible to the app; the value **false** means the opposite.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccountCredential("zhangsan", "pin").then((data) => { - console.log('deleteAccountCredential: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.accountjsdemo").then((data) => { + console.log('checkOAuthTokenVisibility isVisible: ' + data); }).catch((err) => { - console.log("deleteAccountCredential err: " + JSON.stringify(err)); + console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); }); ``` -### checkAccountLabels9+ +### getAllOAuthTokens(deprecated) -checkAccountLabels(name: string, owner: string, labels: Array<string>, callback: AsyncCallback<boolean>): void; +getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void + +Obtains all tokens visible to the invoker for an app account. This API uses an asynchronous callback to return the result. -Checks whether an app account has specific labels. 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 [getAllAuthTokens](#getallauthtokens9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | --------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| labels | Array<string> | Yes | Labels to check. | -| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| callback | AsyncCallback<Array<[OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is a list of all tokens visible to the invoker. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels, (err, data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); - console.log("checkAccountLabels err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo", (err, data) => { + console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }); ``` -### checkAccountLabels9+ +### getAllOAuthTokens(deprecated) -checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> +getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> -Checks whether an app account has specific labels. This API uses a promise to return the result. +Obtains all tokens visible to the invoker for an app account. 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 [getAllAuthTokens](#getallauthtokens9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | --------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| labels | Array<string> | Yes | Labels to check. | +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| name | string | Yes | Name of the target app account. | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -**Parameters** +**Return value** -| Type | Description | -| ------------------- | -------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Type | Description | +| ---------------------------------------- | --------------------- | +| Promise<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Promise used to return the tokens obtained.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels).then((data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAllOAuthTokens("LiSi", "com.example.accountjsdemo").then((data) => { + console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); }).catch((err) => { - console.log("checkAccountLabels err: " + JSON.stringify(err)); + console.log("getAllOAuthTokens err: " + JSON.stringify(err)); }); ``` -### selectAccountsByOptions9+ +### getOAuthList(deprecated) + +getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void -selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>); +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by setOAuthTokenVisibility(#setoauthtokenvisibilitydeprecated). This API uses an asynchronous callback to return the result. -Selects the accounts accessible to the requester based on the options. 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 [getAuthList](#getauthlist9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ----------------------------------- | ----- | --------------- | -| options | SelectAccountsOptions | Yes | Options for selecting accounts. | -| callback | AsyncCallback<[AppAccountInfo](#appaccountinfo)> | Yes | Callback invoked to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| +| 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 authorized bundles obtained. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] - }; - appAccountManager.selectAccountsByOptions(options, (err, data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData", (err, data) => { + console.log('getOAuthList err: ' + JSON.stringify(err)); + console.log('getOAuthList data: ' + JSON.stringify(data)); }); ``` -### selectAccountsByOptions9+ +### getOAuthList(deprecated) -selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> +getOAuthList(name: string, authType: string): Promise<Array<string>> -Selects the accounts accessible to the requester based on the options. This API uses a promise to return the result. +Obtains the authorization list of the specified authentication type for an app account. The authorization list contains all authorized bundles. The token authorization list is set by setOAuthTokenVisibility(#setoauthtokenvisibilitydeprecated). 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 [getAuthList](#getauthlist9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------------------------- | ----- | --------------- | -| options | [SelectAccountsOptions](#selectaccountsoptions9) | Yes | Options for selecting accounts. | +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----------------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type.| -**Parameters** +**Return value** -| Type | Description | -| ------------------- | -------------------------------- | -| Promise<[AppAccountInfo](#appaccountinfo)> | Promise used to return the result.| +| Type | Description | +| ---------------------------------- | --------------------- | +| Promise<Array<string>> | Promise used to return a list of authorized bundles.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] - }; - appAccountManager.selectAccountsByOptions(options).then((data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.accountjsdemo", "getSocialData").then((data) => { + console.log('getOAuthList data: ' + JSON.stringify(data)); }).catch((err) => { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + console.log("getOAuthList err: " + JSON.stringify(err)); }); ``` -### verifyCredential9+ +### getAuthenticatorCallback(deprecated) -verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): void; +getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void -Verifies the user credential. This API uses an asynchronous callback to return the result. +Obtains the authenticator callback for an authentication session. 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 [getAuthCallback](#getauthcallback9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------- | ----- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| +| Name | Type | Mandatory | Description | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| +| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator callback obtained. Otherwise, **err** is an error object.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", { - onResult: (resultCode, result) => { - console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("verifyCredential onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); - } + import featureAbility from '@ohos.ability.featureAbility'; + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant((err, want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId, (err, callback) => { + if (err.code != account_appAccount.ResultCode.SUCCESS) { + console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + return; + } + var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", + [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }); }); ``` -### verifyCredential9+ +### getAuthenticatorCallback(deprecated) -verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; +getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> -Verifies the user credential. This API uses an asynchronous callback to return the result. +Obtains the authenticator callback for an authentication session. 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 [getAuthCallback](#getauthcallback9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------- | ----- | ----------------------- | -| name | string | Yes | Name of the target app account. | -| owner | string | Yes | Owner of the app account. The value is the bundle name of the app. | -| options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for verifying the user credential. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | -------- | +| sessionId | string | Yes | ID of the authentication session.| + +**Return value** + +| Type | Description | +| ------------------------------------ | --------------------- | +| Promise<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Promise used to return the authenticator callback obtained.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - credentialType: "pin", - credential: "123456" - }; - appAccountManager.verifyCredential("zhangsan", "com.example.ohos.accountjsdemo", options, { - onResult: (resultCode, result) => { - console.log("verifyCredential onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("verifyCredential onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("verifyCredential onRequestRedirected, request:" + JSON.stringify(request)); - } + import featureAbility from '@ohos.ability.featureAbility'; + + let appAccountManager = account_appAccount.createAppAccountManager(); + featureAbility.getWant().then((want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { + var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", + [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", + [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthenticatorCallback err: " + JSON.stringify(err)); + }); + }).catch((err) => { + console.log("getWant err: " + JSON.stringify(err)); }); ``` -### setAuthenticatorProperties9+ +### getAuthenticatorInfo(deprecated) + +getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void -setAuthenticatorProperties(owner: string, callback: AuthenticatorCallback): void; +Obtains the authenticator information of an app. This API uses an asynchronous callback to return the result. -Sets authenticator properties. 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 [queryAuthenticatorInfo](#queryauthenticatorinfo9). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------- | ----- | ----------------------- | -| owner | string | Yes | Owner of the authenticator. | -| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is the authenticator information obtained. Otherwise, **err** is an error object. | **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", { - onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); - } + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo", (err, data) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); }); ``` -### setAuthenticatorProperties9+ +### getAuthenticatorInfo(deprecated) + +getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> -setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callback: AuthenticatorCallback): void; +Obtains the authenticator information of an app. This API uses a promise to return the result. -Sets authenticator properties. 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 [queryAuthenticatorInfo](#queryauthenticatorinfo9-1). **System capability**: SystemCapability.Account.AppAccount **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------- | ----- | ----------------------- | -| owner | string | Yes | Owner of the authenticator. | -| options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| Name | Type | Mandatory | Description | +| ----- | ------ | ---- | ----------- | +| owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| + +**Return value** + +| Type | Description | +| -------------------------------- | --------------------- | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise used to return the authenticator information obtained.| **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - properties: {"prop1": "value1"} - }; - appAccountManager.setAuthenticatorProperties("com.example.ohos.accountjsdemo", options, { - onResult: (resultCode, result) => { - console.log("setAuthenticatorProperties onResult, resultCode:" + JSON.stringify(resultCode)); - console.log("setAuthenticatorProperties onResult, result:" + JSON.stringify(result)); - }, - onRequestRedirected: (request) => { - console.log("setAuthenticatorProperties onRequestRedirected, request:" + JSON.stringify(request)); - } + let appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.accountjsdemo").then((data) => { + console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); }); ``` @@ -1979,19 +4505,35 @@ Defines app account information. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----------- | | owner | string | Yes | Owner of the app account. The value is the bundle name of the app.| -| name | string | Yes | Name of the app account. | +| name | string | Yes | Name of the target app account. | + +## AuthTokenInfo9+ + +Defines authorization token information. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| -------------------- | -------------- | ----- | ---------------- | +| authType9+ | string | Yes | Authentication type. | +| token9+ | string | Yes | Value of the authorization token. | +| account9+ | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| + +## OAuthTokenInfo(deprecated) -## OAuthTokenInfo8+ +Defines authorization token information. -Defines OAuth token information. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthTokenInfo](#authtokeninfo9). **System capability**: SystemCapability.Account.AppAccount | Name | Type | Mandatory | Description | | -------------------- | -------------- | ----- | ---------------- | | authType | string | Yes | Authentication type. | -| token | string | Yes | Value of the token. | -| account9+ | AppAccountInfo | No | Account information of the token.| +| token | string | Yes | Value of the authorization token. | +| account9+ | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| ## AuthenticatorInfo8+ @@ -2005,9 +4547,41 @@ Defines OAuth authenticator information. | iconId | number | Yes | ID of the authenticator icon. | | labelId | number | Yes | ID of the authenticator label. | +## AuthResult9+ + +Defines the authentication result. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| account | [AppAccountInfo](#appaccountinfo) | No | Account information of the authorization token.| +| tokenInfo | [AuthTokenInfo](#authtokeninfo9) | No | Token information. | + +## CreateAccountOptions9+ + +Defines the options for creating an app account. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| customData | {[key: string]: string} | No | Custom data.| + +## CreateAccountImplicitlyOptions9+ + +Defines the options for implicitly creating an app account. + +**System capability**: SystemCapability.Account.AppAccount + +| Name | Type | Mandatory | Description | +| ------- | ------ | ---- | ---------- | +| requiredLabels | Array<string> | No | Labels required.| +| authType | string | No | Authentication type.| +| parameters | {[key: string]: Object} | No | Customized parameters.| ## SelectAccountsOptions9+ -Represents the options for selecting accounts. +Defines the options for selecting accounts. **System capability**: SystemCapability.Account.AppAccount @@ -2027,7 +4601,7 @@ Represents the options for verifying the user credential. | -------------- | ---------------------- | ----- | -------------- | | credentialType | string | No | Type of the credential to verify. | | credential | string | No | Credential value. | -| parameters | {[key:string]: Object} | No | Customized parameters.| +| parameters | {[key: string]: Object} | No | Customized parameters.| ## SetPropertiesOptions9+ @@ -2038,8 +4612,8 @@ Represents the options for setting authenticator properties. | Name | Type | Mandatory | Description | | ---------- | ---------------------- | ----- | -------------- | -| properties | {[key:string]: Object} | No | Authenticator properties. | -| parameters | {[key:string]: Object} | No | Customized parameters.| +| properties | {[key: string]: Object} | No | Authenticator properties. | +| parameters | {[key: string]: Object} | No | Customized parameters.| ## Constants8+ @@ -2047,12 +4621,16 @@ Enumerates the constants. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | +| Name | Value | Description | | -------------------------------- | ---------------------- | ----------------------- | -| ACTION_ADD_ACCOUNT_IMPLICITLY | "addAccountImplicitly" | Operation of adding an account implicitly. | -| ACTION_AUTHENTICATE | "authenticate" | Authentication operation. | -| KEY_NAME | "name" | App account name. | -| KEY_OWNER | "owner" | Owner of an app account.| +| ACTION_ADD_ACCOUNT_IMPLICITLY(deprecated) | "addAccountImplicitly" | Operation of adding an account implicitly. | +| ACTION_AUTHENTICATE(deprecated) | "authenticate" | Authentication operation. | +| ACTION_CREATE_ACCOUNT_IMPLICITLY9+ | "createAccountImplicitly" | Operation of creating an account implicitly. | +| ACTION_AUTH9+ | "auth" | Authentication operation. | +| ACTION_VERIFY_CREDENTIAL9+ | "verifyCredential" | Operation of verifying credentials. | +| ACTION_SET_AUTHENTICATOR_PROPERTIES9+ | "setAuthenticatorProperties" | Operation of setting authenticator properties. | +| KEY_NAME | "name" | Name of the app account. | +| KEY_OWNER | "owner" | Owner of the app account.| | KEY_TOKEN | "token" | Token. | | KEY_ACTION | "action" | Operation. | | KEY_AUTH_TYPE | "authType" | Authentication type. | @@ -2069,7 +4647,7 @@ Enumerates the result codes. **System capability**: SystemCapability.Account.AppAccount -| Name | Default Value | Description | +| Name | Value | Description | | ----------------------------------- | ----- | ------------ | | SUCCESS | 0 | The operation is successful. | | ERROR_ACCOUNT_NOT_EXIST | 10001 | The app account does not exist. | @@ -2085,16 +4663,122 @@ Enumerates the result codes. | ERROR_OAUTH_SERVICE_EXCEPTION | 10011 | The OAuth service is abnormal. | | ERROR_OAUTH_SESSION_NOT_EXIST | 10012 | The session to be authenticated does not exist. | | ERROR_OAUTH_TIMEOUT | 10013 | The authentication timed out. | -| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The OAuth token does not exist.| +| ERROR_OAUTH_TOKEN_NOT_EXIST | 10014 | The authorization token does not exist.| | ERROR_OAUTH_TOKEN_TOO_MANY | 10015 | The number of OAuth tokens reaches the limit. | | ERROR_OAUTH_UNSUPPORT_ACTION | 10016 | The authentication operation is not supported. | | ERROR_OAUTH_UNSUPPORT_AUTH_TYPE | 10017 | The authentication type is not supported. | | ERROR_PERMISSION_DENIED | 10018 | The required permission is missing. | -## AuthenticatorCallback8+ +## AuthCallback9+ + +Implements authenticator callbacks. + +### onResult9+ + +onResult: (code: number, result?: AuthResult) => void + +Called to return the result of an authentication request. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | -------------------- | ---- | ------ | +| code | number | Yes | Authentication result code.| +| result | [AuthResult](#authresult9) | No | Authentication result. | + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + var sessionId = "1234"; + appAccountManager.getAuthCallback(sessionId).then((callback) => { + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + }).catch((err) => { + console.log("getAuthCallback err: " + JSON.stringify(err)); + }); + ``` + +### onRequestRedirected9+ + +onRequestRedirected: (request: Want) => void + +Called to redirect a request. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------- | ---- | ---- | ---------- | +| request | Want | Yes | Request to be redirected.| + +**Example** + + ```js + class MyAuthenticator extends account_appAccount.Authenticator { + createAccountImplicitly(options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", + }); + } + + auth(name, authType, options, callback) { + var result = { + accountInfo: { + name: "Lisi", + owner: "com.example.accountjsdemo", + }, + tokenInfo: { + token: "xxxxxx", + authType: "getSocialData" + } + }; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } + } + ``` + +### onRequestContinued9+ + +onRequestContinued?: () => void + +Called to continue to process the request. + +**System capability**: SystemCapability.Account.AppAccount + +**Example** + + ```js + let appAccountManager = account_appAccount.createAppAccountManager(); + var sessionId = "1234"; + appAccountManager.getAuthCallback(sessionId).then((callback) => { + callback.onRequestContinued(); + }).catch((err) => { + console.log("getAuthCallback err: " + JSON.stringify(err)); + }); + ``` + +## AuthenticatorCallback(deprecated) Provides OAuth authenticator callbacks. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthCallback](#authcallback9). + ### onResult8+ onResult: (code: number, result: {[key: string]: any}) => void @@ -2113,11 +4797,11 @@ Called to return the result of an authentication request. **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { var result = {[account_appAccount.Constants.KEY_NAME]: "LiSi", - [account_appAccount.Constants.KEY_OWNER]: "com.example.ohos.accountjsdemo", + [account_appAccount.Constants.KEY_OWNER]: "com.example.accountjsdemo", [account_appAccount.Constants.KEY_AUTH_TYPE]: "getSocialData", [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; callback.onResult(account_appAccount.ResultCode.SUCCESS, result); @@ -2146,8 +4830,8 @@ Called to redirect a request. class MyAuthenticator extends account_appAccount.Authenticator { addAccountImplicitly(authType, callerBundleName, options, callback) { callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.LoginAbility", + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", }); } @@ -2171,7 +4855,7 @@ Called to continue to process the request. **Example** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); + let appAccountManager = account_appAccount.createAppAccountManager(); var sessionId = "1234"; appAccountManager.getAuthenticatorCallback(sessionId).then((callback) => { callback.onRequestContinued(); @@ -2184,11 +4868,30 @@ Called to continue to process the request. Provides APIs to operate the authenticator. -### addAccountImplicitly8+ +### createAccountImplicitly9+ + +createAccountImplicitly(options: CreateAccountImplicitlyOptions, callback: AuthCallback): void + +Creates an app account implicitly based on the specified account owner. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | Yes | Options for implicitly creating the account. | +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| + +### addAccountImplicitlydeprecated addAccountImplicitly(authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Implicitly adds an app account based on the specified authentication type and options. This API uses an asynchronous callback to return the result. +Adds an app account implicitly based on the specified authentication type and options. 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 [createAccountImplicitly](#createaccountimplicitly9-2). **System capability**: SystemCapability.Account.AppAccount @@ -2199,13 +4902,35 @@ Implicitly adds an app account based on the specified authentication type and op | authType | string | Yes | Authentication type. | | callerBundleName | string | Yes | Bundle name of the authentication requester. | | options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.| +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Authenticator callback invoked to return the authentication result.| + +### auth9+ + +auth(name: string, authType: string, options: {[key:string]: Object}, callback: AuthCallback): void + +Authenticates an app account to obtain the authorization token. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.AppAccount + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------------- | --------------------- | ---- | --------------- | +| name | string | Yes | Name of the target app account. | +| authType | string | Yes | Authentication type. | +| callerBundleName | string | Yes | Authentication type. | +| options | {[key: string]: Object} | Yes | Options for the authentication. | +| callback | [AuthCallback](#authcallback9) | Yes | Callback invoked to return the result.| -### authenticate8+ +### authenticatedeprecated authenticate(name: string, authType: string, callerBundleName: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void -Authenticates an app account to obtain the OAuth token. This API uses an asynchronous callback to return the result. +Authenticates an app account to obtain the authorization token. 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 [auth](#auth9-2). **System capability**: SystemCapability.Account.AppAccount @@ -2217,11 +4942,11 @@ Authenticates an app account to obtain the OAuth token. This API uses an asynchr | authType | string | Yes | Authentication type. | | callerBundleName | string | Yes | Bundle name of the authentication requester. | | options | {[key: string]: any} | Yes | Options for the authentication. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the authentication result.| +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | Yes | Authenticator callback invoked to return the authentication result.| ### verifyCredential9+ -verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; +verifyCredential(name: string, options: VerifyCredentialOptions, callback: AuthCallback): void; Verifies the credential of an app account. This API uses an asynchronous callback to return the result. @@ -2233,13 +4958,13 @@ Verifies the credential of an app account. This API uses an asynchronous callbac | ---------------- | --------------------- | ---- | --------------- | | name | string | Yes | Name of the target app account. | | options | [VerifyCredentialOptions](#verifycredentialoptions9) | Yes | Options for credential verification. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the verification result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the verification result.| ### setProperties9+ -setProperties(options: SetPropertiesOptions, callback: AuthenticatorCallback): void; +setProperties(options: SetPropertiesOptions, callback: AuthCallback): void; -Sets authenticator properties. This API uses an asynchronous callback to return the result. +Sets the authenticator properties. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Account.AppAccount @@ -2248,11 +4973,11 @@ Sets authenticator properties. This API uses an asynchronous callback to return | Name | Type | Mandatory | Description | | ---------------- | --------------------- | ---- | --------------- | | options | [SetPropertiesOptions](#setpropertiesoptions9) | Yes | Authenticator properties to set. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| ### checkAccountLabels9+ -checkAccountLabels(name: string, labels: Array<string>, callback: AuthenticatorCallback): void; +checkAccountLabels(name: string, labels: Array<string>, callback: AuthCallback): void; Checks the account labels. This API uses an asynchronous callback to return the result. @@ -2264,11 +4989,11 @@ Checks the account labels. This API uses an asynchronous callback to return the | ---------------- | --------------------- | ---- | --------------- | | name | string | Yes | Name of the target app account. | | labels | Array<string> | Yes | Labels to check. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the check result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the check result.| ### isAccountRemovable9+ -isAccountRemovable(name: string, callback: AuthenticatorCallback): void; +isAccountRemovable(name: string, callback: AuthCallback): void; Checks whether an app account can be deleted. This API uses an asynchronous callback to return the result. @@ -2279,7 +5004,7 @@ Checks whether an app account can be deleted. This API uses an asynchronous call | Name | Type | Mandatory | Description | | ---------------- | --------------------- | ---- | --------------- | | name | string | Yes | Name of the target app account. | -| callback | [AuthenticatorCallback](#authenticatorcallback8) | Yes | Authenticator callback invoked to return the result.| +| callback | [AuthCallback](#authcallback9) | Yes | Authenticator callback invoked to return the result.| ### getRemoteObject9+ @@ -2293,49 +5018,49 @@ Obtains the remote object of an authenticator. This API cannot be overloaded. ```js class MyAuthenticator extends account_appAccount.Authenticator { - addAccountImplicitly(authType, callerBundleName, options, callback) { - callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.LoginAbility", - }); - } + addAccountImplicitly(authType, callerBundleName, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.LoginAbility", + }); + } - authenticate(name, authType, callerBundleName, options, callback) { - var result = {[account_appAccount.Constants.KEY_NAME]: name, - [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, - [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } + authenticate(name, authType, callerBundleName, options, callback) { + var result = {[account_appAccount.Constants.KEY_NAME]: name, + [account_appAccount.Constants.KEY_AUTH_TYPE]: authType, + [account_appAccount.Constants.KEY_TOKEN]: "xxxxxx"}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } - verifyCredential(name, options, callback) { - callback.onRequestRedirected({ - bundleName: "com.example.ohos.accountjsdemo", - abilityName: "com.example.ohos.accountjsdemo.VerifyAbility", - parameters: { - name: name - } - }); - } + verifyCredential(name, options, callback) { + callback.onRequestRedirected({ + bundleName: "com.example.accountjsdemo", + abilityName: "com.example.accountjsdemo.VerifyAbility", + parameters: { + name: name + } + }); + } - setProperties(options, callback) { - callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); - } + setProperties(options, callback) { + callback.onResult(account_appAccount.ResultCode.SUCCESS, {}); + } - checkAccountLabels(name, labels, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } - - isAccountRemovable(name, callback) { - var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; - callback.onResult(account_appAccount.ResultCode.SUCCESS, result); - } + checkAccountLabels(name, labels, callback) { + var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: false}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } + + isAccountRemovable(name, callback) { + var result = {[account_appAccount.Constants.KEY_BOOLEAN_RESULT]: true}; + callback.onResult(account_appAccount.ResultCode.SUCCESS, result); + } } var authenticator = null; export default { - onConnect(want) { - authenticator = new MyAuthenticator(); - return authenticator.getRemoteObject(); - } + onConnect(want) { + authenticator = new MyAuthenticator(); + return authenticator.getRemoteObject(); + } } ``` diff --git a/en/application-dev/reference/apis/js-apis-appControl.md b/en/application-dev/reference/apis/js-apis-appControl.md index 50d8a59fdcbc6b3138afa2679c8ec10700e6ccb1..06b334d58cad8e7dd26a45c0344cfa48e1fdf0d6 100644 --- a/en/application-dev/reference/apis/js-apis-appControl.md +++ b/en/application-dev/reference/apis/js-apis-appControl.md @@ -1,4 +1,4 @@ -# appControl +# @ohos.bundle.appControl (appControl) The **appControl** module provides APIs for setting, obtaining, and deleting the disposed status of an application. An application in the disposed state is forbidden to run. When a user clicks the application icon on the home screen, the corresponding page is displayed based on the disposal intent. @@ -30,7 +30,7 @@ Sets the disposed status for an application. This API uses a promise to return t | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | disposedWant | Want | Yes| Disposal intent of the application.| **Return value** @@ -45,7 +45,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified appId was not found. | +| 17700005 | The specified app ID is not found. | **Example** @@ -81,7 +81,7 @@ Sets the disposed status for an application. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | ----------- | ------------------------------- | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | disposedWant | Want | Yes| Disposal intent of the application.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| @@ -91,7 +91,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified appId was not found. | +| 17700005 | The specified app ID is not found. | **Example** @@ -128,7 +128,7 @@ Obtains the disposed status of an application. This API uses a promise to return | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | **Return value** @@ -142,7 +142,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified appId was not found. | +| 17700005 | The specified app ID is not found. | **Example** @@ -177,7 +177,7 @@ Obtains the disposed status of an application. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the disposed status obtained; otherwise, **err** is an error object. | **Error codes** @@ -186,7 +186,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified appId was not found. | +| 17700005 | The specified app ID is not found. | **Example** @@ -222,7 +222,7 @@ Deletes the disposed status for an application. This API uses a promise to retur | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | **Return value** @@ -236,7 +236,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified appId was not found. | +| 17700005 | The specified app ID is not found. | **Example** @@ -271,7 +271,7 @@ Deletes the disposed status for an application. This API uses an asynchronous ca | Name | Type | Mandatory | Description | | ----------- | ------ | ---- | --------------------------------------- | -| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | +| appId | string | Yes | ID of the target application.
**appId** is the unique identifier of an application and is determined by the bundle name and signature information of the application. For details about how to obtain **appId**, see [Obtaining appId of an Application](#obtaining-appid-of-an-application). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** @@ -280,7 +280,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | ------ | -------------------------------------- | -| 17700005 | The specified appId was not found. | +| 17700005 | The specified app ID is not found. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md index a78f8cc320a4d081f356145d8ed4c51907a025ba..a47e3e8908f69f5515beab95cea6f74351719a77 100644 --- a/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @@ -1,12 +1,10 @@ -# Accessibility Extension Ability +# @ohos.application.AccessibilityExtensionAbility -The **AccessibilityExtensionAbility** module is based on the ExtensionAbility framework and provides the **AccessibilityExtensionAbility**. +The **AccessibilityExtensionAbility** module provides accessibility extension capabilities based on the ExtensionAbility framework. ->**NOTE** +> **NOTE** > ->The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> ->The APIs of this module 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. ## Modules to Import @@ -18,9 +16,9 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens **System capability**: SystemCapability.BarrierFree.Accessibility.Core -| Name | Type | Readable | Writable | Description | +| Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------------------- | -| context | [AccessibilityExtensionContext](js-apis-accessibility-extension-context.md) | Yes | No | Context of the accessibility extension ability. | +| context | [AccessibilityExtensionContext](js-apis-inner-application-accessibilityExtensionContext.md) | Yes| No| Context of the accessibility extension ability.| ## AccessibilityEvent @@ -32,36 +30,10 @@ Defines an accessibility event. | Name | Type | Readable | Writable | Description | | --------- | ---------------------------------------- | ---- | ---- | ---------- | -| eventType | [EventType](js-apis-accessibility.md#eventtype) \| [WindowUpdateType](js-apis-accessibility.md#windowupdatetype) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | +| eventType | [accessibility.EventType](js-apis-accessibility.md#EventType) \| [accessibility.WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | Yes | No | Event type. | | target | AccessibilityElement | Yes | No | Target component where the event occurs.| | timeStamp | number | Yes | No | Timestamp of the event. | -## GesturePath - -Defines a gesture path. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -### Attributes - -| Name | Type | Readable | Writable | Description | -| ------------ | ---------------------------------------- | ---- | ---- | ------ | -| points | Array<[GesturePoint](gesturepoint)> | Yes | Yes | An array of gesture touch points. | -| durationTime | number | Yes | Yes | Total time consumed by the gesture.| - -## GesturePoint - -Defines a gesture touch point. - -**System capability**: SystemCapability.BarrierFree.Accessibility.Core - -### Attributes - -| Name | Type | Readable | Writable | Description | -| --------- | ------ | ---- | ---- | ------- | -| positionX | number | Yes | Yes | X-coordinate of the touch point.| -| positionY | number | Yes | Yes | Y-coordinate of the touch point.| - ## GestureType Enumerates gesture types. @@ -89,7 +61,7 @@ Enumerates gesture types. ## PageUpdateType -Enumerates the page refresh types. +Enumerates the page update types. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -106,27 +78,25 @@ Enumerates the touch guide event types. | Name | Description | | ---------- | ------------ | -| touchBegin | A touch starts in touch guide mode.| -| touchEnd | A touch ends in touch guide mode.| +| touchBegin | Start of touch in touch guide mode. | +| touchEnd | End of touch in touch guide mode. | ## AccessibilityExtensionAbility.onConnect onConnect(): void; -Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can initialize service logic. This API can be overridden as required. +Called when the **AccessibilityExtensionAbility** is enabled and connected to the system service. In this API, you can have the service logic initialized. This API can be overridden as required. **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - -None - **Example** ```ts -onConnect(): void { - console.log("AxExtensionAbility onConnect"); -} +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onConnect() { + console.log('AxExtensionAbility onConnect'); + } +}; ``` ## AccessibilityExtensionAbility.onDisconnect @@ -137,16 +107,14 @@ Called when the **AccessibilityExtensionAbility** is disabled and disconnected f **System capability**: SystemCapability.BarrierFree.Accessibility.Core -**Parameters** - -None - **Example** ```ts -onDisconnect(): void { - console.log("AxExtensionAbility onDisconnect"); -} +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onDisconnect() { + console.log('AxExtensionAbility onDisconnect'); + } +}; ``` ## AccessibilityExtensionAbility.onAccessibilityEvent @@ -166,19 +134,21 @@ Called when an event that matches the specified bundle and event type occurs. In **Example** ```ts -onAccessibilityEvent(event: AccessibilityEvent): void { - console.log("AxExtensionAbility onAccessibilityEvent"); - if (event.eventType == 'click') { - console.log("AxExtensionAbility onAccessibilityEvent: click"); +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onAccessibilityEvent(event) { + console.log('AxExtensionAbility onAccessibilityEvent'); + if (event.eventType == 'click') { + console.log('AxExtensionAbility onAccessibilityEvent: click'); + } } -} +}; ``` ## AccessibilityExtensionAbility.onKeyEvent -onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean; +onKeyEvent(keyEvent: KeyEvent): boolean; -Called when a physical key is pressed. In this API, you can determine whether to intercept the key event based on the service. +Called when a physical key is pressed. In this API, you can determine whether to intercept an event based on the service. **System capability**: SystemCapability.BarrierFree.Accessibility.Core @@ -191,12 +161,14 @@ Called when a physical key is pressed. In this API, you can determine whether to **Example** ```ts -onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean { - console.log("AxExtensionAbility onKeyEvent"); - if (keyEvent.keyCode == 22) { - console.log("AxExtensionAbility onKeyEvent: intercept 22"); - return true; +class MyAccessibilityExtensionAbility extends AccessibilityExtensionAbility { + onKeyEvent(keyEvent) { + console.log('AxExtensionAbility onKeyEvent'); + if (keyEvent.keyCode == 22) { + console.log('AxExtensionAbility onKeyEvent: intercept 22'); + return true; + } + return false; } - return false; -} +}; ``` 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 7798cdee3d2f71f54e7cc6937816cbb4c253a833..9ecffc326e125b6e7dbe0ecd3cf03bfc3d2fa7dd 100644 --- a/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-DataShareExtensionAbility.md @@ -1,6 +1,6 @@ -# Data Share Extension Ability +# @ohos.application.DataShareExtensionAbility -The **DataShareExtensionAbility** module provides Extension abilities for data share services. +The **DataShareExtensionAbility** module provides data share services based on the Extension ability. >**NOTE** > @@ -17,13 +17,34 @@ The **DataShareExtensionAbility** module provides Extension abilities for data s import DataShareExtensionAbility from '@ohos.application.DataShareExtensionAbility' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** + +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## Attributes **System capability**: SystemCapability.DistributedDataManager.DataShare.Provider -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ExtensionContext](js-apis-extension-context.md) | Yes| No|Context of the DataShare Extension ability.| +| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes| No|Context of the DataShare Extension ability.| ## onCreate @@ -37,13 +58,13 @@ Called by the server to initialize service logic when the DataShare client conne | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| want | [Want](js-apis-application-Want.md#want) | Yes | **Want** information, including the ability name and bundle name.| +| want | [Want](js-apis-application-want.md#want) | Yes | **Want** information, including the ability name and bundle name.| | callback | AsyncCallback<void> | Yes| Callback that returns no value.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -56,7 +77,7 @@ export default class DataShareExtAbility extends DataShareExtensionAbility { onCreate(want, callback) { rdb.getRdbStore(this.context, { name: DB_NAME - }, 1, function (err, data) { + }, function (err, data) { console.log('getRdbStore done, data : ' + data); rdbStore = data; rdbStore.executeSql(DDL_TBL_CREATE, [], function (err) { @@ -83,13 +104,13 @@ Inserts data into the database. This API can be overridden as required. | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri |string | Yes | URI of the data to insert.| -| valueBucket |[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| Data to insert.| +| valueBucket |[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes| Data to insert.| | callback |AsyncCallback<number> | Yes| Callback invoked to return the index of the data inserted.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -127,14 +148,14 @@ Updates data in the database. This API can be overridden as required. | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri | string | Yes | URI of the data to update.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.| -| valueBucket | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes| New data.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for updating data.| +| valueBucket | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes| New data.| | callback | AsyncCallback<number> | Yes| Callback invoked to return the number of updated data records.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -170,13 +191,13 @@ Deletes data from the database. This API can be overridden as required. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ---------------------------------- | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for deleting data. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of data records deleted.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -212,14 +233,14 @@ Queries data from the database. This API can be overridden as required. | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | | uri | string | Yes | URI of the data to query.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria for querying data.| | columns | Array<string> | Yes| Columns to query. If this parameter is empty, all columns will be queried.| | callback | AsyncCallback<Object> | Yes| Callback invoked to return the result set.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; @@ -255,16 +276,16 @@ Batch inserts data into the database. This API is called by the server and can b **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------ | ------------------------------------------------------------ | ---- | -------------------------------- | | uri | string | Yes | URI of the data to insert. | -| valueBuckets | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| valueBuckets | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the number of inserted data records.| **Example** ```ts -import rdb from '@ohos.data.rdb'; +import rdb from '@ohos.data.relationalStore'; let DB_NAME = "DB00.db"; let TBL_NAME = "TBL00"; diff --git a/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md b/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md index f0d75fc57deed25160bbb080ef1565a45a94679d..d4c25269235da3b95e4f230c084d92c1df047269 100644 --- a/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md @@ -1,16 +1,16 @@ -# EnvironmentCallback +# @ohos.application.EnvironmentCallback (EnvironmentCallback) -The **EnvironmentCallback** module provides the **onConfigurationUpdated** API for the application context to listen for system environment changes. +The **EnvironmentCallback** module provides APIs, such as **onConfigurationUpdated** and **onMemoryLevel**, for the application context to listen for system environment changes. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.EnvironmentCallback](js-apis-app-ability-environmentCallback.md) instead. 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. ## Modules to Import -```js +```ts import EnvironmentCallback from "@ohos.application.EnvironmentCallback"; ``` @@ -27,24 +27,40 @@ Called when the system environment changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| **Configuration** object after the change.| + | config | [Configuration](js-apis-application-configuration.md) | Yes| **Configuration** object after the change.| + +## EnvironmentCallback.onMemoryLevel + +onMemoryLevel(level: number): void; + +Called when the system memory level changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| New memory level.| **Example** - - ```js -import AbilityStage from "@ohos.application.AbilityStage"; + ```ts +import UIAbility from '@ohos.app.ability.UIAbility'; var callbackId; -export default class MyAbilityStage extends AbilityStage { +export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbilityStage onCreate") + console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ console.log("onConfigurationUpdated config:" + JSON.stringify(config)); }, + onMemoryLevel(level){ + console.log("onMemoryLevel level:" + level); + } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; diff --git a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md deleted file mode 100644 index 45024751e4460258a696e7f7e883e84fb93d73c2..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ /dev/null @@ -1,40 +0,0 @@ -# MissionSnapshot - -The **MissionSnapshot** module provides the mission snapshot information of an ability. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module are system APIs and cannot be called by third-party applications. - -## Usage - -The mission snapshot information can be obtained by using **getMissionSnapShot** in **missionManager**. - -```js -import ElementName from '@ohos.bundle'; -import image from '@ohos.multimedia.image'; -import missionManager from '@ohos.application.missionManager'; - -missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; - - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) -}) -``` -## MissionSnapshot - -Describes the mission snapshot. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| ability | ElementName | Yes| Yes| Information that matches an ability.| -| snapshot | [image.PixelMap](js-apis-image.md) | Yes| Yes| Snapshot of the mission.| diff --git a/en/application-dev/reference/apis/js-apis-application-StartOptions.md b/en/application-dev/reference/apis/js-apis-application-StartOptions.md index 39f44f65437b6b91ce457228fa12153d10aed3e6..7634b276495d98e18bc7ec966f3483e526dd3ba3 100644 --- a/en/application-dev/reference/apis/js-apis-application-StartOptions.md +++ b/en/application-dev/reference/apis/js-apis-application-StartOptions.md @@ -1,15 +1,15 @@ -# StartOptions +# @ohos.application.StartOptions (StartOptions) The **StartOptions** module implements ability startup options. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.StartOptions](js-apis-app-ability-startOptions.md) instead. 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. ## Modules to Import -``` +```ts import StartOptions from '@ohos.application.StartOptions'; ``` @@ -17,7 +17,7 @@ import StartOptions from '@ohos.application.StartOptions'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Readable| Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -------- | -------- | -| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | Yes| No| number | No| Window mode.| -| displayId | Yes| No| number | No| Display ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| [windowMode](js-apis-application-abilityConstant.md#abilityconstantwindowmode) | number | No| Window mode.| +| displayId | number | No| Display ID.| diff --git a/en/application-dev/reference/apis/js-apis-application-Want.md b/en/application-dev/reference/apis/js-apis-application-Want.md index 9275473cd14727d8a3e8f16327d2020a1adefb4d..44cc01a00c5057488b45a5a6a38cc02adbf1cbc2 100644 --- a/en/application-dev/reference/apis/js-apis-application-Want.md +++ b/en/application-dev/reference/apis/js-apis-application-Want.md @@ -1,14 +1,14 @@ -# Want +# @ohos.application.Want (Want) -The **Want** module provides the basic communication component of the system. +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of **startAbility()** to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. > **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [Want](js-apis-app-ability-want.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```ts import Want from '@ohos.application.Want'; ``` @@ -16,28 +16,28 @@ import Want from '@ohos.application.Want'; **System capability**: SystemCapability.Ability.AbilityBase -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| deviceId | Read only | string | No | ID of the device running the ability. | -| bundleName | Read only | string | No | Bundle name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability.| -| abilityName | Read only | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| -| uri | Read only | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| -| type | Read only | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | -| flags | Read only | number | No | How the **Want** object will be handled. For details, see [flags](js-apis-featureAbility.md#flags).| -| action | Read only | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. | -| parameters | Read only | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | -| entities | Read only | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit **Want** and is used to filter ability types. | -| moduleName9+ | Read only | string | No | Module to which the ability belongs.| +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| bundleName | string | No | Bundle name.| +| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| +| uri | string | No | URI information to match. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | +| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantConstant.Flags).| +| action | string | No | Action to take, such as viewing and sharing application details. In implicit **Want**, you can define this attribute and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantConstant.Action). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](application-models/explicit-implicit-want-mappings.md). | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the ability. It is a supplement to the **action** field for implicit Want. and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantConstant.Entity). | +| moduleName9+ | string | No | Module to which the ability belongs.| **Example** -- Basic usage +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). - ``` js - var want = { + ```ts + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", "moduleName": "entry" // moduleName is optional. }; this.context.startAbility(want, (error) => { @@ -46,13 +46,13 @@ import Want from '@ohos.application.Want'; }) ``` -- Data is transferred through user-defined fields. The following data types are supported: +- Data is transferred through user-defined fields. The following data types are supported (called in a UIAbility object, where context in the example is the context object of the UIAbility): * String ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForString: "str", }, @@ -61,8 +61,8 @@ import Want from '@ohos.application.Want'; * Number ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForInt: 100, keyForDouble: 99.99, @@ -72,8 +72,8 @@ import Want from '@ohos.application.Want'; * Boolean ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForBool: true, }, @@ -82,8 +82,8 @@ import Want from '@ohos.application.Want'; * Object ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForObject: { keyForObjectString: "str", @@ -97,8 +97,8 @@ import Want from '@ohos.application.Want'; * Array ```ts let want = { - bundleName: "com.example.demo", - abilityName: "com.example.demo.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", parameters: { keyForArrayString: ["str1", "str2", "str3"], keyForArrayInt: [100, 200, 300, 400], @@ -110,16 +110,16 @@ import Want from '@ohos.application.Want'; * File descriptor (FD) ```ts import fileio from '@ohos.fileio'; - var fd; + let fd; try { fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); } catch(e) { console.log("openSync fail:" + JSON.stringify(e)); } - var want = { + let want = { "deviceId": "", // An empty deviceId indicates the local device. - "bundleName": "com.extreme.test", - "abilityName": "MainAbility", + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", "moduleName": "entry", // moduleName is optional. "parameters": { "keyFd":{"type":"FD", "value":fd} @@ -131,4 +131,6 @@ import Want from '@ohos.application.Want'; }) ``` +- For more details and examples, see [Want](../../application-models/want-overview.md). + diff --git a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md index 1fa16906d34877c7e7dce4638b472b0c539b8921..bd6d74bbcbbdb4b0d29ccad209b012a11f44c9af 100644 --- a/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-WindowExtensionAbility.md @@ -1,4 +1,5 @@ -# Window Extension Ability +# @ohos.application.WindowExtensionAbility (WindowExtensionAbility) + **WindowExtensionAbility** inherits from **ExtensionAbility**. The content in a **WindowExtensionAbility** object can be displayed as an ability component in other application windows. > **NOTE** @@ -21,7 +22,7 @@ import WindowExtensionAbility from '@ohos.application.WindowExtensionAbility'; | Name | Type| Readable| Writable| Description | | --------- | -------- | ---- | ---- | ------------------------- | -| context | [ExtensionContext](js-apis-extension-context.md) | Yes | No | Context of an Extension ability. | +| context | [ExtensionContext](js-apis-inner-application-extensionContext.md) | Yes | No | Context of an Extension ability. | ## WindowExtensionAbility.onConnect @@ -35,7 +36,7 @@ Called when this Window Extension ability is connected to an ability for the fir | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| +| want | [Want](js-apis-application-want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| **Example** @@ -61,7 +62,7 @@ Called when this Window Extension ability is disconnected from all connected abi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| +| want | [Want](js-apis-application-want.md) | Yes| Information related to this Window Extension ability, including the ability name and bundle name.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-application-ability.md b/en/application-dev/reference/apis/js-apis-application-ability.md index 7ba7d62c053ea5eb7f03e6264f959c5770e196ee..efba928564b2c9aa34e35b2af7485674ea99274d 100644 --- a/en/application-dev/reference/apis/js-apis-application-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-ability.md @@ -1,4 +1,4 @@ -# Ability +# @ohos.application.Ability (Ability) The **Ability** module manages the ability lifecycle and context, such as creating and destroying an ability, and dumping client information. @@ -14,8 +14,8 @@ This module provides the following common ability-related functions: ## Modules to Import -``` -import Ability from '@ohos.application.Ability'; +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; ``` ## Attributes @@ -24,9 +24,9 @@ import Ability from '@ohos.application.Ability'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [AbilityContext](js-apis-ability-context.md) | Yes| No| Context of an ability.| -| launchWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters for starting the ability.| -| lastRequestWant | [Want](js-apis-application-Want.md) | Yes| No| Parameters used when the ability was started last time.| +| context | [UIAbilityContext](js-apis-inner-application-uiAbilityContext.md) | Yes| No| Context of an ability.| +| launchWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters for starting the ability.| +| lastRequestWant | [Want](js-apis-app-ability-want.md) | Yes| No| Parameters used when the ability was started last time.| | callee | [Callee](#callee) | Yes| No| Object that invokes the stub service.| ## Ability.onCreate @@ -41,13 +41,13 @@ Called to initialize the service logic when an ability is created. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this ability, including the ability name and bundle name.| + | want | [Want](js-apis-app-ability-want.md) | Yes| Information related to this ability, including the ability name and bundle name.| | param | AbilityConstant.LaunchParam | Yes| Parameters for starting the ability, and the reason for the last abnormal exit.| **Example** ```ts - class myAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, param) { console.log('onCreate, want:' + want.abilityName); } @@ -67,7 +67,7 @@ Called when a **WindowStage** is created for this ability. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** @@ -111,7 +111,7 @@ Called when the **WindowStage** is restored during the migration of this ability | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | windowStage | window.WindowStage | Yes| **WindowStage** information.| + | windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** information.| **Example** @@ -219,48 +219,48 @@ Called to save data during the ability migration preparation process. onNewWant(want: Want, launchParams: AbilityConstant.LaunchParam): void; -Called when the ability startup mode is set to singleton. +Called when a new Want is passed in and this UIAbility is started again. **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want parameters, such as the ability name and bundle name.| - | launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information, such as the ability name and bundle name.| +| launchParams | AbilityConstant.LaunchParam | Yes| Reason for the ability startup and the last abnormal exit.| **Example** ```ts class myAbility extends Ability { - onNewWant(want) { + onNewWant(want, launchParams) { console.log('onNewWant, want:' + want.abilityName); + console.log('onNewWant, launchParams:' + JSON.stringify(launchParams)); } } ``` - ## Ability.onConfigurationUpdated onConfigurationUpdated(config: Configuration): void; -Called when the configuration of the environment where the ability is running is updated. +Called when the global configuration is updated. -**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore +**System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| + | config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| **Example** ```ts class myAbility extends Ability { onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + console.log('onConfigurationUpdated, language:' + config.language); } } ``` @@ -314,12 +314,11 @@ Called when the system has decided to adjust the memory level. For example, this } ``` - ## Ability.onSaveState onSaveState(reason: AbilityConstant.StateType, wantParam : {[key: string]: any}): AbilityConstant.OnSaveResult; -Called when the framework saves the ability state in the case of an application fault if automatic saving is enabled. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). +Called when the framework automatically saves the ability state in the case of an application fault. This API is used together with [appRecovery](js-apis-app-ability-appRecovery.md). **System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore @@ -338,7 +337,7 @@ Called when the framework saves the ability state in the case of an application **Example** - ```js + ```ts import AbilityConstant from '@ohos.application.AbilityConstant' class myAbility extends Ability { @@ -390,8 +389,9 @@ Sends sequenceable data to the target ability. **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; - class MyMessageAble{ // Custom sequenceable data structure + import UIAbility from '@ohos.app.ability.UIAbility'; + + class MyMessageAble{ // Custom sequenceable data structure. name:"" str:"" num: 1 @@ -414,11 +414,11 @@ Sends sequenceable data to the target ability. }; var method = 'call_Function'; // Notification message string negotiated by the two abilities var caller; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -474,7 +474,8 @@ Sends sequenceable data to the target ability and obtains the sequenceable data **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; + class MyMessageAble{ name:"" str:"" @@ -498,11 +499,11 @@ Sends sequenceable data to the target ability and obtains the sequenceable data }; var method = 'call_Function'; var caller; - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -545,14 +546,17 @@ Releases the caller interface of the target ability. **Example** + ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var caller; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; @@ -570,10 +574,9 @@ Releases the caller interface of the target ability. } ``` +## Caller.onRelease -## Caller.on - - on(type: "release", callback: OnReleaseCallback): void; + onRelease(callback: OnReleaseCallBack): void; Registers a callback that is invoked when the stub on the target ability is disconnected. @@ -583,32 +586,25 @@ Registers a callback that is invoked when the stub on the target ability is disc | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is fixed at **release**.| | callback | OnReleaseCallBack | Yes| Callback used for the **onRelease** API.| -**Error codes** - -| ID| Error Message| -| ------- | -------------------------------- | -| 401 | Invalid input parameter. | -| 16200001 | Caller released. The caller has been released. | -| 16000050 | Internal Error. | - **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var caller; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onWindowStageCreate(windowStage) { this.context.startAbilityByCall({ bundleName: "com.example.myservice", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }).then((obj) => { caller = obj; try { - caller.on("release", (str) => { + caller.onRelease((str) => { console.log(' Caller OnRelease CallBack is called ' + str); }); } catch (error) { @@ -654,7 +650,7 @@ Registers a caller notification callback, which is invoked when the target abili **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; class MyMessageAble{ name:"" str:"" @@ -679,11 +675,11 @@ Registers a caller notification callback, which is invoked when the target abili var method = 'call_Function'; function funcCallBack(pdata) { console.log('Callee funcCallBack is called ' + pdata); - let msg = new MyMessageAble(0, ""); + let msg = new MyMessageAble("test", ""); pdata.readSequenceable(msg); - return new MyMessageAble(10, "Callee test"); + return new MyMessageAble("test1", "Callee test"); } - export default class MainAbility extends Ability { + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -722,9 +718,11 @@ Deregisters a caller notification callback, which is invoked when the target abi **Example** ```ts - import Ability from '@ohos.app.ability.UIAbility'; + import UIAbility from '@ohos.app.ability.UIAbility'; + var method = 'call_Function'; - export default class MainAbility extends Ability { + + export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { console.log('Callee onCreate is called'); try { @@ -737,7 +735,7 @@ Deregisters a caller notification callback, which is invoked when the target abi } ``` -## OnReleaseCallback +## OnReleaseCallBack (msg: string): void; @@ -747,7 +745,7 @@ Deregisters a caller notification callback, which is invoked when the target abi | -------- | -------- | -------- | -------- | -------- | | (msg: string) | function | Yes| No| Prototype of the listener function registered by the caller.| -## CalleeCallback +## CalleeCallBack (indata: rpc.MessageParcel): rpc.Sequenceable; @@ -756,5 +754,3 @@ Deregisters a caller notification callback, which is invoked when the target abi | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | (indata: rpc.MessageParcel) | rpc.Sequenceable | Yes| No| Prototype of the listener function registered by the callee.| - - \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md index 50e65757431e7df6b9bc784c6169da902a04bf5d..70d679e5f44e1089e91ff7377b687ded761e29e6 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityConstant.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityConstant.md @@ -1,17 +1,15 @@ -# AbilityConstant +# @ohos.application.AbilityConstant (AbilityConstant) -The **AbilityConstant** module provides ability launch parameters. - -The parameters include the initial launch reasons, reasons for the last exit, and ability continuation results. +The **AbilityConstant** module defines the ability-related enums, including the initial launch reasons, reasons for the last exit, ability continuation results, and window modes. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityConstant](js-apis-app-ability-abilityConstant.md) instead. 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. ## Modules to Import -```js +```ts import AbilityConstant from '@ohos.application.AbilityConstant'; ``` @@ -19,14 +17,14 @@ import AbilityConstant from '@ohos.application.AbilityConstant'; **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| launchReason | LaunchReason| Yes| Yes| Ability launch reason.| -| lastExitReason | LastExitReason | Yes| Yes| Reason for the last exit.| +| launchReason | [LaunchReason](#abilityconstantlaunchreason)| Yes| Yes| Ability launch reason.| +| lastExitReason | [LastExitReason](#abilityconstantlastexitreason) | Yes| Yes| Reason for the last exit.| ## AbilityConstant.LaunchReason -Enumerates ability launch reasons. +Enumerates the initial ability launch reasons. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -36,11 +34,12 @@ Enumerates ability launch reasons. | START_ABILITY | 1 | Ability startup.| | CALL | 2 | Call.| | CONTINUATION | 3 | Ability continuation.| +| APP_RECOVERY | 4 | Application recovery.| ## AbilityConstant.LastExitReason -Enumerates reasons for the last exit. +Enumerates the reasons for the last exit. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -53,7 +52,7 @@ Enumerates reasons for the last exit. ## AbilityConstant.OnContinueResult -Enumerates ability continuation results. +Enumerates the ability continuation results. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -88,3 +87,29 @@ Enumerates the memory levels. | MEMORY_LEVEL_MODERATE | 0 | Moderate memory usage. | | MEMORY_LEVEL_LOW | 1 | Low memory usage. | | MEMORY_LEVEL_CRITICAL | 2 | High memory usage. | + +## AbilityConstant.OnSaveResult + +Enumerates the result types for the operation of saving application data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| ALL_AGREE | 0 | Agreed to save the status.| +| CONTINUATION_REJECT | 1 | Rejected to save the status in continuation.| +| CONTINUATION_MISMATCH | 2 | Continuation mismatch.| +| RECOVERY_AGREE | 3 | Agreed to restore the saved status.| +| RECOVERY_REJECT | 4 | Rejected to restore the saved state.| +| ALL_REJECT | 5 | Rejected to save the status.| + +## AbilityConstant.StateType + +Enumerates the scenarios for saving application data. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Value | Description | +| ----------------------------- | ---- | ------------------------------------------------------------ | +| CONTINUATION | 0 | Saving the status in continuation.| +| APP_RECOVERY | 1 | Saving the status in application recovery.| diff --git a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md similarity index 72% rename from en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md rename to en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md index d30dce2a75e700019c9f44ce1c918a9574f3cea7..ae72afeca2e3214d00a785c0639793e8df47d715 100644 --- a/en/application-dev/reference/apis/js-apis-abilityDelegatorRegistry.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityDelegatorRegistry.md @@ -1,14 +1,14 @@ -# AbilityDelegatorRegistry +# @ohos.application.abilityDelegatorRegistry (AbilityDelegatorRegistry) The **AbilityDelegatorRegistry** module provides APIs for storing the global registers of the registered **AbilityDelegator** and **AbilityDelegatorArgs** objects. You can use the APIs to obtain the **AbilityDelegator** and **AbilityDelegatorArgs** objects of an application. > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityDelegatorRegistry](js-apis-app-ability-abilityDelegatorRegistry.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```js +```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' ``` @@ -38,18 +38,16 @@ Obtains the **AbilityDelegator** object of the application. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| +| [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) | [AbilityDelegator](js-apis-inner-application-abilityDelegator.md#AbilityDelegator) object, which can be used to schedule functions related to the test framework.| **Example** -```js +```ts var abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` - - ## AbilityDelegatorRegistry.getArguments getArguments(): AbilityDelegatorArgs @@ -62,11 +60,11 @@ Obtains the **AbilityDelegatorArgs** object of the application. | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters.| +| [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) | [AbilityDelegatorArgs](js-apis-inner-application-abilityDelegatorArgs.md#AbilityDelegatorArgs) object, which can be used to obtain test parameters.| **Example** -```js +```ts var args = AbilityDelegatorRegistry.getArguments(); console.info("getArguments bundleName:" + args.bundleName); console.info("getArguments testCaseNames:" + args.testCaseNames); diff --git a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md index 54264312fcc88ad0177473a7e4d256f566e6c2d2..040448220bb9da59779f0d449c43a59d8ab920bd 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @@ -1,16 +1,16 @@ -# AbilityLifecycleCallback +# @ohos.application.AbilityLifecycleCallback (AbilityLifecycleCallback) -The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. +The **AbilityLifecycleCallback** module provides callbacks, such as **onAbilityCreate**, **onWindowStageCreate**, and **onWindowStageDestroy**, to receive lifecycle state changes in the application context. These callbacks can be used as an input parameter of [registerAbilityLifecycleCallback](js-apis-inner-application-applicationContext.md#applicationcontextregisterabilitylifecyclecallback). > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) instead. 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. ## Modules to Import -```js +```ts import AbilityLifecycleCallback from "@ohos.application.AbilityLifecycleCallback"; ``` @@ -25,9 +25,9 @@ Called when an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onWindowStageCreate @@ -40,10 +40,10 @@ Called when the window stage of an ability is created. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageActive @@ -56,10 +56,10 @@ Called when the window stage of an ability gains focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageInactive @@ -72,10 +72,10 @@ Called when the window stage of an ability loses focus. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onWindowStageDestroy @@ -88,10 +88,10 @@ Called when the window stage of an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| - | windowStage | [WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| windowStage | [window.WindowStage](js-apis-window.md#windowstage9) | Yes| **WindowStage** object.| ## AbilityLifecycleCallback.onAbilityDestroy @@ -104,9 +104,9 @@ Called when an ability is destroyed. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityForeground @@ -119,9 +119,9 @@ Called when an ability is switched from the background to the foreground. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityBackground @@ -134,9 +134,9 @@ Called when an ability is switched from the foreground to the background. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| ## AbilityLifecycleCallback.onAbilityContinue @@ -149,57 +149,65 @@ Called when an ability is continued on another device. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| ability | [Ability](js-apis-application-ability.md#Ability) | Yes| **Ability** object.| **Example** - - - ```js - import AbilityStage from "@ohos.application.AbilityStage"; - - export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); - }, - onWindowStageCreate(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + +```ts +import AbilityStage from "@ohos.application.AbilityStage"; + +var lifecycleId; + +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let AbilityLifecycleCallback = { + onAbilityCreate(ability) { + console.log("onAbilityCreate ability:" + JSON.stringify(ability)); + }, + onWindowStageCreate(ability, windowStage) { + console.log("onWindowStageCreate ability:" + JSON.stringify(ability)); + console.log("onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); }, - onWindowStageActive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); + onWindowStageActive(ability, windowStage) { + console.log("onWindowStageActive ability:" + JSON.stringify(ability)); + console.log("onWindowStageActive windowStage:" + JSON.stringify(windowStage)); }, - onWindowStageInactive(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); + onWindowStageInactive(ability, windowStage) { + console.log("onWindowStageInactive ability:" + JSON.stringify(ability)); + console.log("onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); }, - onWindowStageDestroy(ability, windowStage){ - console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); - console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); + onWindowStageDestroy(ability, windowStage) { + console.log("onWindowStageDestroy ability:" + JSON.stringify(ability)); + console.log("onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); }, - onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); - }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); - }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); - }, - onAbilityContinue(ability){ - console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); - } - } - // 1. Obtain applicationContext through the context attribute. - let applicationContext = this.context.getApplicationContext(); - // 2. Use applicationContext to register a listener for the ability lifecycle in the application. - let lifecycleid = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); - console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleid)); - } - } - ``` + onAbilityDestroy(ability) { + console.log("onAbilityDestroy ability:" + JSON.stringify(ability)); + }, + onAbilityForeground(ability) { + console.log("onAbilityForeground ability:" + JSON.stringify(ability)); + }, + onAbilityBackground(ability) { + console.log("onAbilityBackground ability:" + JSON.stringify(ability)); + }, + onAbilityContinue(ability) { + console.log("onAbilityContinue ability:" + JSON.stringify(ability)); + } + } + // 1. Obtain applicationContext through the context attribute. + let applicationContext = this.context.getApplicationContext(); + // 2. Use applicationContext to register a listener for the ability lifecycle in the application. + lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); + console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); + } + + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityManager.md b/en/application-dev/reference/apis/js-apis-application-abilityManager.md index e1bf96bae511de4e1fb83d92df6ee05bdddbf990..e509a1b5d13a2d0d20b8d6dee4efee9487c5ee92 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityManager.md +++ b/en/application-dev/reference/apis/js-apis-application-abilityManager.md @@ -1,16 +1,16 @@ -# AbilityManager +# @ohos.application.abilityManager (AbilityManager) The **AbilityManager** module provides APIs for obtaining, adding, and modifying ability running information and state information. > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.abilityManager](js-apis-app-ability-abilityManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import -```js -import AbilityManager from '@ohos.application.abilityManager' +```ts +import abilityManager from '@ohos.application.abilityManager' ``` ## AbilityState @@ -26,8 +26,8 @@ Enumerates the ability states. | INITIAL | 0 | The ability is in the initial state.| | FOREGROUND | 9 | The ability is in the foreground state. | | BACKGROUND | 10 | The ability is in the background state. | -| FOREGROUNDING | 11 | The ability is in the foregrounding state. | -| BACKGROUNDING | 12 | The ability is in the backgrounding state. | +| FOREGROUNDING | 11 | The ability is in the state of being switched to the foreground. | +| BACKGROUNDING | 12 | The ability is in the state of being switched to the background. | ## updateConfiguration @@ -43,19 +43,17 @@ Updates the configuration. This API uses an asynchronous callback to return the | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | Configuration | Yes | New configuration.| +| config | [Configuration](js-apis-application-configuration.md) | Yes | New configuration.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - +```ts var config = { language: 'chinese' } -abilitymanager.updateConfiguration(config, () => { +abilityManager.updateConfiguration(config, () => { console.log('------------ updateConfiguration -----------'); }) ``` @@ -74,7 +72,7 @@ Updates the configuration. This API uses a promise to return the result. | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| config | Configuration | Yes | New configuration.| +| config | [Configuration](js-apis-application-configuration.md) | Yes | New configuration.| **Return value** @@ -84,14 +82,12 @@ Updates the configuration. This API uses a promise to return the result. **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - +```ts var config = { language: 'chinese' } -abilitymanager.updateConfiguration(config).then(() => { +abilityManager.updateConfiguration(config).then(() => { console.log('updateConfiguration success'); }).catch((err) => { console.log('updateConfiguration fail'); @@ -112,14 +108,12 @@ Obtains the ability running information. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getAbilityRunningInfos((err,data) => { +```ts +abilityManager.getAbilityRunningInfos((err,data) => { console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -138,14 +132,12 @@ Obtains the ability running information. This API uses a promise to return the r | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getAbilityRunningInfos().then((data) => { +```ts +abilityManager.getAbilityRunningInfos().then((data) => { console.log("getAbilityRunningInfos data: " + JSON.stringify(data)) }).catch((err) => { console.log("getAbilityRunningInfos err: " + err) @@ -167,16 +159,14 @@ Obtains the extension running information. This API uses an asynchronous callbac | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | | upperLimit | number | Yes| Maximum number of messages that can be obtained.| -| callback | AsyncCallback\> | Yes | Callback used to return the result. | +| callback | AsyncCallback\> | Yes | Callback used to return the result. | **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - +```ts var upperLimit = 0; -abilitymanager.getExtensionRunningInfos(upperLimit, (err,data) => { +abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -201,16 +191,14 @@ Obtains the extension running information. This API uses a promise to return the | Type | Description | | ---------------------------------------- | ------- | -| Promise\> | Promise used to return the result.| +| Promise\> | Promise used to return the result.| **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - +```ts var upperLimit = 0; -abilitymanager.getExtensionRunningInfos(upperLimit).then((data) => { +abilityManager.getExtensionRunningInfos(upperLimit).then((data) => { console.log("getAbilityRunningInfos data: " + JSON.stringify(data)); }).catch((err) => { console.log("getAbilityRunningInfos err: " + err); @@ -229,14 +217,12 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Name | Type | Mandatory | Description | | --------- | ---------------------------------------- | ---- | -------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the result. | **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getTopAbility((err,data) => { +```ts +abilityManager.getTopAbility((err,data) => { console.log("getTopAbility err: " + err + " data: " + JSON.stringify(data)); }); ``` @@ -253,14 +239,12 @@ Obtains the top ability, which is the ability that has the window focus. This AP | Type | Description | | ---------------------------------------- | ------- | -| Promise\| Promise used to return the result.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)>| Promise used to return the result.| **Example** -```js -import abilitymanager from '@ohos.application.abilityManager'; - -abilitymanager.getTopAbility().then((data) => { +```ts +abilityManager.getTopAbility().then((data) => { console.log("getTopAbility data: " + JSON.stringify(data)); }).catch((err) => { console.log("getTopAbility err: " + err); diff --git a/en/application-dev/reference/apis/js-apis-application-abilitystage.md b/en/application-dev/reference/apis/js-apis-application-abilitystage.md index d1c8592f97d4c8b8799d5773b391bb1798663219..1421dcd723028b9a7f052e76e2534f1ea7c4017a 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilitystage.md +++ b/en/application-dev/reference/apis/js-apis-application-abilitystage.md @@ -1,4 +1,4 @@ -# AbilityStage +# @ohos.application.AbilityStage (AbilityStage) **AbilityStage** is a runtime class for HAP files. @@ -6,12 +6,12 @@ The **AbilityStage** module notifies you of when you can perform HAP initializat > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported and deprecated since API version 9. You are advised to use [@ohos.app.ability.AbilityStage](js-apis-app-ability-abilityStage.md) instead. 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. ## Modules to Import -```js +```ts import AbilityStage from '@ohos.application.AbilityStage'; ``` @@ -25,7 +25,7 @@ Called when the application is created. **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onCreate() { console.log("MyAbilityStage.onCreate is called") @@ -38,25 +38,25 @@ Called when the application is created. onAcceptWant(want: Want): string; -Called when a specified ability is started. +Called when a UIAbility is started. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, such as the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target UIAbility, such as the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | string | Returns an ability ID. If this ability has been started, no new instance is created and the ability is placed at the top of the stack. Otherwise, a new instance is created and started.| +| Type| Description| +| -------- | -------- | +| string | Returns a UIAbility ID. If this UIAbility has been started, no new instance is created and the UIAbility is placed at the top of the stack. Otherwise, a new instance is created and started.| **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onAcceptWant(want) { console.log("MyAbilityStage.onAcceptWant called"); @@ -76,13 +76,13 @@ Called when the global configuration is updated. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| Callback invoked when the global configuration is updated. The global configuration indicates the configuration of the environment where the application is running and includes the language and color mode.| **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, language:' + config.language); @@ -100,13 +100,13 @@ Called when the system has decided to adjust the memory level. For example, this **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| **Example** - ```js + ```ts class MyAbilityStage extends AbilityStage { onMemoryLevel(level) { console.log('onMemoryLevel, level:' + JSON.stringify(level)); @@ -118,10 +118,10 @@ Called when the system has decided to adjust the memory level. For example, this context: AbilityStageContext; -Describes the configuration information about the context. +Defines the **Context** object of **AbilityStage**. **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Type | Description | -| ----------- | --------------------------- | ------------------------------------------------------------ | -| context | [AbilityStageContext](js-apis-abilitystagecontext.md) | Called when initialization is performed during ability startup.| +| Name | Type | Description | +| ------- | ------------------------------------------------------------ | -------------------------- | +| context | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | **Context** object of AbilityStage.| diff --git a/en/application-dev/reference/apis/js-apis-application-appManager.md b/en/application-dev/reference/apis/js-apis-application-appManager.md new file mode 100644 index 0000000000000000000000000000000000000000..591f5ec77a34ef2eb36979a00b9553241b33ddb3 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-appManager.md @@ -0,0 +1,714 @@ +# @ohos.application.appManager (appManager) + +The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. + +> **NOTE** +> +> The APIs of this module are supported since API version 7 and deprecated since API version 9. You are advised to use [@ohos.app.ability.appManager](js-apis-app-ability-appManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```ts +import appManager from '@ohos.application.appManager'; +``` + +## appManager.isRunningInStabilityTest8+ + +static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void + +Checks whether this application is undergoing a stability test. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + appManager.isRunningInStabilityTest((err, flag) => { + console.log('error:' + JSON.stringfy(err)); + console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); + }) + ``` + + +## appManager.isRunningInStabilityTest8+ + +static isRunningInStabilityTest(): Promise<boolean> + +Checks whether this application is undergoing a stability test. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + appManager.isRunningInStabilityTest().then((flag) => { + console.log('The result of isRunningInStabilityTest is:' + JSON.stringify(flag)); + }).catch((error) => { + console.log('error:' + JSON.stringify(error)); + }); + ``` + + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(): Promise\; + +Checks whether this application is running on a RAM constrained device. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + appManager.isRamConstrainedDevice().then((data) => { + console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); + }).catch((error) => { + console.log('error:' + JSON.stringify(error)); + }); + ``` + +## appManager.isRamConstrainedDevice + +isRamConstrainedDevice(callback: AsyncCallback\): void; + +Checks whether this application is running on a RAM constrained device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| + +**Example** + + ```ts + appManager.isRamConstrainedDevice((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The result of isRamConstrainedDevice is:' + JSON.stringify(data)); + }) + ``` + +## appManager.getAppMemorySize + +getAppMemorySize(): Promise\; + +Obtains the memory size of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<number> | Size of the application memory.| + +**Example** + + ```ts + appManager.getAppMemorySize().then((data) => { + console.log('The size of app memory is:' + JSON.stringify(data)); + }).catch((error) => { + console.log('error:' + JSON.stringify(error)); + }); + ``` + +## appManager.getAppMemorySize + +getAppMemorySize(callback: AsyncCallback\): void; + +Obtains the memory size of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<number> | Yes| Size of the application memory.| + +**Example** + + ```ts + appManager.getAppMemorySize((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The size of app memory is:' + JSON.stringify(data)); + }) + ``` +## appManager.getProcessRunningInfos(deprecated) + +getProcessRunningInfos(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the process information.| + +**Example** + + ```ts + appManager.getProcessRunningInfos().then((data) => { + console.log('The process running infos is:' + JSON.stringify(data)); + }).catch((error) => { + console.log('error:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInfos(deprecated) + +getProcessRunningInfos(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| + +**Example** + + ```ts + appManager.getProcessRunningInfos((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The process running infos is:' + JSON.stringify(data)); + }) + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(): Promise\>; + +Obtains information about the running processes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Obtains information about the running processes. This API uses a promise to return the result.| + +**Example** + + ```ts + appManager.getProcessRunningInformation().then((data) => { + console.log('The process running info is:' + JSON.stringify(data)); + }).catch((error) => { + console.log('error:' + JSON.stringify(error)); + }); + ``` + +## appManager.getProcessRunningInformation9+ + +getProcessRunningInformation(callback: AsyncCallback\>): void; + +Obtains information about the running processes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Obtains information about the running processes. This API uses a promise to return the result.| + +**Example** + + ```ts + appManager.getProcessRunningInformation((err, data) => { + console.log('error:' + JSON.stringify(err)); + console.log('The process running info is:' + JSON.stringify(data)); + }) + ``` + +## appManager.registerApplicationStateObserver8+ + +registerApplicationStateObserver(observer: ApplicationStateObserver): number; + +Registers an observer to listen for the state changes of all applications. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| + +**Example** + + ```ts + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); + } + } + const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); + console.log('-------- observerCode: ---------', observerCode); + ``` + +## appManager.registerApplicationStateObserver9+ + +registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\): number; + +Registers an observer to listen for the state changes of a specified application. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observer | [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) | Yes| Numeric code of the observer.| +| bundleNameList | Array | Yes| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| + +**Example** + + ```ts + var applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('------------ onForegroundApplicationChanged -----------', appStateData); + }, + onAbilityStateChanged(abilityStateData) { + console.log('------------ onAbilityStateChanged -----------', abilityStateData); + }, + onProcessCreated(processData) { + console.log('------------ onProcessCreated -----------', processData); + }, + onProcessDied(processData) { + console.log('------------ onProcessDied -----------', processData); + }, + onProcessStateChanged(processData) { + console.log('------------ onProcessStateChanged -----------', processData); + } + } + var bundleNameList = ['bundleName1', 'bundleName2']; + const observerCode = appManager.registerApplicationStateObserver(applicationStateObserver, bundleNameList); + console.log('-------- observerCode: ---------', observerCode); + ``` +## appManager.unregisterApplicationStateObserver8+ + +unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\): void; + +Deregisters the application state observer. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | Yes| Numeric code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var observerId = 100; + + function unregisterApplicationStateObserverCallback(err) { + if (err) { + console.log('------------ unregisterApplicationStateObserverCallback ------------', err); + } + } + appManager.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); + ``` + +## appManager.unregisterApplicationStateObserver8+ + +unregisterApplicationStateObserver(observerId: number): Promise\; + +Deregisters the application state observer. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| observerId | number | Yes| Numeric code of the observer.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var observerId = 100; + + appManager.unregisterApplicationStateObserver(observerId) + .then((data) => { + console.log('----------- unregisterApplicationStateObserver success ----------', data); + }) + .catch((err) => { + console.log('----------- unregisterApplicationStateObserver fail ----------', err); + }) + ``` + +## appManager.getForegroundApplications8+ + +getForegroundApplications(callback: AsyncCallback\>): void; + +Obtains information about the applications that are running in the foreground. This API uses an asynchronous callback to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback\> | Yes| Callback used to return the application information.| + +**Example** + + ```ts + function getForegroundApplicationsCallback(err, data) { + if (err) { + console.log('--------- getForegroundApplicationsCallback fail ---------', err); + } else { + console.log('--------- getForegroundApplicationsCallback success ---------', data) + } + } + appManager.getForegroundApplications(getForegroundApplicationsCallback); + ``` + +## appManager.getForegroundApplications8+ + +getForegroundApplications(): Promise\>; + +Obtains information about the applications that are running in the foreground. This API uses a promise to return the result. The application information is defined by [AppStateData](js-apis-inner-application-appStateData.md). + +**Required permissions**: ohos.permission.GET_RUNNING_INFO + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\> | Promise used to return the application information.| + +**Example** + + ```ts + appManager.getForegroundApplications() + .then((data) => { + console.log('--------- getForegroundApplications success -------', data); + }) + .catch((err) => { + console.log('--------- getForegroundApplications fail -------', err); + }) + ``` + +## appManager.killProcessWithAccount8+ + +killProcessWithAccount(bundleName: string, accountId: number): Promise\ + +Kills a process by bundle name and account ID. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| + +**Example** + +```ts +var bundleName = 'bundleName'; +var accountId = 0; +appManager.killProcessWithAccount(bundleName, accountId) + .then((data) => { + console.log('------------ killProcessWithAccount success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessWithAccount fail ------------', err); + }) +``` + + +## appManager.killProcessWithAccount8+ + +killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void + +Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) and ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + +```ts +var bundleName = 'bundleName'; +var accountId = 0; +function killProcessWithAccountCallback(err, data) { + if (err) { + console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessWithAccountCallback success, data: --------------', data); + } +} +appManager.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); +``` + +## appManager.killProcessesByBundleName8+ + +killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); + +Kills a process by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + function killProcessesByBundleNameCallback(err, data) { + if (err) { + console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); + } else { + console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); + } + } + appManager.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); + ``` + +## appManager.killProcessesByBundleName8+ + +killProcessesByBundleName(bundleName: string): Promise\; + +Kills a process by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var bundleName = 'com.example.myapplication'; + appManager.killProcessesByBundleName(bundleName) + .then((data) => { + console.log('------------ killProcessesByBundleName success ------------', data); + }) + .catch((err) => { + console.log('------------ killProcessesByBundleName fail ------------', err); + }) + ``` + +## appManager.clearUpApplicationData8+ + +clearUpApplicationData(bundleName: string, callback: AsyncCallback\); + +Clears application data by bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + function clearUpApplicationDataCallback(err, data) { + if (err) { + console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); + } else { + console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); + } + } + appManager.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); + ``` + +## appManager.clearUpApplicationData8+ + +clearUpApplicationData(bundleName: string): Promise\; + +Clears application data by bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Example** + + ```ts + var bundleName = 'bundleName'; + appManager.clearUpApplicationData(bundleName) + .then((data) => { + console.log('------------ clearUpApplicationData success ------------', data); + }) + .catch((err) => { + console.log('------------ clearUpApplicationData fail ------------', err); + }) + ``` + +## ApplicationState9+ + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the application is being created. | +| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the application is active. | +| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | +| STATE_DESTROY | 5 | State indicating that the application is destroyed. | + +## ProcessState9+ + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| STATE_CREATE | 1 | State indicating that the process is being created. | +| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. | +| STATE_ACTIVE | 3 | State indicating that the process is active. | +| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. | +| STATE_DESTROY | 5 | State indicating that the process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-application-configuration.md b/en/application-dev/reference/apis/js-apis-application-configuration.md new file mode 100644 index 0000000000000000000000000000000000000000..81870036a845c61f852f671616f63c12f92851b8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-configuration.md @@ -0,0 +1,69 @@ +# @ohos.application.Configuration (Configuration) + +The **Configuration** module defines environment change information. + +> **NOTE** +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [@ohos.app.ability.Configuration](js-apis-app-ability-configuration.md) instead. + +## Modules to Import + +```ts +import Configuration from '@ohos.application.Configuration' +``` + +**System capability**: SystemCapability.Ability.AbilityBase + + | Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| language8+ | string | Yes| Yes| Language of the application, for example, **zh**.| +| colorMode8+ | [ColorMode](js-apis-application-configurationConstant.md#configurationconstantcolormode) | Yes| Yes| Color mode, which can be **COLOR_MODE_LIGHT** or **COLOR_MODE_DARK**. The default value is **COLOR_MODE_LIGHT**.| +| direction9+ | [Direction](js-apis-application-configurationConstant.md#configurationconstantdirection9) | Yes| No| Screen orientation, which can be **DIRECTION_HORIZONTAL** or **DIRECTION_VERTICAL**.| +| screenDensity9+ | [ScreenDensity](js-apis-application-configurationConstant.md#configurationconstantscreendensity9) | Yes| No| Screen resolution, which can be **SCREEN_DENSITY_SDPI** (120), **SCREEN_DENSITY_MDPI** (160), **SCREEN_DENSITY_LDPI** (240), **SCREEN_DENSITY_XLDPI** (320), **SCREEN_DENSITY_XXLDPI** (480), or **SCREEN_DENSITY_XXXLDPI** (640).| +| displayId9+ | number | Yes| No| ID of the display where the application is located.| +| hasPointerDevice9+ | boolean | Yes| No| Whether a pointer device, such as a keyboard, mouse, or touchpad, is connected.| + +For details about the fields, see the **ohos.application.Configuration.d.ts** file. + +**Example** + + ```ts +import hilog from '@ohos.hilog'; +import UIAbility from '@ohos.app.ability.UIAbility'; +import Window from '@ohos.window'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + } + + onDestroy() { + } + + onWindowStageCreate(windowStage: Window.WindowStage) { + let envCallback = { + onConfigurationUpdated(config) { + console.info(`envCallback onConfigurationUpdated success: ${JSON.stringify(config)}`) + let language = config.language; + let colorMode = config.colorMode; + let direction = config.direction; + let screenDensity = config.screenDensity; + let displayId = config.displayId; + let hasPointerDevice = config.hasPointerDevice; + } + }; + + let applicationContext = this.context.getApplicationContext(); + applicationContext.registerEnvironmentCallback(envCallback); + + windowStage.loadContent('pages/index', (err, data) => { + if (err.code) { + hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.ERROR); + hilog.error(0x0000, 'testTag', 'Failed to load the content. Cause: %{public}s', JSON.stringify(err) ?? ''); + return; + } + hilog.isLoggable(0x0000, 'testTag', hilog.LogLevel.INFO); + hilog.info(0x0000, 'testTag', 'Succeeded in loading the content. Data: %{public}s', JSON.stringify(data) ?? ''); + }); + } +} + ``` diff --git a/en/application-dev/reference/apis/js-apis-configurationconstant.md b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md similarity index 81% rename from en/application-dev/reference/apis/js-apis-configurationconstant.md rename to en/application-dev/reference/apis/js-apis-application-configurationConstant.md index 70d527483a15d7f676402ad406964740a5686a6b..dabe32b2f9d166dbce68b94c204b82f78b0090de 100644 --- a/en/application-dev/reference/apis/js-apis-configurationconstant.md +++ b/en/application-dev/reference/apis/js-apis-application-configurationConstant.md @@ -1,15 +1,14 @@ -# ConfigurationConstant +# @ohos.application.ConfigurationConstant (ConfigurationConstant) The **ConfigurationConstant** module provides the enumerated values of the environment configuration information. > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.ConfigurationConstant](js-apis-app-ability-configurationConstant.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import - -```js +```ts import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; ``` @@ -17,12 +16,6 @@ import ConfigurationConstant from '@ohos.application.ConfigurationConstant'; You can obtain the value of this constant by calling the **ConfigurationConstant.ColorMode** API. -**Example** - -``` -ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Value| Description| @@ -36,12 +29,6 @@ ConfigurationConstant.ColorMode.COLOR_MODE_LIGHT You can obtain the value of this constant by calling the **ConfigurationConstant.Direction** API. -**Example** - -``` -ConfigurationConstant.Direction.DIRECTION_VERTICAL -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Value| Description| @@ -55,12 +42,6 @@ ConfigurationConstant.Direction.DIRECTION_VERTICAL You can obtain the value of this constant by calling the **ConfigurationConstant.ScreenDensity** API. -**Example** - -``` -ConfigurationConstant.ScreenDensity.SCREEN_DENSITY_NOT_SET -``` - **System capability**: SystemCapability.Ability.AbilityBase | Name| Value| Description| diff --git a/en/application-dev/reference/apis/js-apis-application-context.md b/en/application-dev/reference/apis/js-apis-application-context.md index 16d5fd0c3d79d097bc8f78ef24cae8f91869b8e3..d42e522c14266de6ca53fff7370c68de14c34d36 100644 --- a/en/application-dev/reference/apis/js-apis-application-context.md +++ b/en/application-dev/reference/apis/js-apis-application-context.md @@ -1,183 +1,41 @@ -# Context +# @ohos.application.context (Context) -The **Context** module provides the context for running code. You can use the APIs to query and set the application information and resource manager. +The **Context** module provides all level-2 module APIs for developers to export. > **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 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 +## Modules to Import -You must extend **AbilityContext** to implement this module. - - ```js -import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let test = "com.example.test"; - let context = this.context.createBundleContext(test); - } - } +```ts +import context from '@ohos.application.context' ``` -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| resourceManager | resmgr.ResourceManager; | Yes| No| **ResourceManager** object.| -| applicationInfo | ApplicationInfo | Yes| No| Information about the application.| -| cacheDir | string | Yes| No| Cache directory of the application on the internal storage.| -| tempDir | string | Yes| No| Temporary file directory of the application.| -| filesDir | string | Yes| No| File directory of the application on the internal storage.| -| databaseDir | string | Yes| No| Storage directory of local data.| -| bundleCodeDir | string | Yes| No| Application installation path.| -| distributedFilesDir | string | Yes| No| Storage directory of distributed application data files.| -| eventHub | [EventHub](js-apis-eventhub.md) | Yes| No| Event hub information.| -| area | [AreaMode](#areamode) | Yes| Yes| Area in which the file to be access is located.| -| preferencesDir | string | Yes| Yes| Preferences directory of the application.| - -## Context.createBundleContext - -createBundleContext(bundleName: string): Context; - -Creates a context for a given application. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +**System capability**: SystemCapability.Ability.AbilityBase -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context created.| +| Name | Readable/Writable| Type | Mandatory| Description | +| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | +| AbilityContext | Read Only | [AbilityContext](js-apis-ability-context.md) | No | Level-2 module **AbilityContext**. | +| AbilityStageContext | Read Only | [AbilityStageContext](js-apis-inner-application-abilityStageContext.md) | No | Level-2 module **AbilityStageContext**.| +| ApplicationContext | Read Only | [ApplicationContext](js-apis-inner-application-applicationContext.md) | No | Level-2 module **ApplicationContext**.| +| BaseContext | Read Only | [BaseContext](js-apis-inner-application-baseContext.md) | No | Level-2 module **BaseContext**.| +| Context | Read Only | [Context](js-apis-inner-application-context.md) | No | Level-2 module **Context**.| +| ExtensionContext | Read Only | [ExtensionContext](js-apis-inner-application-extensionContext.md) | No | Level-2 module **ExtensionContext**.| +| FormExtensionContext | Read Only | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | No | Level-2 module **FormExtensionContext**.| +| EventHub | Read Only | [EventHub](js-apis-inner-application-eventHub.md) | No | Level-2 module **EventHub**.| +| PermissionRequestResult | Read Only | [PermissionRequestResult](js-apis-inner-application-permissionRequestResult.md) | No | Level-2 module **PermissionRequestResult**.| **Example** - - ```js - import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let test = "com.example.test"; - let context = this.context.createBundleContext(test); - } -} - - ``` - - -## Context.createModuleContext - -createModuleContext(moduleName: string): Context; - -Creates a context for a given HAP. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | moduleName | string | Yes| HAP name in the application.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context created.| - -**Example** - - ```js - import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let moduleName = "module"; - let context = this.context.createModuleContext(moduleName); - } -} - - ``` - - -## Context.createModuleContext - -createModuleContext(bundleName: string, moduleName: string): Context; - -Creates a context for a given HAP in an application. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Application bundle name.| - | moduleName | string | Yes| HAP name in the application.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Context | Context created.| - -**Example** - - ```js - import AbilityContext from '@ohos.application.Ability' - class MainAbility extends AbilityContext { - onWindowStageCreate(windowStage) { - let bundleName = "com.example.bundle"; - let moduleName = "module"; - let context = this.context.createModuleContext(bundleName, moduleName); - } -} - - ``` - - -## Context.getApplicationContext - -getApplicationContext(): ApplicationContext; - -Obtains the context of this application. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| ApplicationContext | Current application context.| - -**Example** - - ```js - // This part is mandatory. - let applicationContext = this.context.getApplicationContext(); - ``` - - -## AreaMode - -Defines the area where the file to be access is located. Each area has its own content. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Value | Description | -| --------------- | ---- | --------------- | -| EL1 | 0 | Device-level encryption area. | -| EL2 | 1 | User credential encryption area. The default value is **EL2**.| +```ts +let abilityContext: context.AbilityContext; +let abilityStageContext: context.AbilityStageContext; +let applicationContext: context.ApplicationContext; +let baseContext: context.BaseContext; +let context: context.Context; +let extensionContext: context.ExtensionContext; +let formExtensionContext: context.FormExtensionContext; +let eventHub: context.EventHub; +let permissionRequestResult: context.PermissionRequestResult; +``` diff --git a/en/application-dev/reference/apis/js-apis-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md similarity index 67% rename from en/application-dev/reference/apis/js-apis-errorManager.md rename to en/application-dev/reference/apis/js-apis-application-errorManager.md index 4a39fdd6b0031be7e3fcbdfc7a570609ba217a1b..c1eaa2d35e90966795e4b98f4b75cffc0570e855 100644 --- a/en/application-dev/reference/apis/js-apis-errorManager.md +++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md @@ -1,13 +1,13 @@ -# ErrorManager +# @ohos.application.errorManager (ErrorManager) The **ErrorManager** module provides APIs for registering and deregistering error observers. > **NOTE** > -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.errorManager](js-apis-app-ability-errorManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```ts import errorManager from '@ohos.application.errorManager' ``` @@ -23,11 +23,11 @@ Registers an error observer. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observer | [ErrorObserver](#errorobserver) | No| Numeric code of the observer.| +| observer | [ErrorObserver](js-apis-inner-application-errorObserver.md) | Yes| Numeric code of the observer.| **Example** -```js +```ts var observer = { onUnhandledException(errorMsg) { console.log('onUnhandledException, errorMsg: ', errorMsg) @@ -48,12 +48,12 @@ Deregisters an error observer. This API uses an asynchronous callback to return | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| -| callback | AsyncCallback\ | No| Callback used to return the result.| +| observerId | number | Yes| Numeric code of the observer.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| **Example** -```js +```ts var observerId = 100; function unregisterErrorObserverCallback(err) { @@ -77,7 +77,7 @@ Deregisters an error observer. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| +| observerId | number | Yes| Numeric code of the observer.| **Return value** @@ -87,7 +87,7 @@ Deregisters an error observer. This API uses a promise to return the result. **Example** -```js +```ts var observerId = 100; errorManager.unregisterErrorObserver(observerId) .then((data) => { @@ -98,28 +98,3 @@ errorManager.unregisterErrorObserver(observerId) }) ``` - -## ErrorObserver - -onUnhandledException(errMsg: string): void; - -Called when an unhandled exception occurs in the JS runtime. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| errMsg | string | No| Message and error stack trace about the exception.| - -**Example** - -```js -var observer = { - onUnhandledException(errorMsg) { - console.log('onUnhandledException, errorMsg: ', errorMsg) - } -} -errorManager.registerErrorObserver(observer) -``` diff --git a/en/application-dev/reference/apis/js-apis-application-extensionAbility.md b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md new file mode 100644 index 0000000000000000000000000000000000000000..f18b293edd8d7a4f65684bc38df4fe48498fa11b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-extensionAbility.md @@ -0,0 +1,62 @@ +# @ohos.application.ExtensionAbility (ExtensionAbility) + +The **ExtensionAbility** module manages the ExtensionAbility lifecycle and context, such as creating and destroying an ExtensionAbility, and dumping client information. + +> **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. + +## Modules to Import + +```ts +import ExtensionAbility from '@ohos.application.ExtensionAbility'; +``` + +## ExtensionAbility.onConfigurationUpdated + +onConfigurationUpdated(newConfig: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | newConfig | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| + +**Example** + + ```ts + class MyExtensionAbility extends ExtensionAbility { + onConfigurationUpdated(config) { + console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + } + } + ``` + +## ExtensionAbility.onMemoryLevel + +onMemoryLevel(level: AbilityConstant.MemoryLevel): void; + +Called when the system has decided to adjust the memory level. For example, this API can be used when there is not enough memory to run as many background processes as possible. + +**System capability**: SystemCapability.Ability.AbilityRuntime.AbilityCore + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | level | [AbilityConstant.MemoryLevel](js-apis-application-abilityConstant.md#abilityconstantmemorylevel) | Yes| Memory level that indicates the memory usage status. When the specified memory level is reached, a callback will be invoked and the system will start adjustment.| + +**Example** + + ```ts + class MyExtensionAbility extends ExtensionAbility { + onMemoryLevel(level) { + console.log('onMemoryLevel, level:' + JSON.stringify(level)); + } + } + ``` diff --git a/en/application-dev/reference/apis/js-apis-application-formBindingData.md b/en/application-dev/reference/apis/js-apis-application-formBindingData.md new file mode 100644 index 0000000000000000000000000000000000000000..5fbc52c95dc9e573947fb9820f00100a76a06f22 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formBindingData.md @@ -0,0 +1,64 @@ +# @ohos.application.formBindingData (formBindingData) + +The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [FormBindingData](js-apis-app-form-formBindingData.md) instead. +## Modules to Import + +```ts +import formBindingData from '@ohos.application.formBindingData'; +``` + +## FormBindingData + +Describes a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| + + +## createFormBindingData + +createFormBindingData(obj?: Object | string): FormBindingData + +Creates a **FormBindingData** object. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | ------------------------------------------------------------ | +| obj | Object\|string | No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| + + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------------------------- | +| [FormBindingData](#formbindingdata) | **FormBindingData** object created based on the passed data.| + + +**Example** + +```ts +import formBindingData from @ohos.application.formBindingData; +import fs from '@ohos.file.fs'; + +try { + let fd = fs.openSync('/path/to/form.png') + let obj = { + "temperature": "21°", + "formImages": { "image": fd } + }; + formBindingData.createFormBindingData(obj); +} catch (error.code) { + console.log('catch error, error:' + JSON.stringify(error)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-formerror.md b/en/application-dev/reference/apis/js-apis-application-formError.md similarity index 80% rename from en/application-dev/reference/apis/js-apis-formerror.md rename to en/application-dev/reference/apis/js-apis-application-formError.md index 9425026504a875b92fe5d2312b7de6d4c1e61d84..4ca6eecb8cfae8ddbad623262b8a1c7c9ff515ff 100644 --- a/en/application-dev/reference/apis/js-apis-formerror.md +++ b/en/application-dev/reference/apis/js-apis-application-formError.md @@ -1,14 +1,15 @@ -# FormError +# @ohos.application.formError (formError) -The **FormError** module provides error codes for widgets. +The **formError** module provides error codes for widgets. > **NOTE** -> +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [Form Error Codes](../errorcodes/errorcode-form.md) instead. ## Modules to Import -``` +```ts import formError from '@ohos.application.formError'; ``` @@ -16,9 +17,9 @@ import formError from '@ohos.application.formError'; None. -## enum FormError +## FormError -Enumerates the available error codes. +Enumerates the widget types. **System capability** @@ -27,12 +28,12 @@ SystemCapability.Ability.Form | Name | Value | Description | | ----------- | ---- | ------------ | | ERR_COMMON | 1 | Default error code. | -| ERR_PERMISSION_DENY | 2 | No permission to perform the operation. | +| ERR_PERMISSION_DENY | 2 | You are not authorized to perform the operation. | | ERR_GET_INFO_FAILED | 4 | Failed to obtain the widget information. | | ERR_GET_BUNDLE_FAILED | 5 | Failed to obtain the bundle information. | | ERR_GET_LAYOUT_FAILED | 6 | Failed to obtain the layout information. | -| ERR_ADD_INVALID_PARAM | 7 | Invalid parameter. | -| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match any widget. | +| ERR_ADD_INVALID_PARAM | 7 | Invalid parameters are detected. | +| ERR_CFG_NOT_MATCH_ID | 8 | The widget ID does not match any widget. | | ERR_NOT_EXIST_ID | 9 | The widget ID does not exist. | | ERR_BIND_PROVIDER_FAILED | 10 | Failed to bind to the widget provider. | | ERR_MAX_SYSTEM_FORMS | 11 | The number of system widgets exceeds the upper limit. | @@ -48,4 +49,4 @@ SystemCapability.Ability.Form | ERR_SYSTEM_RESPONSES_FAILED | 30 | The system service failed to respond. | | ERR_FORM_DUPLICATE_ADDED | 31 | The widget has been added. | | ERR_IN_RECOVERY | 36 | Failed to overwrite the widget data. | -| ERR_DISTRIBUTED_SCHEDULE_FAILED9+ | 37 | The distributed scheduler failed.
This is a system API. | +| ERR_DISTRIBUTED_SCHEDULE_FAILED9+ | 37 | The distributed scheduler failed.
**System API**: This is a system API. | diff --git a/en/application-dev/reference/apis/js-apis-application-formExtension.md b/en/application-dev/reference/apis/js-apis-application-formExtension.md new file mode 100644 index 0000000000000000000000000000000000000000..fcde831bc20ca03c224b977271f40b69f1ad0569 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formExtension.md @@ -0,0 +1,284 @@ +# @ohos.application.FormExtension (FormExtension) + +The **FormExtension** module provides APIs related to Form Extension abilities. + +> **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. +> This module is deprecated since API version 9. You are advised to use [FormExtensionAbility](js-apis-app-form-formExtensionAbility.md) instead. +> The APIs of this module can be used only in the stage model. + +## Modules to Import + +```ts +import FormExtension from '@ohos.application.FormExtension'; +``` + +## Attributes + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable| Writable| Description | +| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | +| context | [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.| + +## onCreate + +onCreate(want: Want): formBindingData.FormBindingData + +Called to notify the widget provider that a **Form** instance (widget) has been created. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | +| want | [Want](js-apis-application-want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onCreate(want) { + console.log('FormExtension onCreate, want:' + want.abilityName); + let dataObj1 = { + temperature:"11c", + "time":"11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +} +``` + +## FormExtension.onCastToNormal + +onCastToNormal(formId: string): void + +Called to notify the widget provider that a temporary widget has been converted to a normal one. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| formId | string | Yes | ID of the widget that requests to be converted to a normal one.| + +**Example** + +```ts +export default class MyFormExtension extends FormExtension { + onCastToNormal(formId) { + console.log('FormExtension onCastToNormal, formId:' + formId); + } +} +``` + +## FormExtension.onUpdate + +onUpdate(formId: string): void + +Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-inner-application-formExtensionContext.md) class to update the widget data. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget that requests to be updated.| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onUpdate(formId) { + console.log('FormExtension onUpdate, formId:' + formId); + let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + this.context.updateForm(formId, obj2).then((data)=>{ + console.log('FormExtension context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error);}); + } +} +``` + +## FormExtension.onVisibilityChange + +onVisibilityChange(newStatus: { [key: string]: number }): void + +Called to notify the widget provider of the change of visibility. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | ---------------------------- | +| newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| + +**Example** + +```ts +import formBindingData from '@ohos.application.formBindingData' +export default class MyFormExtension extends FormExtension { + onVisibilityChange(newStatus) { + console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); + let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); + + for (let key in newStatus) { + console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); + this.context.updateForm(key, obj2).then((data)=>{ + console.log('FormExtension context updateForm, data:' + data); + }).catch((error) => { + console.error('Operation updateForm failed. Cause: ' + error);}); + } + } +} +``` + +## FormExtension.onEvent + +onEvent(formId: string, message: string): void + +Called to instruct the widget provider to receive and process the widget event. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ---------------------- | +| formId | string | Yes | ID of the widget that requests the event.| +| message | string | Yes | Event message. | + +**Example** + +```ts +export default class MyFormExtension extends FormExtension { + onEvent(formId, message) { + console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); + } +} +``` + +## FormExtension.onDestroy + +onDestroy(formId: string): void + +Called to notify the widget provider that a **Form** instance (widget) has been destroyed. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| formId | string | Yes | ID of the widget to be destroyed.| + +**Example** + +```ts +export default class MyFormExtension extends FormExtension { + onDestroy(formId) { + console.log('FormExtension onDestroy, formId:' + formId); + } +} +``` + +## FormExtension.onConfigurationUpdated + +onConfigurationUpdated(config: Configuration): void; + +Called when the configuration of the environment where the ability is running is updated. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| + +**Example** + +```ts +class MyFormExtension extends FormExtension { + onConfigurationUpdated(config) { + console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); + } +} +``` + +## FormExtension.onAcquireFormState + +onAcquireFormState?(want: Want): formInfo.FormState; + +Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| + +**Example** + +```ts +import formInfo from '@ohos.application.formInfo' +class MyFormExtension extends FormExtension { + onAcquireFormState(want) { + console.log('FormExtension onAcquireFormState, want:' + want); + return formInfo.FormState.UNKNOWN; + } +} +``` + +## FormExtension.onShare + +onShare?(formId: string): {[key: string]: any}; + +Called by the widget provider to receive shared widget data. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ----------------------------------------------------------- | +| {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| + +**Example** + +```ts +class MyFormExtension extends FormExtension { + onShare(formId) { + console.log('FormExtension onShare, formId:' + formId); + let wantParams = { + "temperature":"20", + "time":"2022-8-8 09:59", + }; + return wantParams; + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-formHost.md b/en/application-dev/reference/apis/js-apis-application-formHost.md new file mode 100644 index 0000000000000000000000000000000000000000..11da810effa714b8aaf37e35d3c0566556281ebf --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formHost.md @@ -0,0 +1,1254 @@ +# @ohos.application.formHost (formHost) + +The **formHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets installed by the same user, and obtain widget information and status. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [formHost](js-apis-app-form-formHost.md) instead. +> The APIs provided by this module are system APIs. + +## Modules to Import + +```ts +import formHost from '@ohos.application.formHost'; +``` + +## deleteForm + +deleteForm(formId: string, callback: AsyncCallback<void>): void + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is deleted, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.deleteForm(formId, (error, data) => { + if (error.code) { + console.error('formHost deleteForm, error:' + JSON.stringify(error)); + } +}); +``` + +## deleteForm + +deleteForm(formId: string): Promise<void> + +Deletes a widget. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Parameters** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.deleteForm(formId).then(() => { + console.log('formHost deleteForm success'); +}).catch((error) => { + console.error('formHost deleteForm, error:' + JSON.stringify(error)); +}); +``` + +## releaseForm + +releaseForm(formId: string, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.releaseForm(formId, (error, data) => { + if (error.code) { + console.error('formHost releaseForm, error:' + JSON.stringify(error)); + } else { + console.log('formHost releaseForm success'); + } +}); +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | Yes | Whether to release the cache.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is released, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.releaseForm(formId, true, (error, data) => { + if (error.code) { + console.error('formHost releaseForm, error:' + JSON.stringify(error)); + } else { + console.log('formHost releaseForm success'); + } +}); +``` + +## releaseForm + +releaseForm(formId: string, isReleaseCache?: boolean): Promise<void> + +Releases a widget. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ----------- | +| formId | string | Yes | Widget ID. | +| isReleaseCache | boolean | No | Whether to release the cache.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.releaseForm(formId, true).then(() => { + console.log('formHost releaseForm success'); +}).catch((error) => { + console.error('formHost releaseForm, error:' + JSON.stringify(error)); +}); +``` + +## requestForm + +requestForm(formId: string, callback: AsyncCallback<void>): void + +Requests a widget update. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is updated, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.requestForm(formId, (error, data) => { + if (error.code) { + console.error('formHost requestForm, error:' + JSON.stringify(error)); + } +}); +``` + +## requestForm + +requestForm(formId: string): Promise<void> + +Requests a widget update. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.requestForm(formId).then(() => { + console.log('formHost requestForm success'); +}).catch((error) => { + console.error('formHost requestForm, error:' + JSON.stringify(error)); +}); +``` + +## castTempForm + +castTempForm(formId: string, callback: AsyncCallback<void>): void + +Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is converted to a normal one, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.castTempForm(formId, (error, data) => { + if (error.code) { + console.error('formHost castTempForm, error:' + JSON.stringify(error)); + } +}); +``` + +## castTempForm + +castTempForm(formId: string): Promise<void> + +Converts a temporary widget to a normal one. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.castTempForm(formId).then(() => { + console.log('formHost castTempForm success'); +}).catch((error) => { + console.error('formHost castTempForm, error:' + JSON.stringify(error)); +}); +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget visible, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.notifyVisibleForms(formId, (error, data) => { + if (error.code) { + console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyVisibleForms + +notifyVisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget visible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.notifyVisibleForms(formId).then(() => { + console.log('formHost notifyVisibleForms success'); +}).catch((error) => { + console.error('formHost notifyVisibleForms, error:' + JSON.stringify(error)); +}); +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget invisible, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.notifyInvisibleForms(formId, (error, data) => { + if (error.code) { + console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyInvisibleForms + +notifyInvisibleForms(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget invisible. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.notifyInvisibleForms(formId).then(() => { + console.log('formHost notifyInvisibleForms success'); +}).catch((error) => { + console.error('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); +}); +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget updatable, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.enableFormsUpdate(formId, (error, data) => { + if (error.code) { + console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); + } +}); +``` + +## enableFormsUpdate + +enableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget updatable. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.enableFormsUpdate(formId).then(() => { + console.log('formHost enableFormsUpdate success'); +}).catch((error) => { + console.error('formHost enableFormsUpdate, error:' + JSON.stringify(error)); +}); +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If a notification is sent to the widget framework to make the widget not updatable, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.disableFormsUpdate(formId, (error, data) => { + if (error.code) { + console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); + } +}); +``` + +## disableFormsUpdate + +disableFormsUpdate(formIds: Array<string>): Promise<void> + +Instructs the widget framework to make a widget not updatable. After this API is called, the widget cannot receive updates from the widget provider. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = ["12400633174999288"]; +formHost.disableFormsUpdate(formId).then(() => { + console.log('formHost disableFormsUpdate success'); +}).catch((error) => { + console.error('formHost disableFormsUpdate, error:' + JSON.stringify(error)); +}); +``` + +## isSystemReady + +isSystemReady(callback: AsyncCallback<void>): void + +Checks whether the system is ready. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the check is successful, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.isSystemReady((error, data) => { + if (error.code) { + console.error('formHost isSystemReady, error:' + JSON.stringify(error)); + } +}); +``` + +## isSystemReady + +isSystemReady(): Promise<void> + +Checks whether the system is ready. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +formHost.isSystemReady().then(() => { + console.log('formHost isSystemReady success'); +}).catch((error) => { + console.error('formHost isSystemReady, error:' + JSON.stringify(error)); +}); +``` + +## getAllFormsInfo + +getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +formHost.getAllFormsInfo((error, data) => { + if (error.code) { + console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); + } +}); +``` + +## getAllFormsInfo + +getAllFormsInfo(): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| + +**Example** + + ```ts + import formHost from '@ohos.application.formHost'; + + formHost.getAllFormsInfo().then((data) => { + console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); + }).catch((error) => { + console.error('formHost getAllFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## getFormsInfo + +getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { + if (error.code) { + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } +}); +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void + +Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | Yes| Module name.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Yes| Callback used to return the result. If the widget information is obtained, **error** is undefined and **data** is the information obtained; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { + if (error.code) { + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + } +}); +``` + +## getFormsInfo + +getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formInfo.FormInfo>> + +Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| bundleName | string | Yes| Bundle name of the application.| +| moduleName | string | No| Module name.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<Array<[formInfo.FormInfo](js-apis-application-formInfo.md)>> | Promise used to return the information obtained.| + +**Example** + + ```ts + import formHost from '@ohos.application.formHost'; + + formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { + console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); + }).catch((error) => { + console.error('formHost getFormsInfo, error:' + JSON.stringify(error)); + }); + ``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void + +Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| +| callback | AsyncCallback<number> | Yes| Callback used to return the result. If the invalid widgets are deleted, **error** is undefined and **data** is the number of widgets deleted; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +formHost.deleteInvalidForms(formIds, (error, data) => { + if (error.code) { + console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); + } else { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); + } +}); +``` + +## deleteInvalidForms + +deleteInvalidForms(formIds: Array<string>): Promise<number> + +Deletes invalid widgets from the list. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of valid widget IDs.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the number of widgets deleted.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +formHost.deleteInvalidForms(formIds).then((data) => { + console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); +}).catch((error) => { + console.error('formHost deleteInvalidForms, error:' + JSON.stringify(error)); +}); +``` + +## acquireFormState + +acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo>): void + +Obtains the widget state. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state. The information must contain the bundle name, ability name, module name, widget name, and widget dimensions.| +| callback | AsyncCallback<[formInfo.FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Yes| Callback used to return the result. If the widget state is obtained, **error** is undefined and **data** is the widget state obtained; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +formHost.acquireFormState(want, (error, data) => { + if (error.code) { + console.error('formHost acquireFormState, error:' + JSON.stringify(error)); + } else { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); + } +}); +``` + +## acquireFormState + +acquireFormState(want: Want): Promise<formInfo.FormStateInfo> + +Obtains the widget state. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| want | [Want](js-apis-application-want.md) | Yes | **Want** information carried to query the widget state.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<[FormStateInfo](js-apis-application-formInfo.md#formstateinfo)> | Promise used to return the widget state obtained.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let want = { + "deviceId": "", + "bundleName": "ohos.samples.FormApplication", + "abilityName": "FormAbility", + "parameters": { + "ohos.extra.param.key.module_name": "entry", + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.form_dimension": 2 + } +}; +formHost.acquireFormState(want).then((data) => { + console.log('formHost acquireFormState, data:' + JSON.stringify(data)); +}).catch((error) => { + console.error('formHost acquireFormState, error:' + JSON.stringify(error)); +}); +``` + +## on("formUninstall") + +on(type: "formUninstall", callback: Callback<string>): void + +Subscribes to widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | Yes| Callback used to return the widget ID.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.on("formUninstall", callback); +``` + +## off("formUninstall") + +off(type: "formUninstall", callback?: Callback<string>): void + +Unsubscribes from widget uninstall events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| type | string | Yes | Event type. The value **formUninstall** indicates a widget uninstallation event.| +| callback | Callback<string> | No| Callback used to return the widget ID. If it is left unspecified, it indicates the callback for all the events that have been subscribed.
The value must be the same as that in **on("formUninstall")**.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let callback = function(formId) { + console.log('formHost on formUninstall, formId:' + formId); +} +formHost.off("formUninstall", callback); +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsVisible(formIds, true, (error, data) => { + if (error.code) { + console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyFormsVisible + +notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void> + +Instructs the widgets to make themselves visible. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isVisible | boolean | Yes | Whether to make the widgets visible.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsVisible(formIds, true).then(() => { + console.log('formHost notifyFormsVisible success'); +}).catch((error) => { + console.error('formHost notifyFormsVisible, error:' + JSON.stringify(error)); +}); +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void + +Instructs the widgets to enable or disable updates. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formIds | Array<string> | Yes | List of widget IDs.| +| isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the notification is sent, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { + if (error.code) { + console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); + } +}); +``` + +## notifyFormsEnableUpdate + +notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void> + +Instructs the widgets to enable or disable updates. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------- | + | formIds | Array<string> | Yes | List of widget IDs.| + | isEnableUpdate | boolean | Yes | Whether to make the widgets updatable.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsEnableUpdate(formIds, true).then(() => { + console.log('formHost notifyFormsEnableUpdate success'); +}).catch((error) => { + console.error('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); +}); +``` +## shareForm9+ + +shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void + +Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the widget is shared, **error** is undefined; otherwise, **error** is an error object.| + +**Example** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +formHost.shareForm(formId, deviceId, (error, data) => { + if (error.code) { + console.error('formHost shareForm, error:' + JSON.stringify(error)); + } +}); +``` + +## shareForm9+ + +shareForm(formId: string, deviceId: string): Promise<void> + +Shares a specified widget with a remote device. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Parameters** + +```ts +import formHost from '@ohos.application.formHost'; + +let formId = "12400633174999288"; +let deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; +formHost.shareForm(formId, deviceId).then(() => { + console.log('formHost shareForm success'); +}).catch((error) => { + console.error('formHost shareForm, error:' + JSON.stringify(error)); +}); +``` + +## notifyFormsPrivacyProtected9+ + +notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean, callback: AsyncCallback<void>): void + +Notifies that the privacy protection status of the specified widgets changes. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------- | +| formId | string | Yes | Widget ID.| +| deviceId | string | Yes | Remote device ID.| + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { + console.log('formHost shareForm success'); +}).catch((error) => { + console.error('formHost shareForm, error:' + JSON.stringify(error)); +}); +``` + +## notifyFormsPrivacyProtected + +function notifyFormsPrivacyProtected(formIds: Array<string>, isProtected: boolean): Promise<void>; + +Notifies that the privacy protection status of the specified widgets changes. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.REQUIRE_FORM + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------- | ---- | -------------------------------- | +| formIds | Array<string> | Yes | ID of the widgets.| +| isProtected | boolean | Yes | Whether privacy protection is enabled. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + + +```ts +import formHost from '@ohos.application.formHost'; + +let formIds = new Array("12400633174999288", "12400633174999289"); +try { + formHost.notifyFormsPrivacyProtected(formIds, true).then(() => { + console.log('formHost notifyFormsPrivacyProtected success'); + }).catch((error) => { + console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); + }); +} catch(error) { + console.log('formHost notifyFormsPrivacyProtected, error:' + JSON.stringify(error)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-formInfo.md b/en/application-dev/reference/apis/js-apis-application-formInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..df591cea222b9bdbc98c4d108a4151a8aa1c69cb --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-application-formInfo.md @@ -0,0 +1,141 @@ +# @ohos.application.formInfo (formInfo) + +The **formInfo** module provides types and enums related to the widget information and state. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [formInfo](js-apis-app-form-formInfo.md) instead. + +## Modules to Import + +```ts +import formInfo from '@ohos.application.formInfo'; +``` + +## FormInfo + +Describes widget information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- |-------- | -------------------- | ------------------------------------------------------------ | +| bundleName | string | Yes | No | Name of the bundle to which the widget belongs. | +| moduleName | string | Yes | No | Name of the module to which the widget belongs. | +| abilityName | string | Yes | No | Name of the ability to which the widget belongs. | +| name | string | Yes | No | Widget name. | +| description | string | Yes | No | Description of the widget. | +| type | [FormType](#formtype) | Yes | No | Type of the widget. Currently, only JS widgets are supported.| +| jsComponentName | string | Yes | No | Name of the component used in the JS widget. | +| colorMode | [ColorMode](#colormode) | Yes | No | Color mode of the widget. | +| isDefault | boolean | Yes | No | Whether the widget is the default one. | +| updateEnabled | boolean | Yes | No | Whether the widget is updatable. | +| formVisibleNotify | boolean | Yes | No | Whether to send a notification when the widget is visible. | +| relatedBundleName | string | Yes | No | Name of the associated bundle to which the widget belongs. | +| scheduledUpdateTime | string | Yes | No | Time when the widget was updated. | +| formConfigAbility | string | Yes | No | Configuration ability of the widget. | +| updateDuration | number | Yes | No | Update period of the widget.| +| defaultDimension | number | Yes | No | Default dimension of the widget. | +| supportDimensions | Array<number> | Yes | No | Dimensions supported by the widget. | +| customizeData | {[key: string]: [value: string]} | Yes | No | Custom data of the widget. | + +## FormType + +Enumerates the widget types. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| JS | 1 | JS widget. | +| eTS9+ | 2 | eTS widget.| + +## ColorMode + +Enumerates the color modes supported by the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| MODE_AUTO | -1 | Auto mode. | +| MODE_DARK | 0 | Dark mode. | +| MODE_LIGHT | 1 | Light mode. | + +## FormStateInfo + +Describes the widget state information. + +**System capability**: SystemCapability.Ability.Form + +| Name | Type | Readable | Writable | Description | +| ----------- | -------- |-------- | -------------------- | ------------------------------------------------------------ | +| formState | [FormState](#formstate) | Yes | No | Widget state. | +| want | Want | Yes | No | Want text. | + +## FormState + +Enumerates the widget states. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| UNKNOWN | -1 | Unknown state. | +| DEFAULT | 0 | Default state. | +| READY | 1 | Ready state. | + +## FormParam + +Enumerates the widget parameters. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| IDENTITY_KEY9+ | "ohos.extra.param.key.form_identity" | Widget ID.
**System API**: This is a system API. | +| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | +| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | +| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | +| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | +| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | +| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | +| ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | +| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID. | +| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| + +## FormDimension9+ + +Enumerates the widget dimensions. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| Dimension_1_2 9+ | 1 | 1 x 2. | +| Dimension_2_2 9+ | 2 | 2 x 2. | +| Dimension_2_4 9+ | 3 | 2 x 4. | +| Dimension_4_4 9+ | 4 | 4 x 4. | +| Dimension_2_1 9+ | 5 | 2 x 1. | + +## FormInfoFilter9+ + +Defines the widget information filter. Only the widget information that meets the filter is returned. + +**System capability**: SystemCapability.Ability.Form + +| Name | Description | +| ----------- | ------------ | +| moduleName9+ | Optional. Only the information about the widget whose **moduleName** is the same as the provided value is returned.
If this parameter is not set, **moduleName** is not used for filtering.| + +## VisibilityType9+ + +Enumerates the visibility types of the widget. + +**System capability**: SystemCapability.Ability.Form + +| Name | Value | Description | +| ----------- | ---- | ------------ | +| FORM_VISIBLE9+ | 1 | The widget is visible.| +| FORM_INVISIBLE9+ | 2 | The widget is invisible.| diff --git a/en/application-dev/reference/apis/js-apis-formprovider.md b/en/application-dev/reference/apis/js-apis-application-formProvider.md similarity index 59% rename from en/application-dev/reference/apis/js-apis-formprovider.md rename to en/application-dev/reference/apis/js-apis-application-formProvider.md index 8ce539886e5460ffe712b486addf6e3813c44a90..4d604ff7295eb9903d450bc96f9c00fde253ee11 100644 --- a/en/application-dev/reference/apis/js-apis-formprovider.md +++ b/en/application-dev/reference/apis/js-apis-application-formProvider.md @@ -1,154 +1,150 @@ -# FormProvider +# @ohos.application.formProvider (formProvider) The **FormProvider** module provides APIs related to the widget provider. You can use the APIs to update a widget, set the next refresh time for a widget, obtain widget information, and request a widget release. > **NOTE** -> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> This module is deprecated since API version 9. You are advised to use [formProvider](js-apis-app-form-formProvider.md) instead. ## Modules to Import -``` +```ts import formProvider from '@ohos.application.formProvider'; ``` -## Required Permissions - -None. - ## setFormNextRefreshTime -setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void; +setFormNextRefreshTime(formId: string, minute: number, callback: AsyncCallback<void>): void Sets the next refresh time for a widget. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------- | - | formId | string | Yes | ID of a widget. | + | formId | string | Yes | Widget ID. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js - var formId = "12400633174999288"; + ```ts + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5, (error, data) => { - if (error.code) { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); - } + if (error.code) { + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + } }); ``` ## setFormNextRefreshTime -setFormNextRefreshTime(formId: string, minute: number): Promise<void>; +setFormNextRefreshTime(formId: string, minute: number): Promise<void> Sets the next refresh time for a widget. This API uses a promise to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------- | - | formId | string | Yes | ID of a widget. | + | formId | string | Yes | Widget ID. | | minute | number | Yes | Refresh interval, in minutes. The value must be greater than or equal to 5. | **Return value** | Type | Description | | ------------- | ---------------------------------- | - | Promise\ |Promise used to return the result. | + | Promise\ | Promise that returns no value. | **Example** - ```js - var formId = "12400633174999288"; + ```ts + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; formProvider.setFormNextRefreshTime(formId, 5).then(() => { - console.log('formProvider setFormNextRefreshTime success'); + console.log('formProvider setFormNextRefreshTime success'); }).catch((error) => { - console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); + console.log('formProvider setFormNextRefreshTime, error:' + JSON.stringify(error)); }); ``` ## updateForm -updateForm(formId: string, formBindingData: formBindingData.FormBindingData,callback: AsyncCallback<void>): void; +updateForm(formId: string, formBindingData: formBindingData.FormBindingData,callback: AsyncCallback<void>): void Updates a widget. This API uses an asynchronous callback to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | + | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js + ```ts import formBindingData from '@ohos.application.formBindingData'; - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj, (error, data) => { - if (error.code) { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); - } + if (error.code) { + console.log('formProvider updateForm, error:' + JSON.stringify(error)); + } }); ``` ## updateForm -updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void>; +updateForm(formId: string, formBindingData: formBindingData.FormBindingData): Promise<void> Updates a widget. This API uses a promise to return the result. -**System capability** - -SystemCapability.Ability.Form +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | | formId | string | Yes | ID of the widget to update.| - | formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data to be used for the update. | + | formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data to be used for the update. | **Return value** | Type | Description | | -------------- | ----------------------------------- | -| Promise\ | Promise used to return the result.| +| Promise\ | Promise that returns no value.| **Example** - ```js + ```ts import formBindingData from '@ohos.application.formBindingData'; - var formId = "12400633174999288"; + import formProvider from '@ohos.app.form.formProvider'; + + let formId = "12400633174999288"; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.updateForm(formId, obj).then(() => { - console.log('formProvider updateForm success'); + console.log('formProvider updateForm success'); }).catch((error) => { - console.log('formProvider updateForm, error:' + JSON.stringify(error)); + console.log('formProvider updateForm, error:' + JSON.stringify(error)); }); ``` ## getFormsInfo9+ -getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void; +getFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void Obtains the application's widget information on the device. This API uses an asynchronous callback to return the result. @@ -158,22 +154,24 @@ Obtains the application's widget information on the device. This API uses an asy | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** -```js +```ts +import formProvider from '@ohos.app.form.formProvider'; + formProvider.getFormsInfo((error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } }); ``` ## getFormsInfo9+ -getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; +getFormsInfo(filter: formInfo.FormInfoFilter, callback: AsyncCallback<Array<formInfo.FormInfo>>): void Obtains the application's widget information that meets a filter criterion on the device. This API uses an asynchronous callback to return the result. @@ -183,28 +181,31 @@ Obtains the application's widget information that meets a filter criterion on th | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md#forminfofilter) | Yes| Filter criterion.| -| callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| +| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md#forminfofilter) | Yes| Filter criterion.| +| callback | AsyncCallback<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Yes| Callback used to return the information obtained.| **Example** -```js +```ts import formInfo from '@ohos.application.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + const filter : formInfo.FormInfoFilter = { - moduleName : "entry" + // get info of forms belong to module entry. + moduleName : "entry" }; formProvider.getFormsInfo(filter, (error, data) => { - if (error.code) { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + } else { + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + } }); ``` ## getFormsInfo9+ -getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>>; +getFormsInfo(filter?: formInfo.FormInfoFilter): Promise<Array<formInfo.FormInfo>> Obtains the application's widget information on the device. This API uses a promise to return the result. @@ -214,121 +215,127 @@ Obtains the application's widget information on the device. This API uses a prom | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| filter | [formInfo.FormInfoFilter](./js-apis-formInfo.md) | No| Filter criterion.| +| filter | [formInfo.FormInfoFilter](./js-apis-application-formInfo.md) | No| Filter criterion.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| +| Promise<Array<[formInfo.FormInfo](./js-apis-application-formInfo.md#forminfo-1)>> | Promise used to return the information obtained.| **Example** -```js +```ts import formInfo from '@ohos.application.formInfo'; +import formProvider from '@ohos.app.form.formProvider'; + const filter : formInfo.FormInfoFilter = { - moduleName : "entry" + // get info of forms belong to module entry. + moduleName : "entry" }; formProvider.getFormsInfo(filter).then((data) => { - console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); + console.log('formProvider getFormsInfo, data:' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); + console.log('formProvider getFormsInfo, error:' + JSON.stringify(error)); }); ``` ## requestPublishForm9+ -requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void; +requestPublishForm(want: Want, formBindingData: formBindingData.FormBindingData, callback: AsyncCallback\): void -Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. +Requests to publish a widget carrying data to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------------------------------------------------------- | ---- | ---------------- | -| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | Yes | Data used for creating the widget.| +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| | callback | AsyncCallback<string> | Yes| Callback used to return the widget ID.| **Example** - ```js + ```ts import formBindingData from '@ohos.application.formBindingData'; - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + import formProvider from '@ohos.app.form.formProvider'; + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; let obj = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); formProvider.requestPublishForm(want, obj, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } }); ``` ## requestPublishForm9+ -requestPublishForm(want: Want, callback: AsyncCallback<string>): void; +requestPublishForm(want: Want, callback: AsyncCallback<string>): void -Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. +Requests to publish a widget to the widget host. This API uses an asynchronous callback to return the result. This API is usually called by the home screen. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| callback | AsyncCallback<string> | Yes | Callback used to return the widget ID. | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| callback | AsyncCallback<string> | Yes | Callback used to return the widget ID.| **Example** - ```js - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + ```ts + import formProvider from '@ohos.app.form.formProvider'; + + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; formProvider.requestPublishForm(want, (error, data) => { - if (error.code) { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); - } else { - console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); - } + if (error.code) { + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + } else { + console.log('formProvider requestPublishForm, form ID is: ' + JSON.stringify(data)); + } }); ``` ## requestPublishForm9+ -requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string>; +requestPublishForm(want: Want, formBindingData?: formBindingData.FormBindingData): Promise<string> -Requests to publish a widget to the widget host. This API uses a promise to return the result. +Requests to publish a widget to the widget host. This API uses a promise to return the result. This API is usually called by the home screen. **System capability**: SystemCapability.Ability.Form -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** | Name | Type | Mandatory| Description | | --------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | -| formBindingData | [FormBindingData](js-apis-formbindingdata.md#formbindingdata) | No | Data used for creating the widget. | +| want | [Want](js-apis-application-want.md) | Yes | Request used for publishing. The following fields must be included:
Information about the target widget.
**abilityName**: ability of the target widget.
**parameters**:
"ohos.extra.param.key.form_dimension"
"ohos.extra.param.key.form_name"
"ohos.extra.param.key.module_name" | +| formBindingData | [formBindingData.FormBindingData](js-apis-application-formBindingData.md#formbindingdata) | Yes | Data used for creating the widget.| **Return value** @@ -338,53 +345,55 @@ Requests to publish a widget to the widget host. This API uses a promise to retu **Example** - ```js - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + ```ts + import formProvider from '@ohos.app.form.formProvider'; + + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; formProvider.requestPublishForm(want).then((data) => { - console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); + console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); }).catch((error) => { - console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); + console.log('formProvider requestPublishForm, error: ' + JSON.stringify(error)); }); ``` ## isRequestPublishFormSupported9+ -isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void; +isRequestPublishFormSupported(callback: AsyncCallback<boolean>): void Checks whether a widget can be published to the widget host. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Ability.Form +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Ability.Form **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the widget can be published to the widget host.| **Example** -```js +```ts formProvider.isRequestPublishFormSupported((error, isSupported) => { if (error.code) { console.log('formProvider isRequestPublishFormSupported, error:' + JSON.stringify(error)); } else { if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { - "ohos.extra.param.key.form_dimension": 2, - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.module_name": "entry" - } + let want = { + abilityName: "FormAbility", + parameters: { + "ohos.extra.param.key.form_dimension": 2, + "ohos.extra.param.key.form_name": "widget", + "ohos.extra.param.key.module_name": "entry" + } }; formProvider.requestPublishForm(want, (error, data) => { if (error.code) { @@ -400,32 +409,32 @@ formProvider.isRequestPublishFormSupported((error, isSupported) => { ## isRequestPublishFormSupported9+ -isRequestPublishFormSupported(): Promise<boolean>; +isRequestPublishFormSupported(): Promise<boolean> Checks whether a widget can be published to the widget host. This API uses a promise to return the result. -**System capability**: SystemCapability.Ability.Form +**System API**: This is a system API. -**System API**: This is a system API and cannot be called by third-party applications. +**System capability**: SystemCapability.Ability.Form **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<boolean> | Promise used to return the result.| +| Promise<boolean> | Promise used to return whether the widget can be published to the widget host.| **Example** -```js +```ts formProvider.isRequestPublishFormSupported().then((isSupported) => { if (isSupported) { - var want = { - abilityName: "FormAbility", - parameters: { + let want = { + abilityName: "FormAbility", + parameters: { "ohos.extra.param.key.form_dimension": 2, "ohos.extra.param.key.form_name": "widget", "ohos.extra.param.key.module_name": "entry" - } + } }; formProvider.requestPublishForm(want).then((data) => { console.log('formProvider requestPublishForm success, form ID is :' + JSON.stringify(data)); diff --git a/en/application-dev/reference/apis/js-apis-missionManager.md b/en/application-dev/reference/apis/js-apis-application-missionManager.md similarity index 76% rename from en/application-dev/reference/apis/js-apis-missionManager.md rename to en/application-dev/reference/apis/js-apis-application-missionManager.md index 189042b1f1df1727423c65c0a226b11ae473db2a..17de66e19334dce9663017c3df9c18b575e14bd7 100644 --- a/en/application-dev/reference/apis/js-apis-missionManager.md +++ b/en/application-dev/reference/apis/js-apis-application-missionManager.md @@ -1,14 +1,14 @@ -# missionManager +# @ohos.application.missionManager (missionManager) The **missionManager** module provides APIs to lock, unlock, and clear missions, and switch a mission to the foreground. > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 8 and deprecated since API version 9. You are advised to use [@ohos.app.ability.missionManager](js-apis-app-ability-missionManager.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```ts import missionManager from '@ohos.application.missionManager' ``` @@ -22,7 +22,7 @@ registerMissionListener(listener: MissionListener): number; Registers a listener to observe the mission status. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -32,27 +32,28 @@ Registers a listener to observe the mission status. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listener | MissionListener | Yes| Listener to register.| + | listener | [MissionListener](js-apis-inner-application-missionListener.md) | Yes| Mission status listener to register.| **Return value** | Type| Description| | -------- | -------- | - | number | Returns the unique index of the mission status listener, which is created by the system and allocated when the listener is registered.| + | number | Index of the mission status listener, which is created by the system and allocated when the listener is registered.| **Example** -```js - var listener = { - onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, - onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, - onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, - onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, - onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} - }; - console.log("registerMissionListener") - var listenerid = missionManager.registerMissionListener(listener); +```ts +var listener = { + onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, + onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, + onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, + onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, + onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} +}; +console.log("registerMissionListener") +var listenerid = missionManager.registerMissionListener(listener); ``` @@ -62,7 +63,7 @@ unregisterMissionListener(listenerId: number, callback: AsyncCallback<void> Deregisters a mission status listener. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -72,19 +73,20 @@ Deregisters a mission status listener. This API uses an asynchronous callback to | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** -```js +```ts var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); @@ -101,7 +103,7 @@ unregisterMissionListener(listenerId: number): Promise<void>; Deregisters a mission status listener. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -111,7 +113,7 @@ Deregisters a mission status listener. This API uses a promise to return the res | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | listenerId | number | Yes| Unique index of the mission status listener to unregister. It is returned by **registerMissionListener**.| + | listenerId | number | Yes| Index of the mission status listener to deregister. It is returned by **registerMissionListener()**.| **Return value** @@ -121,14 +123,15 @@ Deregisters a mission status listener. This API uses a promise to return the res **Example** -```js +```ts var listener = { onMissionCreated: function (mission) {console.log("--------onMissionCreated-------")}, onMissionDestroyed: function (mission) {console.log("--------onMissionDestroyed-------")}, onMissionSnapshotChanged: function (mission) {console.log("--------onMissionSnapshotChanged-------")}, onMissionMovedToFront: function (mission) {console.log("--------onMissionMovedToFront-------")}, onMissionIconUpdated: function (mission, icon) {console.log("--------onMissionIconUpdated-------")}, - onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")} + onMissionClosed: function (mission) {console.log("--------onMissionClosed-------")}, + onMissionLabelUpdated: function (mission) {console.log("--------onMissionLabelUpdated-------")} }; console.log("registerMissionListener") var listenerid = missionManager.registerMissionListener(listener); @@ -145,7 +148,7 @@ getMissionInfo(deviceId: string, missionId: number, callback: AsyncCallback<M Obtains the information about a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -157,16 +160,21 @@ Obtains the information about a given mission. This API uses an asynchronous cal | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionInfo](#missioninfo)> | Yes| Callback used to return the mission information obtained.| + | callback | AsyncCallback<[MissionInfo](js-apis-inner-application-missionInfo.md)> | Yes| Callback used to return the mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions=missionManager.getMissionInfos("",10).catch(function(err){console.log(err);}); missionManager.getMissionInfo("", allMissions[0].missionId, (error, mission) => { - console.log("getMissionInfo is called, error.code = " + error.code) + if (error.code) { + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("mission.missionId = " + mission.missionId); console.log("mission.runningState = " + mission.runningState); console.log("mission.lockedState = " + mission.lockedState); @@ -183,7 +191,7 @@ getMissionInfo(deviceId: string, missionId: number): Promise<MissionInfo>; Obtains the information about a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -200,11 +208,11 @@ Obtains the information about a given mission. This API uses a promise to return | Type| Description| | -------- | -------- | - | Promise<[MissionInfo](#missioninfo)> | Promise used to return the mission information obtained.| + | Promise<[MissionInfo](js-apis-inner-application-missionInfo.md)> | Promise used to return the mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var mission = missionManager.getMissionInfo("", 10).catch(function (err){ @@ -219,7 +227,7 @@ getMissionInfos(deviceId: string, numMax: number, callback: AsyncCallback<Arr Obtains information about all missions. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -231,15 +239,19 @@ Obtains information about all missions. This API uses an asynchronous callback t | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | numMax | number | Yes| Maximum number of missions whose information can be obtained.| - | callback | AsyncCallback<Array<[MissionInfo](#missioninfo)>> | Yes| Callback used to return the array of mission information obtained.| + | callback | AsyncCallback<Array<[MissionInfo](js-apis-inner-application-missionInfo.md)>> | Yes| Callback used to return the array of mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); }) @@ -252,7 +264,7 @@ getMissionInfos(deviceId: string, numMax: number): Promise<Array<MissionIn Obtains information about all missions. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -269,11 +281,11 @@ Obtains information about all missions. This API uses a promise to return the re | Type| Description| | -------- | -------- | - | Promise<Array<[MissionInfo](#missioninfo)>> | Promise used to return the array of mission information obtained.| + | Promise<Array<[MissionInfo](js-apis-inner-application-missionInfo.md)>> | Promise used to return the array of mission information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions = missionManager.getMissionInfos("", 10).catch(function (err){ @@ -288,7 +300,7 @@ getMissionSnapShot(deviceId: string, missionId: number, callback: AsyncCallback& Obtains the snapshot of a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -300,22 +312,30 @@ Obtains the snapshot of a given mission. This API uses an asynchronous callback | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); + if (error.code) { + console.log("getMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("bundleName = " + snapshot.ability.bundleName); }) }) ``` @@ -327,7 +347,7 @@ getMissionSnapShot(deviceId: string, missionId: number): Promise<MissionSnaps Obtains the snapshot of a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -344,11 +364,11 @@ Obtains the snapshot of a given mission. This API uses a promise to return the r | Type| Description| | -------- | -------- | - | Promise<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Promise used to return the snapshot information obtained.| + | Promise<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Promise used to return the snapshot information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -370,7 +390,7 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number, callback: A Obtains the low-resolution snapshot of a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -382,22 +402,30 @@ Obtains the low-resolution snapshot of a given mission. This API uses an asynchr | -------- | -------- | -------- | -------- | | deviceId | string | Yes| Device ID. It is a null string by default for the local device.| | missionId | number | Yes| Mission ID.| - | callback | AsyncCallback<[MissionSnapshot](js-apis-application-MissionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| + | callback | AsyncCallback<[MissionSnapshot](js-apis-inner-application-missionSnapshot.md)> | Yes| Callback used to return the snapshot information obtained.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; missionManager.getLowResolutionMissionSnapShot("", id, (error, snapshot) => { - console.log("getLowResolutionMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); + if (error.code) { + console.log("getLowResolutionMissionSnapShot failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("bundleName = " + snapshot.ability.bundleName); }) }) ``` @@ -409,7 +437,7 @@ getLowResolutionMissionSnapShot(deviceId: string, missionId: number): Promise\ { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -490,7 +522,7 @@ lockMission(missionId: number): Promise<void>; Locks a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -510,7 +542,7 @@ Locks a given mission. This API uses a promise to return the result. **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; missionManager.getMissionInfos("",10).then(function(res){ @@ -532,7 +564,7 @@ unlockMission(missionId: number, callback: AsyncCallback<void>): void; Unlocks a given mission. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -547,11 +579,15 @@ Unlocks a given mission. This API uses an asynchronous callback to return the re **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -569,7 +605,7 @@ unlockMission(missionId: number): Promise<void>; Unlocks a given mission. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -589,7 +625,7 @@ Unlocks a given mission. This API uses a promise to return the result. **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -615,7 +651,7 @@ clearMission(missionId: number, callback: AsyncCallback<void>): void; Clears a given mission, regardless of whether it is locked. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -630,11 +666,15 @@ Clears a given mission, regardless of whether it is locked. This API uses an asy **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -652,7 +692,7 @@ clearMission(missionId: number): Promise<void>; Clears a given mission, regardless of whether it is locked. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -672,7 +712,7 @@ Clears a given mission, regardless of whether it is locked. This API uses a prom **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -695,7 +735,7 @@ clearAllMissions(callback: AsyncCallback<void>): void; Clears all unlocked missions. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -703,7 +743,7 @@ Clears all unlocked missions. This API uses an asynchronous callback to return t **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.clearAllMissions().then(() => { @@ -718,7 +758,7 @@ clearAllMissions(): Promise<void>; Clears all unlocked missions. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -732,7 +772,7 @@ Clears all unlocked missions. This API uses a promise to return the result. **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.clearAllMissions().catch(function (err){ console.log(err); @@ -746,7 +786,7 @@ moveMissionToFront(missionId: number, callback: AsyncCallback<void>): void Switches a given mission to the foreground. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -761,11 +801,15 @@ Switches a given mission to the foreground. This API uses an asynchronous callba **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -783,7 +827,7 @@ moveMissionToFront(missionId: number, options: StartOptions, callback: AsyncCall Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -794,16 +838,20 @@ Switches a given mission to the foreground, with the startup parameters for the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| - | options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | options | [StartOptions](js-apis-application-startOptions.md) | Yes| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } console.log("size = " + missions.length); console.log("missions = " + JSON.stringify(missions)); var id = missions[0].missionId; @@ -821,7 +869,7 @@ moveMissionToFront(missionId: number, options?: StartOptions): Promise<void&g Switches a given mission to the foreground, with the startup parameters for the switching specified. This API uses a promise to return the result. -**Required permission**: ohos.permission.MANAGE_MISSIONS +**Required permissions**: ohos.permission.MANAGE_MISSIONS **System capability**: SystemCapability.Ability.AbilityRuntime.Mission @@ -832,7 +880,7 @@ Switches a given mission to the foreground, with the startup parameters for the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | missionId | number | Yes| Mission ID.| - | options | [StartOptions](js-apis-application-StartOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| + | options | [StartOptions](js-apis-application-startOptions.md) | No| Startup parameters, which are used to specify the window mode and device ID for switching the mission to the foreground.| **Return value** @@ -842,7 +890,7 @@ Switches a given mission to the foreground, with the startup parameters for the **Example** - ```js + ```ts import missionManager from '@ohos.application.missionManager' var allMissions; @@ -857,22 +905,3 @@ Switches a given mission to the foreground, with the startup parameters for the console.log(err); }); ``` - -## MissionInfo - -Describes the mission information. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| missionId | number | Yes| Yes| Mission ID.| -| runningState | number | Yes| Yes| Running state of the mission.| -| lockedState | boolean | Yes| Yes| Locked state of the mission.| -| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| -| want | [Want](js-apis-application-Want.md) | Yes| Yes| **Want** information of the mission.| -| label | string | Yes| Yes| Label of the mission.| -| iconPath | string | Yes| Yes| Path of the mission icon.| -| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| diff --git a/en/application-dev/reference/apis/js-apis-application-quickFixManager.md b/en/application-dev/reference/apis/js-apis-application-quickFixManager.md deleted file mode 100644 index 5abe8c19658d484fb335efc0d3fe8e2aa49bdc48..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-application-quickFixManager.md +++ /dev/null @@ -1,186 +0,0 @@ -# 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-service-extension-ability.md b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md similarity index 65% rename from en/application-dev/reference/apis/js-apis-service-extension-ability.md rename to en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md index 388b4308555f8dc061bfa62da40fd4dc5d97cfee..beb8c007b0fa58bdae058ac554c96425bdf93bd5 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-application-serviceExtensionAbility.md @@ -1,16 +1,19 @@ -# ServiceExtensionAbility +# @ohos.application.ServiceExtensionAbility (ServiceExtensionAbility) The **ServiceExtensionAbility** module provides APIs for Service Extension abilities. > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are supported since API version 9 and are deprecated in versions later than API version 9. You are advised to use [@ohos.app.ability.ServiceExtensionAbility](js-apis-app-ability-serviceExtensionAbility.md) instead. +> +> 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. ## Modules to Import -``` -import ServiceExtension from '@ohos.application.ServiceExtensionAbility'; +```ts +import ServiceExtensionAbility from '@ohos.application.ServiceExtensionAbility'; ``` ## Required Permissions @@ -23,9 +26,9 @@ None. **System API**: This is a system API and cannot be called by third-party applications. -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| context | [ServiceExtensionContext](js-apis-service-extension-context.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| +| context | [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md) | Yes| No| Service Extension context, which is inherited from **ExtensionContext**.| ## ServiceExtensionAbility.onCreate @@ -40,13 +43,13 @@ Called when a Service Extension ability is created to initialize the service log **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onCreate(want) { console.log('onCreate, want:' + want.abilityName); @@ -67,7 +70,7 @@ Called when this Service Extension ability is destroyed to clear resources. **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onDestroy() { console.log('onDestroy'); @@ -88,14 +91,14 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Information related to this Service Extension ability, including the ability name and bundle name.| - | startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| +| startId | number | Yes| Number of ability start times. The initial value is **1**, and the value is automatically incremented for each ability started.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onRequest(want, startId) { console.log('onRequest, want:' + want.abilityName); @@ -116,19 +119,19 @@ Called after **onCreate** is invoked when a Service Extension ability is started **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Return value** - | Type| Description| - | -------- | -------- | - | rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| +| Type| Description| +| -------- | -------- | +| rpc.RemoteObject | A **RemoteObject** object used for communication with the client.| **Example** - ```js + ```ts import rpc from '@ohos.rpc' class StubTest extends rpc.RemoteObject{ constructor(des) { @@ -158,13 +161,13 @@ Called when this Service Extension ability is disconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onDisconnect(want) { console.log('onDisconnect, want:' + want.abilityName); @@ -184,13 +187,13 @@ Called when this Service Extension ability is reconnected. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want |[Want](js-apis-application-Want.md)| Yes| Information related to this Service Extension ability, including the ability name and bundle name.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md)| Yes| Want information related to this Service Extension ability, including the ability name and bundle name.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onReconnect(want) { console.log('onReconnect, want:' + want.abilityName); @@ -202,7 +205,7 @@ Called when this Service Extension ability is reconnected. onConfigurationUpdated(config: Configuration): void; - Called when the configuration of this Service Extension ability is updated. +Called when the configuration of this Service Extension ability is updated. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -210,13 +213,13 @@ onConfigurationUpdated(config: Configuration): void; **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [Configuration](js-apis-application-configuration.md) | Yes| New configuration.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { onConfigurationUpdated(config) { console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); @@ -236,13 +239,13 @@ Dumps the client information. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | params | Array\ | Yes| Parameters in the form of a command.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| params | Array\ | Yes| Parameters in the form of a command.| **Example** - ```js + ```ts class ServiceExt extends ServiceExtension { dump(params) { console.log('dump, params:' + JSON.stringify(params)); diff --git a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md index 57a313f1f600607c143aaec48205a482221ba355..5fc9b0999940310b10bf7b4e7227d5651153eb50 100644 --- a/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @@ -1,14 +1,15 @@ -# StaticSubscriberExtensionAbility +# @ohos.application.StaticSubscriberExtensionAbility (StaticSubscriberExtensionAbility) The **StaticSubscriberExtensionAbility** module provides Extension abilities for static subscribers. > **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. ## Modules to Import -``` +```ts import StaticSubscriberExtensionAbility from '@ohos.application.StaticSubscriberExtensionAbility' ``` @@ -24,13 +25,13 @@ Callback of the common event of a static subscriber. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | event | [CommonEventData](js-apis-commonEvent.md#commoneventdata) | Yes| Common event of a static subscriber.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | [CommonEventData](js-apis-commonEventManager.md#commoneventdata) | Yes| Common event of a static subscriber.| **Example** - ```js + ```ts var StaticSubscriberExtensionAbility = requireNapi("application.StaticSubscriberExtensionAbility") { onReceiveEvent(event){ diff --git a/en/application-dev/reference/apis/js-apis-testRunner.md b/en/application-dev/reference/apis/js-apis-application-testRunner.md similarity index 94% rename from en/application-dev/reference/apis/js-apis-testRunner.md rename to en/application-dev/reference/apis/js-apis-application-testRunner.md index 403ec97e87bce272b6b4ee45568eb6a23590ab31..d2146524c0c5249374e21c95762438d35dc48c35 100644 --- a/en/application-dev/reference/apis/js-apis-testRunner.md +++ b/en/application-dev/reference/apis/js-apis-application-testRunner.md @@ -1,4 +1,4 @@ -# TestRunner +# @ohos.application.testRunner (TestRunner) The **TestRunner** module provides a test framework. You can use the APIs of this module to prepare the unit test environment and run test cases. @@ -10,7 +10,7 @@ To implement your own unit test framework, extend this class and override its AP ## Modules to Import -```js +```ts import TestRunner from '@ohos.application.testRunner' ``` @@ -24,7 +24,7 @@ Prepares the unit test environment to run test cases. **Example** -```js +```ts export default class UserTestRunner implements TestRunner { onPrepare() { console.log("Trigger onPrepare") @@ -45,7 +45,7 @@ Runs test cases. **Example** -```js +```ts export default class UserTestRunner implements TestRunner { onPrepare() {} onRun() { diff --git a/en/application-dev/reference/apis/js-apis-appmanager.md b/en/application-dev/reference/apis/js-apis-appmanager.md deleted file mode 100644 index 3d93bdf33a527668c4c1c98ac4cfd8611ea9010a..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-appmanager.md +++ /dev/null @@ -1,1000 +0,0 @@ -# appManager - -The **appManager** module implements application management. You can use the APIs of this module to query whether the application is undergoing a stability test, whether the application is running on a RAM constrained device, the memory size of the application, and information about the running process. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -```js -import app from '@ohos.application.appManager'; -``` - -## appManager.isRunningInStabilityTest8+ - -static isRunningInStabilityTest(callback: AsyncCallback<boolean>): void - -Checks whether this application is undergoing a stability test. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest((err, flag) => { - console.log('startAbility result:' + JSON.stringify(err)); - }) - ``` - - -## appManager.isRunningInStabilityTest8+ - -static isRunningInStabilityTest(): Promise<boolean> - -Checks whether this application is undergoing a stability test. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. If the application is undergoing a stability test, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - import app from '@ohos.application.appManager'; - app.isRunningInStabilityTest().then((flag) => { - console.log('success:' + JSON.stringify(flag)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - - -## appManager.isRamConstrainedDevice - -isRamConstrainedDevice(): Promise\; - -Checks whether this application is running on a RAM constrained device. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - app.isRamConstrainedDevice().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.isRamConstrainedDevice - -isRamConstrainedDevice(callback: AsyncCallback\): void; - -Checks whether this application is running on a RAM constrained device. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | No| Callback used to return whether the application is running on a RAM constrained device. If the application is running on a RAM constrained device, **true** will be returned; otherwise, **false** will be returned.| - -**Example** - - ```js - app.isRamConstrainedDevice((err, data) => { - console.log('startAbility result failed:' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` - -## appManager.getAppMemorySize - -getAppMemorySize(): Promise\; - -Obtains the memory size of this application. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<number> | Size of the application memory.| - -**Example** - - ```js - app.getAppMemorySize().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.getAppMemorySize - -getAppMemorySize(callback: AsyncCallback\): void; - -Obtains the memory size of this application. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<number> | No| Size of the application memory.| - -**Example** - - ```js - app.getAppMemorySize((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` -## appManager.getProcessRunningInfos(deprecated) - -getProcessRunningInfos(): Promise\>; - -Obtains information about the running processes. This API uses a promise to return the result. - -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9) instead. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\> | Promise used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInfos().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.getProcessRunningInfos(deprecated) - -getProcessRunningInfos(callback: AsyncCallback\>): void; - -Obtains information about the running processes. This API uses an asynchronous callback to return the result. - -> This API is deprecated since API version 9. You are advised to use [appManager.getProcessRunningInformation9+](#appmanagergetprocessrunninginformation9-1) instead. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | No| Callback used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInfos((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` - -## appManager.getProcessRunningInformation9+ - -getProcessRunningInformation(): Promise\>; - -Obtains information about the running processes. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\> | Promise used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInformation().then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` - -## appManager.getProcessRunningInformation9+ - -getProcessRunningInformation(callback: AsyncCallback\>): void; - -Obtains information about the running processes. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | No| Callback used to return the process information.| - -**Example** - - ```js - app.getProcessRunningInformation((err, data) => { - console.log('startAbility result failed :' + JSON.stringify(err)); - console.log('startAbility result success:' + JSON.stringify(data)); - }) - ``` - -## appManager.registerApplicationStateObserver8+ - -registerApplicationStateObserver(observer: ApplicationStateObserver): number; - -Registers an observer to listen for the state changes of all applications. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| - -**Example** - - ```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); - - ``` - -## appManager.registerApplicationStateObserver9+ - -registerApplicationStateObserver(observer: ApplicationStateObserver, bundleNameList: Array\): number; - -Registers an observer to listen for the state changes of a specified application. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observer | [ApplicationStateObserver](#applicationstateobserver) | No| Numeric code of the observer.| -| bundleNameList | Array | No| **bundleName** array of the application. A maximum of 128 bundle names can be passed.| - -**Example** - - ```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - var bundleNameList = ['bundleName1', 'bundleName2']; - const observerCode = app.registerApplicationStateObserver(applicationStateObserver, bundleNameList); - console.log('-------- observerCode: ---------', observerCode); - - ``` -## appManager.unregisterApplicationStateObserver8+ - -unregisterApplicationStateObserver(observerId: number, callback: AsyncCallback\): void; - -Deregisters the application state observer. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| -| callback | AsyncCallback\ | No| Callback used to return the result.| - -**Example** - - ```js - var observerId = 100; - - function unregisterApplicationStateObserverCallback(err) { - if (err) { - console.log('------------ unregisterApplicationStateObserverCallback ------------', err); - } - } - app.unregisterApplicationStateObserver(observerId, unregisterApplicationStateObserverCallback); - ``` - -## appManager.unregisterApplicationStateObserver8+ - -unregisterApplicationStateObserver(observerId: number): Promise\; - -Deregisters the application state observer. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.RUNNING_STATE_OBSERVER - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| observerId | number | No| Numeric code of the observer.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Example** - - ```js - var observerId = 100; - - app.unregisterApplicationStateObserver(observerId) - .then((data) => { - console.log('----------- unregisterApplicationStateObserver success ----------', data); - }) - .catch((err) => { - console.log('----------- unregisterApplicationStateObserver fail ----------', err); - }) - ``` - -## appManager.getForegroundApplications8+ - -getForegroundApplications(callback: AsyncCallback\>): void; - -Obtains applications that are running in the foreground. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback\> | No| Callback used to return the application state data.| - -**Example** - - ```js - function getForegroundApplicationsCallback(err, data) { - if (err) { - console.log('--------- getForegroundApplicationsCallback fail ---------', err); - } else { - console.log('--------- getForegroundApplicationsCallback success ---------', data) - } - } - app.getForegroundApplications(getForegroundApplicationsCallback); - ``` - -## appManager.getForegroundApplications8+ - -getForegroundApplications(): Promise\>; - -Obtains applications that are running in the foreground. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_RUNNING_INFO - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\> | Promise used to return the application state data.| - -**Example** - - ```js - app.getForegroundApplications() - .then((data) => { - console.log('--------- getForegroundApplications success -------', data); - }) - .catch((err) => { - console.log('--------- getForegroundApplications fail -------', err); - }) - ``` - -## appManager.killProcessWithAccount8+ - -killProcessWithAccount(bundleName: string, accountId: number): Promise\ - -Kills a process by bundle name and account ID. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - -**Example** - -```js -var bundleName = 'bundleName'; -var accountId = 0; -app.killProcessWithAccount(bundleName, accountId) - .then((data) => { - console.log('------------ killProcessWithAccount success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessWithAccount fail ------------', err); - }) -``` - - -## appManager.killProcessWithAccount8+ - -killProcessWithAccount(bundleName: string, accountId: number, callback: AsyncCallback\): void - -Kills a process by bundle name and account ID. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS and ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | bundleName | string | Yes| Bundle name of an application.| - | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| - | callback | AsyncCallback\ | Yes| Callback used to return the result.| - -**Example** - -```js -var bundleName = 'bundleName'; -var accountId = 0; -function killProcessWithAccountCallback(err, data) { - if (err) { - console.log('------------- killProcessWithAccountCallback fail, err: --------------', err); - } else { - console.log('------------- killProcessWithAccountCallback success, data: --------------', data); - } -} -app.killProcessWithAccount(bundleName, accountId, killProcessWithAccountCallback); -``` - -## appManager.killProcessesByBundleName8+ - -killProcessesByBundleName(bundleName: string, callback: AsyncCallback\); - -Kills a process by bundle name. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| -| callback | AsyncCallback\ | No| Callback used to return the result.| - -**Example** - - ```js - var bundleName = 'bundleName'; - function killProcessesByBundleNameCallback(err, data) { - if (err) { - console.log('------------- killProcessesByBundleNameCallback fail, err: --------------', err); - } else { - console.log('------------- killProcessesByBundleNameCallback success, data: --------------', data); - } - } - app.killProcessesByBundleName(bundleName, killProcessesByBundleNameCallback); - ``` - -## appManager.killProcessesByBundleName8+ - -killProcessesByBundleName(bundleName: string): Promise\; - -Kills a process by bundle name. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.CLEAN_BACKGROUND_PROCESSES - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Example** - - ```js -var bundleName = 'bundleName'; -app.killProcessesByBundleName(bundleName) - .then((data) => { - console.log('------------ killProcessesByBundleName success ------------', data); - }) - .catch((err) => { - console.log('------------ killProcessesByBundleName fail ------------', err); - }) - - ``` - -## appManager.clearUpApplicationData8+ - -clearUpApplicationData(bundleName: string, callback: AsyncCallback\); - -Clears application data by bundle name. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| -| callback | AsyncCallback\ | No| Callback used to return the result.| - -**Example** - - ```js - var bundleName = 'bundleName'; - function clearUpApplicationDataCallback(err, data) { - if (err) { - console.log('------------- clearUpApplicationDataCallback fail, err: --------------', err); - } else { - console.log('------------- clearUpApplicationDataCallback success, data: --------------', data); - } - } - app.clearUpApplicationData(bundleName, clearUpApplicationDataCallback); - - ``` - -## appManager.clearUpApplicationData8+ - -clearUpApplicationData(bundleName: string): Promise\; - -Clears application data by bundle name. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.CLEAN_APPLICATION_DATA - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| bundleName | string | No| Bundle name of an application.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise\ | Promise used to return the result.| - -**Example** - - ```js - var bundleName = 'bundleName'; - app.clearUpApplicationData(bundleName) - .then((data) => { - console.log('------------ clearUpApplicationData success ------------', data); - }) - .catch((err) => { - console.log('------------ clearUpApplicationData fail ------------', err); - }) - - ``` - -## ApplicationStateObserver.onForegroundApplicationChanged8+ - -onForegroundApplicationChanged(appStateData: AppStateData): void; - -Called when the application state changes. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| appStateData | [AppStateData](#appstatedata) | No| Information about the application whose state is changed.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); - -``` - -## ApplicationStateObserver.onAbilityStateChanged8+ - -onAbilityStateChanged(abilityStateData: AbilityStateData): void; - -Called when the ability state changes. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| abilityStateData | [AbilityStateData](#abilitystatedata) | No| Information about the ability whose state is changed.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## ApplicationStateObserver.onProcessCreated8+ - -onProcessCreated(processData: ProcessData): void; - -Called when a process is created. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| processData | [ProcessData](#processdata) | No| Process information.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## ApplicationStateObserver.onProcessDied8+ - -onProcessDied(processData: ProcessData): void; - -Called when a process is terminated. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| processData | [ProcessData](#processdata) | No| Process information.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## ApplicationStateObserver.onProcessStateChanged9+ - - onProcessStateChanged(processData: ProcessData): void; - -Called when the process state changes. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| processData | [ProcessData](#processdata) | No| Process information.| - -**Example** - -```js - var applicationStateObserver = { - onForegroundApplicationChanged(appStateData) { - console.log('------------ onForegroundApplicationChanged -----------', appStateData); - }, - onAbilityStateChanged(abilityStateData) { - console.log('------------ onAbilityStateChanged -----------', abilityStateData); - }, - onProcessCreated(processData) { - console.log('------------ onProcessCreated -----------', processData); - }, - onProcessDied(processData) { - console.log('------------ onProcessDied -----------', processData); - }, - onProcessStateChanged(processData) { - console.log('------------ onProcessStateChanged -----------', processData); - } - } - const observerCode = app.registerApplicationStateObserver(applicationStateObserver); - console.log('-------- observerCode: ---------', observerCode); -``` - -## AppStateData - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| bundleName8+ | Read only | string | No | Bundle name of an application. | -| uid8+ | Read only | number | No | User ID.| -| state8+ | Read only | number | No | Application state.| - -## AbilityStateData - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name of an application. | -| abilityName8+ | string | Yes | No | Ability name. | -| uid8+ | number | Yes | No | User ID. | -| state8+ | number | Yes | No | Ability state. | -| moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | -| abilityType8+ | string | Yes | No | Ability type. | - -## ProcessData - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| pid8+ | number | Yes | No | Process ID. | -| bundleName8+ | string | Yes | No | Bundle name of an application. | -| uid8+ | number | Yes | No | User ID. | -| isContinuousTask9+ | boolean | Yes | No | Whether the process is a continuous task. | -| isKeepAlive9+ | boolean | Yes | No | Whether the process remains active. | - -## ProcessRunningInfo - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| pid8+ | Read only | number | No | Process ID. | -| uid8+ | Read only | number | No | User ID.| -| processName8+ | Read only | string | No | Process name.| -| bundleNames8+ | Read only | Array\ | No | **bundleName** array in the running processes.| - -## ApplicationStateObserver - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Type | Readable| Writable| Description | -| ----------------------- | ---------| ---- | ---- | ------------------------- | -| [onForegroundApplicationChanged8+](#applicationstateobserveronforegroundapplicationchanged8) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | -| [onAbilityStateChanged8+](#applicationstateobserveronabilitystatechanged8) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | -| [onProcessCreated8+](#applicationstateobserveronprocesscreated8) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | -| [onProcessDied8+](#applicationstateobserveronprocessdied8) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | - -## ProcessRunningInformation - -Defines the process running information. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable/Writable| Type | Mandatory| Description | -| ----------- | -------- | -------------------- | ---- | ------------------------------------------------------------ | -| pid9+ | Read only | number | No | Process ID. | -| uid9+ | Read only | number | No | User ID.| -| processName9+ | Read only | string | No | Process name.| -| bundleNames9+ | Read only | Array\ | No | **bundleName** array in the running processes.| - -## ApplicationState9+ - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | State indicating that the application is being created. | -| STATE_FOREGROUND | 2 | State indicating that the application is running in the foreground. | -| STATE_ACTIVE | 3 | State indicating that the application is active. | -| STATE_BACKGROUND | 4 | State indicating that the application is running in the background. | -| STATE_DESTROY | 5 | State indicating that the application is destroyed. | - -## ProcessState9+ - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -| Name | Value | Description | -| -------------------- | --- | --------------------------------- | -| STATE_CREATE | 1 | State indicating that the process is being created. | -| STATE_FOREGROUND | 2 | State indicating that the process is running in the foreground. | -| STATE_ACTIVE | 3 | State indicating that the process is active. | -| STATE_BACKGROUND | 4 | State indicating that the process is running in the background. | -| STATE_DESTROY | 5 | State indicating that the process is destroyed. | diff --git a/en/application-dev/reference/apis/js-apis-arraylist.md b/en/application-dev/reference/apis/js-apis-arraylist.md index d98422b678ea658dbe4092dc9247ca4bb551f5cc..ebf538d3b5508c1ee26aa77d4db01aa995239c3b 100644 --- a/en/application-dev/reference/apis/js-apis-arraylist.md +++ b/en/application-dev/reference/apis/js-apis-arraylist.md @@ -1,7 +1,6 @@ -# Linear Container ArrayList +# @ohos.util.ArrayList (Linear Container ArrayList) > **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. **ArrayList** is a linear data structure that is implemented based on arrays. **ArrayList** can dynamically adjust the capacity based on project requirements. It increases the capacity by 50% each time. @@ -42,7 +41,7 @@ A constructor used to create an **ArrayList** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -52,11 +51,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let arrayList = new ArrayList(); -try { - let arrayList2 = ArrayList(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -82,7 +76,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -90,21 +84,16 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er **Example** - ```ts - let arrayList = new ArrayList(); - let result = arrayList.add("a"); - let result1 = arrayList.add(1); - let b = [1, 2, 3]; - let result2 = arrayList.add(b); - let c = {name: "Dylon", age: "13"}; - let result3 = arrayList.add(c); - let result4 = arrayList.add(false); - try { - arrayList.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. - } catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); - } - ``` +```ts +let arrayList = new ArrayList(); +let result = arrayList.add("a"); +let result1 = arrayList.add(1); +let b = [1, 2, 3]; +let result2 = arrayList.add(b); +let c = {name: "Dylon", age: "13"}; +let result3 = arrayList.add(c); +let result4 = arrayList.add(false); +``` ### insert @@ -123,12 +112,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -137,21 +126,6 @@ let arrayList = new ArrayList(); arrayList.insert("A", 0); arrayList.insert(0, 1); arrayList.insert(true, 2); -try { - arrayList.insert.bind({}, 1, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - let res = arrayList.insert (8, 11); // Trigger an out-of-bounds exception. -} catch (err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - let res = arrayList.insert("a", "b"); // Trigger a type exception. -} catch (err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -176,7 +150,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -189,11 +163,6 @@ let arrayList = new ArrayList(); let result = arrayList.has("squirrel"); arrayList.add("squirrel"); let result1 = arrayList.has("squirrel"); -try { - arrayList.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -218,7 +187,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -236,11 +205,6 @@ arrayList.add(1); arrayList.add(2); arrayList.add(4); let result = arrayList.getIndexOf(2); -try { - arrayList.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -265,7 +229,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -283,11 +247,6 @@ arrayList.add(1); arrayList.add(2); arrayList.add(4); let result = arrayList.getLastIndexOf(2); -try { - arrayList.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -312,12 +271,12 @@ Removes an element with the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -329,21 +288,6 @@ arrayList.add(5); arrayList.add(2); arrayList.add(4); let result = arrayList.removeByIndex(2); -try { - arrayList.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByIndex("a"); // Trigger a type exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByIndex(8); // Trigger an out-of-bounds exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -368,7 +312,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -383,11 +327,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.remove(2); -try { - arrayList.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByRange @@ -407,12 +346,12 @@ Removes from this container all of the elements within a range, including the el **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByRange method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -423,21 +362,11 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.removeByRange(2, 4); -try { - arrayList.removeByRange.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.removeByRange(8, 4); // Trigger an out-of-bounds exception. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -448,7 +377,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for the replacement.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -461,7 +390,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -481,18 +410,11 @@ arrayList.replaceAllElements((value: number, index: number)=> { arrayList.replaceAllElements((value: number, index: number) => { return value = value - 2; }); -try { - arrayList.replaceAllElements.bind({}, (value: number, index: number)=> { - return value = 2 * value; - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, +forEach(callbackFn: (value: T, index?: number, arrlist?: ArrayList<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -503,7 +425,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -516,7 +438,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -533,13 +455,6 @@ arrayList.add(4); arrayList.forEach((value, index) => { console.log(`value:${value}`, index); }); -try { - arrayList.forEach.bind({}, (value, index) => { - console.log(`value:${value}`, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### sort @@ -565,7 +480,7 @@ comparator **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -582,11 +497,6 @@ arrayList.add(4); arrayList.sort((a: number, b: number) => a - b); arrayList.sort((a: number, b: number) => b - a); arrayList.sort(); -try { - arrayList.sort.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### subArrayList @@ -612,12 +522,12 @@ Obtains elements within a range in this container, including the element at the **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The subArrayList method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -630,16 +540,6 @@ arrayList.add(4); let result1 = arrayList.subArrayList(2, 4); let result2 = arrayList.subArrayList(4, 3); let result3 = arrayList.subArrayList(2, 6); -try { - arrayList.subArrayList.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - arrayList.subArrayList(6, 4); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -652,7 +552,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -667,11 +567,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.clear(); -try { - arrayList.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -691,7 +586,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -706,11 +601,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.clone(); -try { - arrayList.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getCapacity @@ -729,7 +619,7 @@ Obtains the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -744,11 +634,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.getCapacity(); -try { - arrayList.getCapacity.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -767,7 +652,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -782,11 +667,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.convertToArray(); -try { - arrayList.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -805,7 +685,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -820,11 +700,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); let result = arrayList.isEmpty(); -try { - arrayList.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### increaseCapacityTo @@ -843,7 +718,7 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -859,11 +734,6 @@ arrayList.add(5); arrayList.add(4); arrayList.increaseCapacityTo(2); arrayList.increaseCapacityTo(8); -try { - arrayList.increaseCapacityTo.bind({}, 5)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### trimToCurrentLength @@ -876,7 +746,7 @@ Trims the capacity of this container to its current length. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -891,11 +761,6 @@ arrayList.add(4); arrayList.add(5); arrayList.add(4); arrayList.trimToCurrentLength(); -try { - arrayList.trimToCurrentLength.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -914,7 +779,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -941,9 +806,4 @@ while(temp != undefined) { console.log(`value:${temp}`); temp = iter.next().value; } -try { - arrayList[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 8296185a2866ab0148e68ee56e52eea68e708892..a992de969d6b6e673b89eff8f14f28f5328ce017 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -1,4 +1,4 @@ -# Audio Management +# @ohos.multimedia.audio (Audio Management) The **Audio** module provides basic audio management capabilities, including audio volume and audio device management, and audio data collection and rendering. @@ -9,9 +9,9 @@ This module provides the following common audio-related functions: - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. - [TonePlayer](#toneplayer9): tone player, used to manage and play Dual Tone Multi Frequency (DTMF) tones, such as dial tones and ringback tones. -> **NOTE** +> **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 @@ -23,9 +23,9 @@ import audio from '@ohos.multimedia.audio'; | Name | Type | Readable | Writable| Description | | --------------------------------------- | ----------| ---- | ---- | ------------------ | -| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | -| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | -| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | +| LOCAL_NETWORK_ID9+ | string | Yes | No | Network ID of the local device.
This is a system API.
**System capability**: SystemCapability.Multimedia.Audio.Device | +| DEFAULT_VOLUME_GROUP_ID9+ | number | Yes | No | Default volume group ID.
**System capability**: SystemCapability.Multimedia.Audio.Volume | +| DEFAULT_INTERRUPT_GROUP_ID9+ | number | Yes | No | Default audio interruption group ID.
**System capability**: SystemCapability.Multimedia.Audio.Interrupt | **Example** @@ -74,7 +74,10 @@ Creates an **AudioRenderer** instance. This API uses an asynchronous callback to **Example** ```js +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; import audio from '@ohos.multimedia.audio'; + let audioStreamInfo = { samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, channels: audio.AudioChannel.CHANNEL_1, @@ -126,6 +129,8 @@ Creates an **AudioRenderer** instance. This API uses a promise to return the res **Example** ```js +import featureAbility from '@ohos.ability.featureAbility'; +import fileio from '@ohos.fileio'; import audio from '@ohos.multimedia.audio'; let audioStreamInfo = { @@ -279,9 +284,9 @@ Creates a **TonePlayer** instance. This API uses an asynchronous callback to ret import audio from '@ohos.multimedia.audio'; let audioRendererInfo = { - "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags": 0 + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 } let tonePlayer; @@ -322,13 +327,14 @@ Creates a **TonePlayer** instance. This API uses a promise to return the result. ```js import audio from '@ohos.multimedia.audio'; -async function createTonePlayer(){ +let tonePlayer; +async function createTonePlayerBefore(){ let audioRendererInfo = { - "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags": 0 + content : audio.ContentType.CONTENT_TYPE_SONIFICATION, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 } - let tonePlayer = await audio.createTonePlayer(audioRendererInfo); + tonePlayer = await audio.createTonePlayer(audioRendererInfo); } ``` @@ -338,7 +344,7 @@ Enumerates the audio stream types. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | VOICE_CALL8+ | 0 | Audio stream for voice calls.| | RINGTONE | 2 | Audio stream for ringtones. | @@ -354,7 +360,7 @@ Enumerates the result types of audio interruption requests. **System API**: This is a system API. -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | INTERRUPT_REQUEST_GRANT | 0 | The audio interruption request is accepted.| | INTERRUPT_REQUEST_REJECT | 1 | The audio interruption request is denied. There may be a stream with a higher priority.| @@ -365,7 +371,7 @@ Enumerates the audio interruption modes. **System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------- | ------ | ---------- | | SHARE_MODE | 0 | Shared mode.| | INDEPENDENT_MODE | 1 | Independent mode.| @@ -376,7 +382,7 @@ Enumerates the audio device flags. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value | Description | +| Name | Value | Description | | ------------------------------- | ------ | ------------------------------------------------- | | NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API. | | OUTPUT_DEVICES_FLAG | 1 | Output device.| @@ -392,7 +398,7 @@ Enumerates the audio device roles. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | ------------- | ------ | -------------- | | INPUT_DEVICE | 1 | Input role.| | OUTPUT_DEVICE | 2 | Output role.| @@ -403,7 +409,7 @@ Enumerates the audio device types. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------| ------ | --------------------------------------------------------- | | INVALID | 0 | Invalid device. | | EARPIECE | 1 | Earpiece. | @@ -422,7 +428,7 @@ Enumerates the device types used for communication. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | ------------- | ------ | -------------| | SPEAKER | 2 | Speaker. | @@ -432,7 +438,7 @@ Enumerates the ringer modes. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | ------------------- | ------ | ---------- | | RINGER_MODE_SILENT | 0 | Silent mode.| | RINGER_MODE_VIBRATE | 1 | Vibration mode.| @@ -444,7 +450,7 @@ Enumerates the audio sample formats. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | -------------------------- | | SAMPLE_FORMAT_INVALID | -1 | Invalid format. | | SAMPLE_FORMAT_U8 | 0 | Unsigned 8-bit integer. | @@ -459,15 +465,15 @@ Enumerates the audio error codes. **System capability**: SystemCapability.Multimedia.Audio.Core -| Error Message | Error Code | Error Description | +| Name | Value | Description | | ---------------------| --------| ----------------- | | ERROR_INVALID_PARAM | 6800101 | Invalid parameter. | | ERROR_NO_MEMORY | 6800102 | Memory allocation failure. | | ERROR_ILLEGAL_STATE | 6800103 | Unsupported state. | -| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | +| ERROR_UNSUPPORTED | 6800104 | Unsupported parameter value. | | ERROR_TIMEOUT | 6800105 | Processing timeout. | | ERROR_STREAM_LIMIT | 6800201 | Too many audio streams.| -| ERROR_SYSTEM | 6800301 | System error. | +| ERROR_SYSTEM | 6800301 | System error. | ## AudioChannel8+ @@ -475,18 +481,18 @@ Enumerates the audio channels. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------- | -------- | -------- | | CHANNEL_1 | 0x1 << 0 | Mono.| | CHANNEL_2 | 0x1 << 1 | Dual-channel.| ## AudioSamplingRate8+ -Enumerates the audio sampling rates. +Enumerates the audio sampling rates. The sampling rates supported vary according to the device in use. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------- | ------ | --------------- | | SAMPLE_RATE_8000 | 8000 | The sampling rate is 8000. | | SAMPLE_RATE_11025 | 11025 | The sampling rate is 11025.| @@ -506,7 +512,7 @@ Enumerates the audio encoding types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------------- | ------ | --------- | | ENCODING_TYPE_INVALID | -1 | Invalid. | | ENCODING_TYPE_RAW | 0 | PCM encoding.| @@ -517,7 +523,7 @@ Enumerates the audio content types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | ---------- | | CONTENT_TYPE_UNKNOWN | 0 | Unknown content.| | CONTENT_TYPE_SPEECH | 1 | Speech. | @@ -532,7 +538,7 @@ Enumerates the audio stream usage. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------------------------------------| ------ | ---------- | | STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| | STREAM_USAGE_MEDIA | 1 | Used for media. | @@ -548,7 +554,7 @@ Enumerates the audio interruption request types. **System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------- | ------ | ------------------------- | | INTERRUPT_REQUEST_TYPE_DEFAULT | 0 | Default type, which can be used to interrupt audio requests. | @@ -558,7 +564,7 @@ Enumerates the audio states. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | -------------- | ------ | ---------------- | | STATE_INVALID | -1 | Invalid state. | | STATE_NEW | 0 | Creating instance state.| @@ -574,7 +580,7 @@ Enumerates the audio renderer rates. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | ------------------ | ------ | ---------- | | RENDER_RATE_NORMAL | 0 | Normal rate.| | RENDER_RATE_DOUBLE | 1 | Double rate. | @@ -586,7 +592,7 @@ Enumerates the audio interruption types. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | -------------------- | ------ | ---------------------- | | INTERRUPT_TYPE_BEGIN | 1 | Audio interruption started.| | INTERRUPT_TYPE_END | 2 | Audio interruption ended.| @@ -597,7 +603,7 @@ Enumerates the types of force that causes audio interruption. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | --------------- | ------ | ------------------------------------ | | INTERRUPT_FORCE | 0 | Forced action taken by the system. | | INTERRUPT_SHARE | 1 | The application can choose to take action or ignore.| @@ -608,7 +614,7 @@ Enumerates the hints provided along with audio interruption. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------------------- | ------ | -------------------------------------------- | | INTERRUPT_HINT_NONE8+ | 0 | None. | | INTERRUPT_HINT_RESUME | 1 | Resume the playback. | @@ -636,7 +642,7 @@ Describes audio renderer information. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ------------- | --------------------------- | ---- | ---------------- | | content | [ContentType](#contenttype) | Yes | Audio content type. | | usage | [StreamUsage](#streamusage) | Yes | Audio stream usage.| @@ -661,7 +667,7 @@ Describes audio renderer configurations. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ------------ | ---------------------------------------- | ---- | ---------------- | | streamInfo | [AudioStreamInfo](#audiostreaminfo8) | Yes | Audio stream information.| | rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| @@ -672,7 +678,7 @@ Describes the interruption event received by the application when playback is in **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Mandatory| Description | +| Name | Type |Mandatory | Description | | --------- | ------------------------------------------ | ---- | ------------------------------------ | | eventType | [InterruptType](#interrupttype) | Yes | Whether the interruption has started or ended. | | forceType | [InterruptForceType](#interruptforcetype9) | Yes | Whether the interruption is taken by the system or to be taken by the application.| @@ -686,7 +692,7 @@ Describes the event received by the application when the volume is changed. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory | Description | | ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | | volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | | volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| @@ -701,7 +707,7 @@ Describes the event received by the application when the microphone mute status **System capability**: SystemCapability.Multimedia.Audio.Device | Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| ---------- | ----------------------------------- | ---- |-------------------------------------------------------- | | mute | boolean | Yes | Mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | ## ConnectType9+ @@ -712,7 +718,7 @@ Enumerates the types of connected devices. **System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Default Value| Description | +| Name | Value | Description | | :------------------------------ | :----- | :--------------------- | | CONNECT_TYPE_LOCAL | 1 | Local device. | | CONNECT_TYPE_DISTRIBUTED | 2 | Distributed device. | @@ -738,7 +744,7 @@ Describes the volume group information. | networkId9+ | string | Yes | No | Network ID of the device. | | groupId9+ | number | Yes | No | Group ID of the device.| | mappingId9+ | number | Yes | No | Group mapping ID.| -| groupName9+ | number | Yes | No | Group name.| +| groupName9+ | string | Yes | No | Group name.| | type9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| ## DeviceChangeAction @@ -758,7 +764,7 @@ Enumerates the device connection statuses. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Default Value| Description | +| Name | Value | Description | | :--------- | :----- | :------------- | | CONNECT | 0 | Connected. | | DISCONNECT | 1 | Disconnected.| @@ -791,7 +797,7 @@ Enumerates the audio source types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | +| Name | Value | Description | | :------------------------------------------- | :----- | :--------------------- | | SOURCE_TYPE_INVALID | -1 | Invalid audio source. | | SOURCE_TYPE_MIC | 0 | Mic source. | @@ -804,7 +810,7 @@ Enumerates the audio scenes. **System capability**: SystemCapability.Multimedia.Audio.Communication -| Name | Default Value| Description | +| Name | Value | Description | | :--------------------- | :----- | :-------------------------------------------- | | AUDIO_SCENE_DEFAULT | 0 | Default audio scene. | | AUDIO_SCENE_RINGING | 1 | Ringing audio scene.
This is a system API.| @@ -959,7 +965,6 @@ Sets an audio scene. This API uses an asynchronous callback to return the result **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { console.error(`Failed to set the audio scene mode.​ ${err}`); @@ -994,7 +999,6 @@ Sets an audio scene. This API uses a promise to return the result. **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { console.info('Promise returned to indicate a successful setting of the audio scene mode.'); }).catch ((err) => { @@ -1019,7 +1023,6 @@ Obtains the audio scene. This API uses an asynchronous callback to return the re **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.getAudioScene((err, value) => { if (err) { console.error(`Failed to obtain the audio scene mode.​ ${err}`); @@ -1046,7 +1049,6 @@ Obtains the audio scene. This API uses a promise to return the result. **Example** ```js -let audioManager = audio.getAudioManager(); audioManager.getAudioScene().then((value) => { console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); }).catch ((err) => { @@ -1096,179 +1098,20 @@ Obtains an **AudioRoutingManager** instance. let audioRoutingManager = audioManager.getRoutingManager(); ``` -## AudioVolumeManager9+ - -Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance. - -### getVolumeGroupInfos9+ - -getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void - -Obtains the volume groups. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | -| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| - -**Example** -```js -audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); - return; - } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -}); -``` - -### getVolumeGroupInfos9+ - -getVolumeGroupInfos(networkId: string\): Promise - -Obtains the volume groups. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------| ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | - -**Return value** - -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| - -**Example** - -```js -async function getVolumeGroupInfos(){ - let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); - console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) -} -``` - -### getVolumeGroupManager9+ - -getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void - -Obtains the audio group manager. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| groupId | number | Yes | Volume group ID. | -| callback | AsyncCallback< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Yes | Callback used to return the audio group manager.| - -**Example** - -```js -let groupid = audio.DEFAULT_VOLUME_GROUP_ID; -audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { - if (err) { - console.error(`Failed to obtain the volume group infos list. ${err}`); - return; - } - console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -}); - -``` - -### getVolumeGroupManager9+ - -getVolumeGroupManager(groupId: number\): Promise - -Obtains the audio group manager. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------- | ---- | ---------------- | -| groupId | number | Yes | Volume group ID. | - -**Return value** - -| Type | Description | -| ------------------- | ----------------------------- | -| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.| - -**Example** - -```js -let groupid = audio.DEFAULT_VOLUME_GROUP_ID; -let audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); -console.info('Callback invoked to indicate that the volume group infos list is obtained.'); -``` - -### on('volumeChange')9+ - -on(type: 'volumeChange', callback: Callback\): void - -Subscribes to system volume change events. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.| -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | - -**Error codes** - -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). - -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | - -**Example** - -```js -audioVolumeManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); -}); -``` - -## AudioVolumeGroupManager9+ - -Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume - -### setVolume9+ +### setVolume(deprecated) setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System API**: This is a system API. - **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1282,7 +1125,7 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { if (err) { console.error(`Failed to set the volume. ${err}`); return; @@ -1291,18 +1134,20 @@ audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { }); ``` -### setVolume9+ +### setVolume(deprecated) setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -**System API**: This is a system API. - **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1321,17 +1166,21 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { +audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { console.info('Promise returned to indicate a successful volume setting.'); }); ``` -### getVolume9+ +### getVolume(deprecated) getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the volume of a stream. 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 [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1344,7 +1193,7 @@ Obtains the volume of a stream. This API uses an asynchronous callback to return **Example** ```js -audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the volume. ${err}`); return; @@ -1353,12 +1202,16 @@ audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { }); ``` -### getVolume9+ +### getVolume(deprecated) getVolume(volumeType: AudioVolumeType): Promise<number> Obtains the volume of a stream. 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 [getVolume](#getvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1376,17 +1229,21 @@ Obtains the volume of a stream. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value}.`); +audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value} .`); }); ``` -### getMinVolume9+ +### getMinVolume(deprecated) getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the minimum volume allowed for a stream. 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 [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1399,7 +1256,7 @@ Obtains the minimum volume allowed for a stream. This API uses an asynchronous c **Example** ```js -audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the minimum volume. ${err}`); return; @@ -1408,12 +1265,16 @@ audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) = }); ``` -### getMinVolume9+ +### getMinVolume(deprecated) getMinVolume(volumeType: AudioVolumeType): Promise<number> Obtains the minimum volume allowed for a stream. 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 [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1431,17 +1292,21 @@ Obtains the minimum volume allowed for a stream. This API uses a promise to retu **Example** ```js -audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); +audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); }); ``` -### getMaxVolume9+ +### getMaxVolume(deprecated) getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void Obtains the maximum volume allowed for a stream. 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 [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1454,7 +1319,7 @@ Obtains the maximum volume allowed for a stream. This API uses an asynchronous c **Example** ```js -audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the maximum volume. ${err}`); return; @@ -1463,12 +1328,16 @@ audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) = }); ``` -### getMaxVolume9+ +### getMaxVolume(deprecated) getMaxVolume(volumeType: AudioVolumeType): Promise<number> Obtains the maximum volume allowed for a stream. 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 [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1486,22 +1355,20 @@ Obtains the maximum volume allowed for a stream. This API uses a promise to retu **Example** ```js -audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { +audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { console.info('Promised returned to indicate that the maximum volume is obtained.'); }); ``` -### mute9+ +### mute(deprecated) mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. - -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -1516,7 +1383,7 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** ```js -audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { if (err) { console.error(`Failed to mute the stream. ${err}`); return; @@ -1525,17 +1392,15 @@ audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { }); ``` -### mute9+ +### mute(deprecated) mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> Mutes or unmutes a stream. This API uses a promise to return the result. -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. - -**System API**: This is a system API. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [mute](#mute9) in **AudioVolumeGroupManager**. **System capability**: SystemCapability.Multimedia.Audio.Volume @@ -1554,18 +1419,23 @@ This permission is required only for muting or unmuting the ringer when **volume **Example** + ```js -audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { +audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { console.info('Promise returned to indicate that the stream is muted.'); }); ``` -### isMute9+ +### isMute(deprecated) isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void Checks whether a stream is muted. 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 [isMute](#ismute9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1578,21 +1448,25 @@ Checks whether a stream is muted. This API uses an asynchronous callback to retu **Example** ```js -audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { console.error(`Failed to obtain the mute status. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); + console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` -### isMute9+ +### isMute(deprecated) isMute(volumeType: AudioVolumeType): Promise<boolean> Checks whether a stream is muted. 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 [isMute](#ismute9) in **AudioVolumeGroupManager**. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -1610,24 +1484,89 @@ Checks whether a stream is muted. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { +audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` -### setRingerMode9+ +### isActive(deprecated) + +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void + +Checks whether a stream is active. 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 [isActive](#isactive9) in **AudioStreamManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| + +**Example** + +```js +audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); +}); +``` + +### isActive(deprecated) + +isActive(volumeType: AudioVolumeType): Promise<boolean> + +Checks whether a stream is active. 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 [isActive](#isactive9) in **AudioStreamManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| + +**Example** + +```js +audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); +}); +``` + +### setRingerMode(deprecated) setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void Sets the ringer 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1639,7 +1578,7 @@ This permission is required only for muting or unmuting the ringer. **Example** ```js -audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { console.error(`Failed to set the ringer mode.​ ${err}`); return; @@ -1648,19 +1587,21 @@ audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (e }); ``` -### setRingerMode9+ +### setRingerMode(deprecated) setRingerMode(mode: AudioRingMode): Promise<void> Sets the ringer 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. + **Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY This permission is required only for muting or unmuting the ringer. -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1677,18 +1618,22 @@ This permission is required only for muting or unmuting the ringer. **Example** ```js -audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { +audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { console.info('Promise returned to indicate a successful setting of the ringer mode.'); }); ``` -### getRingerMode9+ +### getRingerMode(deprecated) getRingerMode(callback: AsyncCallback<AudioRingMode>): void Obtains the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** @@ -1699,7 +1644,7 @@ Obtains the ringer mode. This API uses an asynchronous callback to return the re **Example** ```js -audioVolumeGroupManager.getRingerMode((err, value) => { +audioManager.getRingerMode((err, value) => { if (err) { console.error(`Failed to obtain the ringer mode.​ ${err}`); return; @@ -1708,13 +1653,17 @@ audioVolumeGroupManager.getRingerMode((err, value) => { }); ``` -### getRingerMode9+ +### getRingerMode(deprecated) getRingerMode(): Promise<AudioRingMode> Obtains the ringer mode. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Communication **Return value** @@ -1725,85 +1674,123 @@ Obtains the ringer mode. This API uses a promise to return the result. **Example** ```js -audioVolumeGroupManager.getRingerMode().then((value) => { +audioManager.getRingerMode().then((value) => { console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); }); ``` -### on('ringerModeChange')9+ +### getDevices(deprecated) -on(type: 'ringerModeChange', callback: Callback\): void +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void -Subscribes to ringer mode change events. +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| -**Error codes** +**Example** +```js +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { + if (err) { + console.error(`Failed to obtain the device list. ${err}`); + return; + } + console.info('Callback invoked to indicate that the device list is obtained.'); +}); +``` -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +### getDevices(deprecated) -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> + +Obtains the audio devices with a specific flag. 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 [getDevices](#getdevices9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| **Example** ```js -audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); ``` -### setMicrophoneMute9+ -setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void +### setDeviceActive(deprecated) -Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void -**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG +Sets a device to the active state. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | --------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -audioVolumeGroupManager.setMicrophoneMute(true, (err) => { +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { if (err) { - console.error(`Failed to mute the microphone. ${err}`); + console.error(`Failed to set the active status of the device. ${err}`); return; } - console.info('Callback invoked to indicate that the microphone is muted.'); + console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` -### setMicrophoneMute9+ +### setDeviceActive(deprecated) -setMicrophoneMute(mute: boolean): Promise<void> +setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> -Mutes or unmutes the microphone. This API uses a promise to return the result. +Sets a device to the active state. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | --------------------------------------------- | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** @@ -1813,552 +1800,539 @@ Mutes or unmutes the microphone. This API uses a promise to return the result. **Example** + ```js -audioVolumeGroupManager.setMicrophoneMute(true).then(() => { - console.info('Promise returned to indicate that the microphone is muted.'); +audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); }); ``` -### isMicrophoneMute9+ +### isDeviceActive(deprecated) -isMicrophoneMute(callback: AsyncCallback<boolean>): void +isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void -Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +Checks whether a device is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** ```js -audioVolumeGroupManager.isMicrophoneMute((err, value) => { +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { if (err) { - console.error(`Failed to obtain the mute status of the microphone. ${err}`); + console.error(`Failed to obtain the active status of the device. ${err}`); return; } - console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### isMicrophoneMute9+ +### isDeviceActive(deprecated) -isMicrophoneMute(): Promise<boolean> +isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> -Checks whether the microphone is muted. This API uses a promise to return the result. +Checks whether a device is active. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------ | +| deviceType | [ActiveDeviceType](#activedevicetypedeprecated) | Yes | Audio device type.| **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| **Example** ```js -audioVolumeGroupManager.isMicrophoneMute().then((value) => { - console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); ``` -### on('micStateChange')9+ +### setMicrophoneMute(deprecated) -on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -Subscribes to system mic state change events. +Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'micStateChange'** means the system mic state change event, which is triggered when the system mic state changes.| -| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed micr state. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | -**Error codes** +**Example** -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +```js +audioManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; + } + console.info('Callback invoked to indicate that the microphone is muted.'); +}); +``` -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +### setMicrophoneMute(deprecated) + +setMicrophoneMute(mute: boolean): Promise<void> + +Mutes or unmutes the microphone. 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 [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioVolumeGroupManager.on('micStateChange', (micStateChange) => { - console.info(`Current microphone status is: ${micStateChange.mute} `); +audioManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -## AudioStreamManager9+ +### isMicrophoneMute(deprecated) -Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. +isMicrophoneMute(callback: AsyncCallback<boolean>): void -### getCurrentAudioRendererInfoArray9+ +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. -Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MICROPHONE -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------- | -------- | --------------------------- | -| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { - console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); +audioManager.isMicrophoneMute((err, value) => { if (err) { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - } else { - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } + console.error(`Failed to obtain the mute status of the microphone. ${err}`); + return; } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### getCurrentAudioRendererInfoArray9+ +### isMicrophoneMute(deprecated) -getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> +isMicrophoneMute(): Promise<boolean> -Obtains the information about the current audio renderer. This API uses a promise to return the result. +Checks whether the microphone is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. + +**Required permissions**: ohos.permission.MICROPHONE + +**System capability**: SystemCapability.Multimedia.Audio.Device **Return value** -| Type | Description | -| ---------------------------------------------------------------------------------| --------------------------------------- | -| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -async function getCurrentAudioRendererInfoArray(){ - await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); - }); -} +audioManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +}); ``` -### getCurrentAudioCapturerInfoArray9+ +### on('volumeChange')(deprecated) -getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void +on(type: 'volumeChange', callback: Callback\): void -Obtains the information about the current audio capturer. 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 [on](#on9) in **AudioVolumeManager**. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Subscribes to system volume change events. + +**System API**: This is a system API. + +Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | -| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Example** ```js -audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { - console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); - if (err) { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - } else { - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - } +audioManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### getCurrentAudioCapturerInfoArray9+ +### on('ringerModeChange')(deprecated) -getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> +on(type: 'ringerModeChange', callback: Callback\): void -Obtains the information about the current audio capturer. This API uses a promise to return the result. +Subscribes to ringer mode change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('ringerModeChange')](#onringermodechange9) in **AudioVolumeGroupManager**. -**Return value** +**System API**: This is a system API. -| Type | Description | -| -----------------------------------------------------------------------------| ----------------------------------- | -| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode change event. | **Example** ```js -async function getCurrentAudioCapturerInfoArray(){ - await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - } - } - }).catch((err) => { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); - }); -} +audioManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); ``` -### on('audioRendererChange')9+ - -on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void - -Subscribes to audio renderer change events. +### on('deviceChange')(deprecated) -**System capability**: SystemCapability.Multimedia.Audio.Renderer +on(type: 'deviceChange', callback: Callback): void -**Parameters** +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -| Name | Type | Mandatory | Description | -| -------- | ---------- | --------- | ------------------------------------------------------------------------ | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | -| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioRoutingManager**. -**Error codes** +**System capability**: SystemCapability.Multimedia.Audio.Device -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**Parameters** -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | **Example** ```js -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); - } - } +audioManager.on('deviceChange', (deviceChanged) => { + console.info(`device change type : ${deviceChanged.type} `); + console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); + console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); }); ``` -### off('audioRendererChange')9+ - -off(type: "audioRendererChange"): void - -Unsubscribes from audio renderer change events. +### off('deviceChange')(deprecated) -**System capability**: SystemCapability.Multimedia.Audio.Renderer +off(type: 'deviceChange', callback?: Callback): void -**Parameters** +Unsubscribes from device change events. -| Name | Type | Mandatory| Description | -| -------- | ------- | ---- | ---------------- | -| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [off](#off9) in **AudioRoutingManager**. -**Error codes** +**System capability**: SystemCapability.Multimedia.Audio.Device -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**Parameters** -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | **Example** ```js -audioStreamManager.off('audioRendererChange'); -console.info('######### RendererChange Off is called #########'); +audioManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); +}); ``` -### on('audioCapturerChange')9+ +### on('interrupt')(deprecated) -on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void +on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void -Subscribes to audio capturer change events. +Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------- | --------- | ----------------------------------------------------------------------- | -| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | -| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | Yes | Callback invoked for the audio interruption event. | **Example** ```js -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to gain the audio focus starts.'); + console.info(`Focus gain event: ${InterruptAction} `); + } + if (InterruptAction.actionType === 1) { + console.info('An audio interruption event starts.'); + console.info(`Audio interruption event: ${InterruptAction} `); } }); ``` -### off('audioCapturerChange')9+ +### off('interrupt')(deprecated) -off(type: "audioCapturerChange"): void; +off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void -Unsubscribes from audio capturer change events. +Unsubscribes from audio interruption events. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | --- | ------------------------------------------------------------- | -| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application.| +| interrupt | AudioInterrupt | Yes | Audio interruption event type. | +| callback | Callback<[InterruptAction](#interruptactiondeprecated)> | No | Callback invoked for the audio interruption event. | **Example** ```js -audioStreamManager.off('audioCapturerChange'); -console.info('######### CapturerChange Off is called #########'); - +let interAudioInterrupt = { + streamUsage:2, + contentType:0, + pauseWhenDucked:true +}; +audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { + if (InterruptAction.actionType === 0) { + console.info('An event to release the audio focus starts.'); + console.info(`Focus release event: ${InterruptAction} `); + } +}); ``` -### isActive9+ +## AudioVolumeManager9+ -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +Implements audio volume management. Before calling an API in **AudioVolumeManager**, you must use [getVolumeManager](#getvolumemanager9) to obtain an **AudioVolumeManager** instance. -Checks whether a stream is active. This API uses an asynchronous callback to return the result. +### getVolumeGroupInfos9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +getVolumeGroupInfos(networkId: string, callback: AsyncCallback\): void + +Obtains the volume groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | +| callback | AsyncCallback<[VolumeGroupInfos](#volumegroupinfos9)> | Yes | Callback used to return the volume group information array.| **Example** - ```js -audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { +audioVolumeManager.getVolumeGroupInfos(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); ``` -### isActive9+ +### getVolumeGroupInfos9+ -isActive(volumeType: AudioVolumeType): Promise<boolean> +getVolumeGroupInfos(networkId: string\): Promise -Checks whether a stream is active. This API uses a promise to return the result. +Obtains the volume groups. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------- | ---- | ------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------| ---- | -------------------- | +| networkId | string | Yes | Network ID of the device. The network ID of the local device is **audio.LOCAL_NETWORK_ID**. | **Return value** -| Type | Description | -| ---------------------- | -------------------------------------------------------- | -| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| **Example** ```js -audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); -}); -``` - -## AudioRoutingManager9+ - -Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. +async function getVolumeGroupInfos(){ + let volumegroupinfos = await audio.getAudioManager().getVolumeManager().getVolumeGroupInfos(audio.LOCAL_NETWORK_ID); + console.info('Promise returned to indicate that the volumeGroup list is obtained.'+JSON.stringify(volumegroupinfos)) +} +``` -### getDevices9+ +### getVolumeGroupManager9+ -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +getVolumeGroupManager(groupId: number, callback: AsyncCallback\): void -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +Obtains the audio group manager. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| +| groupId | number | Yes | Volume group ID. | +| callback | AsyncCallback<[AudioVolumeGroupManager](#audiovolumegroupmanager9)> | Yes | Callback used to return the audio group manager.| **Example** ```js -audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +audioVolumeManager.getVolumeGroupManager(groupid, (err, value) => { if (err) { - console.error(`Failed to obtain the device list. ${err}`); + console.error(`Failed to obtain the volume group infos list. ${err}`); return; } - console.info('Callback invoked to indicate that the device list is obtained.'); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); }); + ``` -### getDevices9+ +### getVolumeGroupManager9+ -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +getVolumeGroupManager(groupId: number\): Promise -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +Obtains the audio group manager. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ---------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------- | ---- | ---------------- | +| groupId | number | Yes | Volume group ID. | **Return value** -| Type | Description | -| ------------------------------------------------------------ | ------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise< [AudioVolumeGroupManager](#audiovolumegroupmanager9) > | Promise used to return the audio group manager.| **Example** ```js -audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); -}); +let groupid = audio.DEFAULT_VOLUME_GROUP_ID; +let audioVolumeGroupManager; +getVolumeGroupManager(); +async function getVolumeGroupManager(){ + audioVolumeGroupManager = await audioVolumeManager.getVolumeGroupManager(groupid); + console.info('Callback invoked to indicate that the volume group infos list is obtained.'); +} + ``` -### on9+ +### on('volumeChange')9+ -on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void +on(type: 'volumeChange', callback: Callback\): void -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Subscribes to system volume change events. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when the system volume changes.| +| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the system volume change event. | **Error codes** @@ -2366,2108 +2340,2320 @@ For details about the error codes, see [Audio Error Codes](../errorcodes/errorco | ID| Error Message| | ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +| 6800101 | if input parameter value error | **Example** ```js -audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { - console.info('device change type : ' + deviceChanged.type); - console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); - console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); +audioVolumeManager.on('volumeChange', (volumeEvent) => { + console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); + console.info(`Volume level: ${volumeEvent.volume} `); + console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); }); ``` -### off9+ +## AudioVolumeGroupManager9+ -off(type: 'deviceChange', callback?: Callback): void +Manages the volume of an audio group. Before calling any API in **AudioVolumeGroupManager**, you must use [getVolumeGroupManager](#getvolumegroupmanager9) to obtain an **AudioVolumeGroupManager** instance. -Unsubscribes from device change events. +### setVolume9+ -**System capability**: SystemCapability.Multimedia.Audio.Device +setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void -**Parameters** +Sets the volume for a stream. This API uses an asynchronous callback to return the result. -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**Error codes** +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**System API**: This is a system API. -| ID| Error Message| -| ------- | --------------------------------------------| -| 6800101 | if input parameter value error. | +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -audioRoutingManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { + if (err) { + console.error(`Failed to set the volume. ${err}`); + return; + } + console.info('Callback invoked to indicate a successful volume setting.'); }); ``` -### selectInputDevice9+ - -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void - -Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +### setVolume9+ -**Example** -```js -let inputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; +setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> -async function selectInputDevice(){ - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select input devices result callback: SUCCESS'); } - }); -} -``` +Sets the volume for a stream. This API uses a promise to return the result. -### selectInputDevice9+ +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. **System API**: This is a system API. -Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let inputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.INPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function getRoutingManager(){ - audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { - console.info('Select input devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioVolumeGroupManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { + console.info('Promise returned to indicate a successful volume setting.'); +}); ``` -### setCommunicationDevice9+ +### getVolume9+ -setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void +getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Sets a communication device to the active state. This API uses an asynchronous callback to return the result. +Obtains the volume of a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ------------------------------------- | ---- | ------------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the volume.| **Example** ```js -audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to set the active status of the device. ${err}`); + console.error(`Failed to obtain the volume. ${err}`); return; } - console.info('Callback invoked to indicate that the device is set to the active status.'); + console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` -### setCommunicationDevice9+ +### getVolume9+ -setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> +getVolume(volumeType: AudioVolumeType): Promise<number> -Sets a communication device to the active state. This API uses a promise to return the result. +Obtains the volume of a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ----------------------------------------------------- | ---- | ------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ------------------- | ------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the volume.| **Example** ```js -audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); +audioVolumeGroupManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the volume is obtained ${value}.`); }); ``` -### isCommunicationDeviceActive9+ +### getMinVolume9+ -isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void +getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -Checks whether a communication device is active. This API uses an asynchronous callback to return the result. +Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ------------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume.| **Example** ```js -audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); + console.error(`Failed to obtain the minimum volume. ${err}`); return; } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); + console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); }); ``` -### isCommunicationDeviceActive9+ +### getMinVolume9+ -isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> +getMinVolume(volumeType: AudioVolumeType): Promise<number> -Checks whether a communication device is active. This API uses a promise to return the result. +Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------------------- | ---- | ------------------ | -| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| ---------------------- | ------------------------------- | -| Promise<boolean> | Promise used to return the active state of the device.| +| Type | Description | +| --------------------- | ------------------------- | +| Promise<number> | Promise used to return the minimum volume.| **Example** ```js -audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); +audioVolumeGroupManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promised returned to indicate that the minimum volume is obtained ${value}.`); }); ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +### getMaxVolume9+ -Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void -**System API**: This is a system API. +Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ---------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume.| **Example** + ```js -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectOutputDevice(){ - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices result callback: SUCCESS'); } - }); -} +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { + if (err) { + console.error(`Failed to obtain the maximum volume. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); +}); ``` -### selectOutputDevice9+ - -selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> +### getMaxVolume9+ -**System API**: This is a system API. +getMaxVolume(volumeType: AudioVolumeType): Promise<number> -Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. +Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------- | ----------------------------- | +| Promise<number> | Promise used to return the maximum volume.| **Example** ```js -let outputAudioDeviceDescriptor =[{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function selectOutputDevice(){ - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }); -} +audioVolumeGroupManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { + console.info('Promised returned to indicate that the maximum volume is obtained.'); +}); ``` -### selectOutputDeviceByFilter9+ +### mute9+ -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void +mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void -**System API**: This is a system API. +Mutes or unmutes a stream. This API uses an asynchronous callback to return the result. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** -```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; -async function selectOutputDeviceByFilter(){ - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices by filter result callback: SUCCESS'); } - }); -} +```js +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { + if (err) { + console.error(`Failed to mute the stream. ${err}`); + return; + } + console.info('Callback invoked to indicate that the stream is muted.'); +}); ``` -### selectOutputDeviceByFilter9+ +### mute9+ -selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> +mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> -**System API**: This is a system API. +Mutes or unmutes a stream. This API uses a promise to return the result. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory| Description | -| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | -| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | -| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite.| **Return value** -| Type | Description | -| --------------------- | --------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ----------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; -let outputAudioDeviceDescriptor = [{ - "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, - "networkId":audio.LOCAL_NETWORK_ID, - "interruptGroupId":1, - "volumeGroupId":1 }]; - -async function selectOutputDeviceByFilter(){ - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices by filter result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }) -} +audioVolumeGroupManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { + console.info('Promise returned to indicate that the stream is muted.'); +}); ``` -## AudioRendererChangeInfoArray9+ - -Defines an **AudioRenderChangeInfo** array, which is read-only. +### isMute9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -## AudioRendererChangeInfo9+ +Checks whether a stream is muted. This API uses an asynchronous callback to return the result. -Describes the audio renderer change event. +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Parameters** -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | -| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ----------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| **Example** ```js -import audio from '@ohos.multimedia.audio'; - -let audioStreamManager; -let resultFlag = false; -let audioManager = audio.getAudioManager(); - -audioManager.getStreamManager((err, data) => { +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error(`Get AudioStream Manager : ERROR : ${err}`); - } else { - audioStreamManager = data; - console.info('Get AudioStream Manager : Success'); + console.error(`Failed to obtain the mute status. ${err}`); + return; } + console.info(`Callback invoked to indicate that the mute status of the stream is obtained ${value}.`); }); +``` -audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - console.info(`## RendererChange on is called for ${i} ##`); - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); - console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); - console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); - let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for ${i} is: ${resultFlag}`); - } - } +### isMute9+ + +isMute(volumeType: AudioVolumeType): Promise<boolean> + +Checks whether a stream is muted. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type.| + +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite.| + +**Example** + +```js +audioVolumeGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); }); ``` +### setRingerMode9+ -## AudioCapturerChangeInfoArray9+ +setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void -Defines an **AudioCapturerChangeInfo** array, which is read-only. +Sets the ringer mode. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -## AudioCapturerChangeInfo9+ +This permission is required only for muting or unmuting the ringer. -Describes the audio capturer change event. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Readable | Writable | Description | -| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | -| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------ | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -import audio from '@ohos.multimedia.audio'; - -const audioManager = audio.getAudioManager(); -let audioStreamManager; -audioManager.getStreamManager((err, data) => { +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -let resultFlag = false; -audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##`); - console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } - if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { - resultFlag = true; - console.info(`ResultFlag for element ${i} is: ${resultFlag}`); - } + console.error(`Failed to set the ringer mode.​ ${err}`); + return; } + console.info('Callback invoked to indicate a successful setting of the ringer mode.'); }); ``` -## AudioDeviceDescriptors +### setRingerMode9+ -Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. +setRingerMode(mode: AudioRingMode): Promise<void> -## AudioDeviceDescriptor +Sets the ringer mode. This API uses a promise to return the result. -Describes an audio device. +**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -**System capability**: SystemCapability.Multimedia.Audio.Device +This permission is required only for muting or unmuting the ringer. -| Name | Type | Readable | Writable | Description | -| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | -| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | -| id9+ | number | Yes | No | Device ID. | -| name9+ | string | Yes | No | Device name. | -| address9+ | string | Yes | No | Device address. | -| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | -| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | -| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | -| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. | -| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | -| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------- | ---- | -------------- | +| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -import audio from '@ohos.multimedia.audio'; +audioVolumeGroupManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { + console.info('Promise returned to indicate a successful setting of the ringer mode.'); +}); +``` -function displayDeviceProp(value) { - deviceRoleValue = value.deviceRole; - deviceTypeValue = value.deviceType; -} +### getRingerMode9+ -let deviceRoleValue = null; -let deviceTypeValue = null; -const promise = audio.getAudioManager().getDevices(1); -promise.then(function (value) { - console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); - value.forEach(displayDeviceProp); - if (deviceTypeValue != null && deviceRoleValue != null){ - console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); - } else { - console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); +getRingerMode(callback: AsyncCallback<AudioRingMode>): void + +Obtains the ringer mode. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode.| + +**Example** + +```js +audioVolumeGroupManager.getRingerMode((err, value) => { + if (err) { + console.error(`Failed to obtain the ringer mode.​ ${err}`); + return; } + console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` -## AudioRendererFilter9+ +### getRingerMode9+ + +getRingerMode(): Promise<AudioRingMode> + +Obtains the ringer mode. This API uses a promise to return the result. -Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. +**System capability**: SystemCapability.Multimedia.Audio.Volume -**System API**: This is a system API. +**Return value** -| Name | Type | Mandatory | Description | -| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | -| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | -| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| Type | Description | +| ---------------------------------------------- | ------------------------------- | +| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode.| **Example** ```js -let outputAudioRendererFilter = { - "uid":20010041, - "rendererInfo": { - "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, - "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, - "rendererFlags":0 }, - "rendererId":0 }; +audioVolumeGroupManager.getRingerMode().then((value) => { + console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +}); ``` -## AudioRenderer8+ +### on('ringerModeChange')9+ -Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. +on(type: 'ringerModeChange', callback: Callback\): void -### Attributes +Subscribes to ringer mode change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume -| Name | Type | Readable | Writable | Description | -| ------------------ | -------------------------- | -------- | -------- | --------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected.| +| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the system volume change event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let state = audioRenderer.state; +audioVolumeGroupManager.on('ringerModeChange', (ringerMode) => { + console.info(`Updated ringermode: ${ringerMode}`); +}); ``` +### setMicrophoneMute9+ -### getRendererInfo8+ +setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void -getRendererInfo(callback: AsyncCallback): void +Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. -Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -audioRenderer.getRendererInfo((err, rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); +audioVolumeGroupManager.setMicrophoneMute(true, (err) => { + if (err) { + console.error(`Failed to mute the microphone. ${err}`); + return; + } + console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` -### getRendererInfo8+ +### setMicrophoneMute9+ -getRendererInfo(): Promise +setMicrophoneMute(mute: boolean): Promise<void> -Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. +Mutes or unmutes the microphone. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Required permissions**: ohos.permission.MANAGE_AUDIO_CONFIG + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------- | +| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite.| **Return value** -| Type | Description | -| -------------------------------------------------- | ------------------------------------------------ | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.getRendererInfo().then((rendererInfo) => { - console.info('Renderer GetRendererInfo:'); - console.info(`Renderer content: ${rendererInfo.content}`); - console.info(`Renderer usage: ${rendererInfo.usage}`); - console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); +audioVolumeGroupManager.setMicrophoneMute(true).then(() => { + console.info('Promise returned to indicate that the microphone is muted.'); }); ``` -### getStreamInfo8+ +### isMicrophoneMute9+ -getStreamInfo(callback: AsyncCallback): void +isMicrophoneMute(callback: AsyncCallback<boolean>): void -Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioRenderer.getStreamInfo((err, streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +audioVolumeGroupManager.isMicrophoneMute((err, value) => { + if (err) { + console.error(`Failed to obtain the mute status of the microphone. ${err}`); + return; + } + console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### getStreamInfo8+ +### isMicrophoneMute9+ -getStreamInfo(): Promise +isMicrophoneMute(): Promise<boolean> -Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. +Checks whether the microphone is muted. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Volume **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite.| **Example** ```js -audioRenderer.getStreamInfo().then((streamInfo) => { - console.info('Renderer GetStreamInfo:'); - console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Renderer channel: ${streamInfo.channels}`); - console.info(`Renderer format: ${streamInfo.sampleFormat}`); - console.info(`Renderer encoding type: ${streamInfo.encodingType}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioVolumeGroupManager.isMicrophoneMute().then((value) => { + console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); }); +``` + +### on('micStateChange')9+ +on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void + +Subscribes to system microphone state change events. + +Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. + +**System capability**: SystemCapability.Multimedia.Audio.Volume + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'micStateChange'** means the system microphone state change event, which is triggered when the system microphone state changes.| +| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | Yes | Callback used to return the changed microphone state. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | + +**Example** + +```js +audioVolumeGroupManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); +}); ``` -### getAudioStreamId9+ +## AudioStreamManager9+ -getAudioStreamId(callback: AsyncCallback): void +Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. -Obtains the stream ID of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +### getCurrentAudioRendererInfoArray9+ + +getCurrentAudioRendererInfoArray(callback: AsyncCallback<AudioRendererChangeInfoArray>): void + +Obtains the information about the current audio renderer. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | -------- | --------------------------- | +| callback | AsyncCallback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the audio renderer information.| **Example** ```js -audioRenderer.getAudioStreamId((err, streamid) => { - console.info(`Renderer GetStreamId: ${streamid}`); +audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { + console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); + if (err) { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + } else { + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + } }); - ``` -### getAudioStreamId9+ +### getCurrentAudioRendererInfoArray9+ -getAudioStreamId(): Promise +getCurrentAudioRendererInfoArray(): Promise<AudioRendererChangeInfoArray> -Obtains the stream ID of this **AudioRenderer** instance. This API uses a promise to return the result. +Obtains the information about the current audio renderer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| ---------------------------------------------------------------------------------| --------------------------------------- | +| Promise<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Promise used to return the audio renderer information. | **Example** ```js -audioRenderer.getAudioStreamId().then((streamid) => { - console.info(`Renderer getAudioStreamId: ${streamid}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +async function getCurrentAudioRendererInfoArray(){ + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + }); +} ``` -### start8+ +### getCurrentAudioCapturerInfoArray9+ -start(callback: AsyncCallback): void +getCurrentAudioCapturerInfoArray(callback: AsyncCallback<AudioCapturerChangeInfoArray>): void -Starts the renderer. This API uses an asynchronous callback to return the result. +Obtains the information about the current audio capturer. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------- | --------- | -------------------------------------------------------- | +| callback | AsyncCallback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the audio capturer information.| **Example** ```js -audioRenderer.start((err) => { +audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { + console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); if (err) { - console.error('Renderer start failed.'); + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); } else { - console.info('Renderer start success.'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } } }); - ``` -### start8+ +### getCurrentAudioCapturerInfoArray9+ -start(): Promise +getCurrentAudioCapturerInfoArray(): Promise<AudioCapturerChangeInfoArray> -Starts the renderer. This API uses a promise to return the result. +Obtains the information about the current audio capturer. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| -----------------------------------------------------------------------------| ----------------------------------- | +| Promise<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Promise used to return the audio capturer information. | **Example** ```js -audioRenderer.start().then(() => { - console.info('Renderer started'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +async function getCurrentAudioCapturerInfoArray(){ + await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } + } + }).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + }); +} ``` -### pause8+ +### on('audioRendererChange')9+ -pause(callback: AsyncCallback\): void +on(type: "audioRendererChange", callback: Callback<AudioRendererChangeInfoArray>): void -Pauses rendering. This API uses an asynchronous callback to return the result. +Subscribes to audio renderer change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------- | --------- | ------------------------------------------------------------------------ | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes. | +| callback | Callback<[AudioRendererChangeInfoArray](#audiorendererchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.pause((err) => { - if (err) { - console.error('Renderer pause failed'); - } else { - console.info('Renderer paused.'); +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } } }); - ``` -### pause8+ +### off('audioRendererChange')9+ -pause(): Promise\ +off(type: "audioRendererChange"): void -Pauses rendering. This API uses a promise to return the result. +Unsubscribes from audio renderer change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | ---------------- | +| type | string | Yes | Event type. The event `'audioRendererChange'` is triggered when the audio renderer changes.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.pause().then(() => { - console.info('Renderer paused'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - +audioStreamManager.off('audioRendererChange'); +console.info('######### RendererChange Off is called #########'); ``` -### drain8+ +### on('audioCapturerChange')9+ -drain(callback: AsyncCallback\): void +on(type: "audioCapturerChange", callback: Callback<AudioCapturerChangeInfoArray>): void -Drains the playback buffer. This API uses an asynchronous callback to return the result. +Subscribes to audio capturer change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------------------------------------------------------------------- | +| type | string | Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes. | +| callback | Callback<[AudioCapturerChangeInfoArray](#audiocapturerchangeinfoarray9)> | Yes | Callback used to return the result. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.drain((err) => { - if (err) { - console.error('Renderer drain failed'); - } else { - console.info('Renderer drained.'); +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } } }); - ``` -### drain8+ +### off('audioCapturerChange')9+ -drain(): Promise\ +off(type: "audioCapturerChange"): void; -Drains the playback buffer. This API uses a promise to return the result. +Unsubscribes from audio capturer change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -**Return value** +**Parameters** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------- | --- | ------------------------------------------------------------- | +| type | string |Yes | Event type. The event `'audioCapturerChange'` is triggered when the audio capturer changes.| + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -audioRenderer.drain().then(() => { - console.info('Renderer drained successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +audioStreamManager.off('audioCapturerChange'); +console.info('######### CapturerChange Off is called #########'); ``` -### stop8+ +### isActive9+ -stop(callback: AsyncCallback\): void +isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void -Stops rendering. This API uses an asynchronous callback to return the result. +Checks whether a stream is active. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------------------------------------------- | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -audioRenderer.stop((err) => { +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { if (err) { - console.error('Renderer stop failed'); - } else { - console.info('Renderer stopped.'); + console.error(`Failed to obtain the active status of the stream. ${err}`); + return; } + console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); - ``` -### stop8+ +### isActive9+ -stop(): Promise\ +isActive(volumeType: AudioVolumeType): Promise<boolean> -Stops rendering. This API uses a promise to return the result. +Checks whether a stream is active. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------- | ---- | ------------ | +| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream types.| + **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ---------------------- | -------------------------------------------------------- | +| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite.| **Example** ```js -audioRenderer.stop().then(() => { - console.info('Renderer stopped successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioStreamManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { + console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); }); - ``` -### release8+ +## AudioRoutingManager9+ -release(callback: AsyncCallback\): void +Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. -Releases the renderer. This API uses an asynchronous callback to return the result. +### getDevices9+ -**System capability**: SystemCapability.Multimedia.Audio.Renderer +getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void + +Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | -------------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list.| **Example** ```js -audioRenderer.release((err) => { +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { - console.error('Renderer release failed'); - } else { - console.info('Renderer released.'); + console.error(`Failed to obtain the device list. ${err}`); + return; } + console.info('Callback invoked to indicate that the device list is obtained.'); }); - ``` -### release8+ +### getDevices9+ -release(): Promise\ +getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> -Releases the renderer. This API uses a promise to return the result. +Obtains the audio devices with a specific flag. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag.| **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ------------------------------------------------------------ | ------------------------- | +| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list.| **Example** ```js -audioRenderer.release().then(() => { - console.info('Renderer released successfully'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { + console.info('Promise returned to indicate that the device list is obtained.'); }); - ``` -### write8+ +### on9+ -write(buffer: ArrayBuffer, callback: AsyncCallback\): void +on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback): void -Writes the buffer. This API uses an asynchronous callback to return the result. +Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ------------------------------------------------------------ | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory| Description | +| :------- | :--------------------------------------------------- | :--- | :----------------------------------------- | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | +| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data)=> { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`Buffer size: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf, (err, writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } +audioRoutingManager.on('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + console.info('device change type : ' + deviceChanged.type); + console.info('device descriptor size : ' + deviceChanged.deviceDescriptors.length); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceRole); + console.info('device change descriptor : ' + deviceChanged.deviceDescriptors[0].deviceType); }); - ``` -### write8+ +### off9+ -write(buffer: ArrayBuffer): Promise\ +off(type: 'deviceChange', callback?: Callback): void -Writes the buffer. This API uses a promise to return the result. +Unsubscribes from device change events. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Device -**Return value** +**Parameters** -| Type | Description | -| ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected.| +| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID| Error Message| +| ------- | --------------------------------------------| +| 6800101 | if input parameter value error | **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; - }).catch((err) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); - }); -console.info(`BufferSize: ${bufferSize}`); -let context = featureAbility.getContext(); -let path; -async function getCacheDir(){ - path = await context.getCacheDir(); -} -let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; -let ss = fileio.createStreamSync(filePath, 'r'); -let buf = new ArrayBuffer(bufferSize); -ss.readSync(buf); -audioRenderer.write(buf).then((writtenbytes) => { - if (writtenbytes < 0) { - console.error('write failed.'); - } else { - console.info(`Actual written bytes: ${writtenbytes}`); - } -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.off('deviceChange', (deviceChanged) => { + console.info('Should be no callback.'); }); - ``` -### getAudioTime8+ +### selectInputDevice9+ -getAudioTime(callback: AsyncCallback\): void +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. +Selects an audio input device. Only one input device can be selected. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -audioRenderer.getAudioTime((err, timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}); +let inputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.INPUT_DEVICE, + deviceType : audio.DeviceType.EARPIECE, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectInputDevice(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select input devices result callback: SUCCESS'); } + }); +} ``` -### getAudioTime8+ +### selectInputDevice9+ -getAudioTime(): Promise\ +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> -Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio input device. Only one input device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | **Return value** -| Type | Description | -| ---------------- | ------------------------------------- | -| Promise\ | Promise used to return the timestamp. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.getAudioTime().then((timestamp) => { - console.info(`Current timestamp: ${timestamp}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); +let inputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.INPUT_DEVICE, + deviceType : audio.DeviceType.EARPIECE, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function getRoutingManager(){ + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Select input devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` -### getBufferSize8+ +### setCommunicationDevice9+ -getBufferSize(callback: AsyncCallback\): void +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean, callback: AsyncCallback<void>): void -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. +Sets a communication device to the active state. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true, (err) => { if (err) { - console.error('getBufferSize error'); + console.error(`Failed to set the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the device is set to the active status.'); }); - ``` -### getBufferSize8+ +### setCommunicationDevice9+ -getBufferSize(): Promise\ +setCommunicationDevice(deviceType: CommunicationDeviceType, active: boolean): Promise<void> -Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. +Sets a communication device to the active state. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| +| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | **Return value** -| Type | Description | -| ---------------- | --------------------------------------- | -| Promise\ | Promise used to return the buffer size. | +| Type | Description | +| ------------------- | ------------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let bufferSize; -audioRenderer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); - bufferSize = data; -}).catch((err) => { - console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); +audioRoutingManager.setCommunicationDevice(audio.CommunicationDeviceType.SPEAKER, true).then(() => { + console.info('Promise returned to indicate that the device is set to the active status.'); }); - ``` -### setRenderRate8+ +### isCommunicationDeviceActive9+ -setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void +isCommunicationDeviceActive(deviceType: CommunicationDeviceType, callback: AsyncCallback<boolean>): void -Sets the render rate. This API uses an asynchronous callback to return the result. +Checks whether a communication device is active. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | --------- | ----------------------------------- | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device.| **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER, (err, value) => { if (err) { - console.error('Failed to set params'); - } else { - console.info('Callback invoked to indicate a successful render rate setting.'); + console.error(`Failed to obtain the active status of the device. ${err}`); + return; } + console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); - ``` -### setRenderRate8+ +### isCommunicationDeviceActive9+ -setRenderRate(rate: AudioRendererRate): Promise\ +isCommunicationDeviceActive(deviceType: CommunicationDeviceType): Promise<boolean> -Sets the render rate. This API uses a promise to return the result. +Checks whether a communication device is active. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Communication **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ---------------------------------------- | --------- | ------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | ------------------ | +| deviceType | [CommunicationDeviceType](#communicationdevicetype9) | Yes | Communication device type.| **Return value** -| Type | Description | -| -------------- | ---------------------------------- | -| Promise\ | Promise used to return the result. | +| Type | Description | +| ---------------------- | ------------------------------- | +| Promise<boolean> | Promise used to return the active state of the device.| **Example** ```js -audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { - console.info('setRenderRate SUCCESS'); -}).catch((err) => { - console.error(`ERROR: ${err}`); +audioRoutingManager.isCommunicationDeviceActive(audio.CommunicationDeviceType.SPEAKER).then((value) => { + console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); }); - ``` -### getRenderRate8+ +### selectOutputDevice9+ -getRenderRate(callback: AsyncCallback\): void +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Obtains the current render rate. This API uses an asynchronous callback to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -audioRenderer.getRenderRate((err, renderrate) => { - console.info(`getRenderRate: ${renderrate}`); -}); +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); +} ``` -### getRenderRate8+ - -getRenderRate(): Promise\ - -Obtains the current render rate. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Renderer - -**Return value** - -| Type | Description | -| ------------------------------------------------- | --------------------------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | - -**Example** - -```js -audioRenderer.getRenderRate().then((renderRate) => { - console.info(`getRenderRate: ${renderRate}`); -}).catch((err) => { - console.error(`ERROR: ${err}`); -}); - -``` +### selectOutputDevice9+ -### setInterruptMode9+ +selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void> -setInterruptMode(mode: InterruptMode): Promise<void> +**System API**: This is a system API. -Sets the audio interruption mode for the application. This API uses a promise to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| ---- | -------------------------------- | --------- | ------------------------ | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -let mode = 0; -audioRenderer.setInterruptMode(mode).then(data=>{ - console.info('setInterruptMode Success!'); -}).catch((err) => { - console.error(`setInterruptMode Fail: ${err}`); -}); +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDevice(){ + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` -### setInterruptMode9+ +### selectOutputDeviceByFilter9+ -setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | --------- | ----------------------------------- | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** - ```js -let mode = 1; -audioRenderer.setInterruptMode(mode, (err, data)=>{ - if(err){ - console.error(`setInterruptMode Fail: ${err}`); - } - console.info('setInterruptMode Success!'); -}); +let outputAudioRendererFilter = { + uid : 20010041, + rendererInfo : { + content : audio.ContentType.CONTENT_TYPE_MUSIC, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 }, + rendererId : 0 }; + +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); +} ``` -### setVolume9+ +### selectOutputDeviceByFilter9+ -setVolume(volume: number): Promise<void> +selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise<void> -Sets the volume for the application. This API uses a promise to return the result. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device **Parameters** -| Name | Type | Mandatory | Description | -| ------ | ------ | --------- | -------------- | -| volume | number | Yes | Volume to set. | +| Name | Type | Mandatory| Description | +| ----------------------| ------------------------------------------------------------ | ---- | ------------------------- | +| filter | [AudioRendererFilter](#audiorendererfilter9) | Yes | Filter criteria. | +| outputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Output device. | **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| **Example** ```js -audioRenderer.setVolume(10).then(data=>{ - console.info('setVolume Success!'); -}).catch((err) => { - console.error(`setVolume Fail: ${err}`); -}); +let outputAudioRendererFilter = { + uid : 20010041, + rendererInfo : { + content : audio.ContentType.CONTENT_TYPE_MUSIC, + usage : audio.StreamUsage.STREAM_USAGE_MEDIA, + rendererFlags : 0 }, + rendererId : 0 }; -``` +let outputAudioDeviceDescriptor = [{ + deviceRole : audio.DeviceRole.OUTPUT_DEVICE, + deviceType : audio.DeviceType.SPEAKER, + id : 1, + name : "", + address : "", + sampleRates : [44100], + channelCounts : [2], + channelMasks : [0], + networkId : audio.LOCAL_NETWORK_ID, + interruptGroupId : 1, + volumeGroupId : 1, +}]; -### setVolume9+ +async function selectOutputDeviceByFilter(){ + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) +} +``` -setVolume(volume: number, callback: AsyncCallback\): void +## AudioRendererChangeInfoArray9+ -Sets the volume for the application. This API uses an asynchronous callback to return the result. +Defines an **AudioRenderChangeInfo** array, which is read-only. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +## AudioRendererChangeInfo9+ -| Name | Type | Mandatory | Description | -| -------- | -------------------- | --------- | ----------------------------------- | -| volume | number | Yes | Volume to set. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +Describes the audio renderer change event. + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API. | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | +| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -audioRenderer.setVolume(10, (err, data)=>{ - if(err){ - console.error(`setVolume Fail: ${err}`); +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager = audioManager.getStreamManager(); +let resultFlag = false; + +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + console.info(`## RendererChange on is called for ${i} ##`); + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfoArray[i].clientUid}`); + console.info(`Content for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.content}`); + console.info(`Stream for ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfoArray[i].rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfoArray[i].rendererState}`); + let devDescriptor = AudioRendererChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioRendererChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM: ${i} : ${AudioRendererChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + if (AudioRendererChangeInfoArray[i].rendererState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for ${i} is: ${resultFlag}`); + } } - console.info('setVolume Success!'); }); - ``` -### on('audioInterrupt')9+ - -on(type: 'audioInterrupt', callback: Callback\): void - -Subscribes to audio interruption events. This API uses a callback to get interrupt events. -Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. +## AudioCapturerChangeInfoArray9+ -**System capability**: SystemCapability.Multimedia.Audio.Interrupt +Defines an **AudioCapturerChangeInfo** array, which is read-only. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | -| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | +## AudioCapturerChangeInfo9+ -**Error codes** +Describes the audio capturer change event. -For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| ID | Error Message | -| ------- | ------------------------------- | -| 6800101 | if input parameter value error. | +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ---------------------------------------------------------- | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API. | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | +| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API. | **Example** ```js -let isPlay; -let started; -audioRenderer.on('audioInterrupt', async(interruptEvent) => { - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Force paused. Stop writing'); - isPlay = false; - break; - case audio.InterruptHint.INTERRUPT_HINT_STOP: - console.info('Force stopped. Stop writing'); - isPlay = false; - break; +import audio from '@ohos.multimedia.audio'; + +const audioManager = audio.getAudioManager(); +let audioStreamManager = audioManager.getStreamManager(); + +let resultFlag = false; +audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`## CapChange on is called for element ${i} ##`); + console.info(`StrId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`CUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Src for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + let devDescriptor = AudioCapturerChangeInfoArray[i].deviceDescriptors; + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Addr: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SR: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`C ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`CM ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - console.info('Resume force paused renderer or ignore'); - await audioRenderer.start().then(async function () { - console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); - started = true; - }).catch((err) => { - console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); - started = false; - }); - if (started) { - isPlay = true; - console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); - } else { - console.error('AudioInterruptMusic Renderer start failed'); - } - break; - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - console.info('Choose to pause or ignore'); - if (isPlay == true) { - isPlay == false; - console.info('AudioInterruptMusic: Media PAUSE : TRUE'); - } else { - isPlay = true; - console.info('AudioInterruptMusic: Media PLAY : TRUE'); - } - break; + if (AudioCapturerChangeInfoArray[i].capturerState == 1 && devDescriptor != null) { + resultFlag = true; + console.info(`ResultFlag for element ${i} is: ${resultFlag}`); } } }); - ``` -### on('markReach')8+ +## AudioDeviceDescriptors -on(type: "markReach", frame: number, callback: Callback<number>): void +Defines an [AudioDeviceDescriptor](#audiodevicedescriptor) array, which is read-only. -Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked. +## AudioDeviceDescriptor -**System capability**: SystemCapability.Multimedia.Audio.Renderer +Describes an audio device. -**Parameters** +**System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Readable | Writable | Description | +| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | +| id9+ | number | Yes | No | Device ID. | +| name9+ | string | Yes | No | Device name. | +| address9+ | string | Yes | No | Device address. | +| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | +| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | +| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | +| networkId9+ | string | Yes | No | ID of the device network.
This is a system API. | +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API. | +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API. | **Example** ```js -audioRenderer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +import audio from '@ohos.multimedia.audio'; + +function displayDeviceProp(value) { + deviceRoleValue = value.deviceRole; + deviceTypeValue = value.deviceType; +} + +let deviceRoleValue = null; +let deviceTypeValue = null; +const promise = audio.getAudioManager().getDevices(1); +promise.then(function (value) { + console.info('AudioFrameworkTest: Promise: getDevices OUTPUT_DEVICES_FLAG'); + value.forEach(displayDeviceProp); + if (deviceTypeValue != null && deviceRoleValue != null){ + console.info('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : PASS'); + } else { + console.error('AudioFrameworkTest: Promise: getDevices : OUTPUT_DEVICES_FLAG : FAIL'); } }); - ``` +## AudioRendererFilter9+ -### off('markReach') 8+ +Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you must obtain an **AudioRendererFilter** instance. -off(type: 'markReach'): void +**System API**: This is a system API. -Unsubscribes from mark reached events. +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**Example** -**Parameters** +```js +let outputAudioRendererFilter = { + "uid":20010041, + "rendererInfo": { + "contentType":audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage":audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags":0 }, + "rendererId":0 }; +``` -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +## AudioRenderer8+ + +Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, you must use [createAudioRenderer](#audiocreateaudiorenderer8) to create an **AudioRenderer** instance. + +### Attributes + +**System capability**: SystemCapability.Multimedia.Audio.Renderer + +| Name | Type | Readable | Writable | Description | +| ------------------ | -------------------------- | -------- | -------- | --------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | **Example** ```js -audioRenderer.off('markReach'); - +let state = audioRenderer.state; ``` -### on('periodReach') 8+ +### getRendererInfo8+ -on(type: "periodReach", frame: number, callback: Callback<number>): void +getRendererInfo(callback: AsyncCallback): void -Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. +Obtains the renderer information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | **Example** ```js -audioRenderer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } +audioRenderer.getRendererInfo((err, rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`); }); - ``` -### off('periodReach') 8+ +### getRendererInfo8+ -off(type: 'periodReach'): void +getRendererInfo(): Promise -Unsubscribes from period reached events. +Obtains the renderer information of this **AudioRenderer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Type | Description | +| -------------------------------------------------- | ------------------------------------------------ | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | **Example** ```js -audioRenderer.off('periodReach') - +audioRenderer.getRendererInfo().then((rendererInfo) => { + console.info('Renderer GetRendererInfo:'); + console.info(`Renderer content: ${rendererInfo.content}`); + console.info(`Renderer usage: ${rendererInfo.usage}`); + console.info(`Renderer flags: ${rendererInfo.rendererFlags}`) +}).catch((err) => { + console.error(`AudioFrameworkRenderLog: RendererInfo :ERROR: ${err}`); +}); ``` -### on('stateChange')8+ +### getStreamInfo8+ -on(type: 'stateChange', callback: Callback): void +getStreamInfo(callback: AsyncCallback): void -Subscribes to state change events. +Obtains the stream information of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** ```js -audioRenderer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio renderer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio renderer state is: STATE_RUNNING'); - } +audioRenderer.getStreamInfo((err, streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); }); - ``` -## AudioCapturer8+ +### getStreamInfo8+ -Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. +getStreamInfo(): Promise -### Attributes +Obtains the stream information of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable | Writable | Description | -| :----------------- | :------------------------- | :------- | :------- | :-------------------- | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | +**Return value** + +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -let state = audioCapturer.state; +audioRenderer.getStreamInfo().then((streamInfo) => { + console.info('Renderer GetStreamInfo:'); + console.info(`Renderer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Renderer channel: ${streamInfo.channels}`); + console.info(`Renderer format: ${streamInfo.sampleFormat}`); + console.info(`Renderer encoding type: ${streamInfo.encodingType}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); +}); ``` -### getCapturerInfo8+ +### getAudioStreamId9+ -getCapturerInfo(callback: AsyncCallback): void +getAudioStreamId(callback: AsyncCallback): void -Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Obtains the stream ID of this **AudioRenderer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the capturer information. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | **Example** ```js -audioCapturer.getCapturerInfo((err, capturerInfo) => { - if (err) { - console.error('Failed to get capture info'); - } else { - console.info('Capturer getCapturerInfo:'); - console.info(`Capturer source: ${capturerInfo.source}`); - console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); - } +audioRenderer.getAudioStreamId((err, streamid) => { + console.info(`Renderer GetStreamId: ${streamid}`); }); ``` +### getAudioStreamId9+ -### getCapturerInfo8+ - -getCapturerInfo(): Promise +getAudioStreamId(): Promise -Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. +Obtains the stream ID of this **AudioRenderer** instance. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :------------------------------------------------ | :----------------------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | **Example** ```js -audioCapturer.getCapturerInfo().then((audioParamsGet) => { - if (audioParamsGet != undefined) { - console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); - console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); - console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); - } else { - console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); - console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); - } +audioRenderer.getAudioStreamId().then((streamid) => { + console.info(`Renderer getAudioStreamId: ${streamid}`); }).catch((err) => { - console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### getStreamInfo8+ +### start8+ -getStreamInfo(callback: AsyncCallback): void +start(callback: AsyncCallback): void -Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Starts the renderer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.getStreamInfo((err, streamInfo) => { +audioRenderer.start((err) => { if (err) { - console.error('Failed to get stream info'); + console.error('Renderer start failed.'); } else { - console.info('Capturer GetStreamInfo:'); - console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); - console.info(`Capturer channel: ${streamInfo.channels}`); - console.info(`Capturer format: ${streamInfo.sampleFormat}`); - console.info(`Capturer encoding type: ${streamInfo.encodingType}`); + console.info('Renderer start success.'); } }); ``` -### getStreamInfo8+ +### start8+ -getStreamInfo(): Promise +start(): Promise -Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. +Starts the renderer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------------------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.getStreamInfo().then((audioParamsGet) => { - console.info('getStreamInfo:'); - console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); - console.info(`samplingRate: ${audioParamsGet.samplingRate}`); - console.info(`channels: ${audioParamsGet.channels}`); - console.info(`encodingType: ${audioParamsGet.encodingType}`); +audioRenderer.start().then(() => { + console.info('Renderer started'); }).catch((err) => { - console.error(`getStreamInfo :ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### getAudioStreamId9+ +### pause8+ -getAudioStreamId(callback: AsyncCallback): void +pause(callback: AsyncCallback\): void -Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Pauses rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the stream ID. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.getAudioStreamId((err, streamid) => { - console.info(`audioCapturer GetStreamId: ${streamid}`); +audioRenderer.pause((err) => { + if (err) { + console.error('Renderer pause failed'); + } else { + console.info('Renderer paused.'); + } }); ``` -### getAudioStreamId9+ +### pause8+ -getAudioStreamId(): Promise +pause(): Promise\ -Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result. +Pauses rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the stream ID. | +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.getAudioStreamId().then((streamid) => { - console.info(`audioCapturer getAudioStreamId: ${streamid}`); +audioRenderer.pause().then(() => { + console.info('Renderer paused'); }).catch((err) => { console.error(`ERROR: ${err}`); }); ``` -### start8+ +### drain8+ -start(callback: AsyncCallback): void +drain(callback: AsyncCallback\): void -Starts capturing. This API uses an asynchronous callback to return the result. +Drains the playback buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.start((err) => { +audioRenderer.drain((err) => { if (err) { - console.error('Capturer start failed.'); + console.error('Renderer drain failed'); } else { - console.info('Capturer start success.'); + console.info('Renderer drained.'); } }); ``` +### drain8+ -### start8+ - -start(): Promise +drain(): Promise\ -Starts capturing. This API uses a promise to return the result. +Drains the playback buffer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.start().then(() => { - console.info('AudioFrameworkRecLog: ---------START---------'); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); - console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { - console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); - } +audioRenderer.drain().then(() => { + console.info('Renderer drained successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### stop8+ -stop(callback: AsyncCallback): void +stop(callback: AsyncCallback\): void -Stops capturing. This API uses an asynchronous callback to return the result. +Stops rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.stop((err) => { +audioRenderer.stop((err) => { if (err) { - console.error('Capturer stop failed'); + console.error('Renderer stop failed'); } else { - console.info('Capturer stopped.'); + console.info('Renderer stopped.'); } }); ``` - ### stop8+ -stop(): Promise +stop(): Promise\ -Stops capturing. This API uses a promise to return the result. +Stops rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.stop().then(() => { - console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); - if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ - console.info('AudioFrameworkRecLog: State is Stopped:'); - } +audioRenderer.stop().then(() => { + console.info('Renderer stopped successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### release8+ -release(callback: AsyncCallback): void +release(callback: AsyncCallback\): void -Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Releases the renderer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.release((err) => { +audioRenderer.release((err) => { if (err) { - console.error('capturer release failed'); + console.error('Renderer release failed'); } else { - console.info('capturer released.'); + console.info('Renderer released.'); } }); ``` - ### release8+ -release(): Promise +release(): Promise\ -Releases this **AudioCapturer** instance. This API uses a promise to return the result. +Releases the renderer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -let stateFlag; -audioCapturer.release().then(() => { - console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); - console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); - console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); - console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); +audioRenderer.release().then(() => { + console.info('Renderer released successfully'); }).catch((err) => { - console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); + console.error(`ERROR: ${err}`); }); ``` -### read8+ +### write8+ -read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void +write(buffer: ArrayBuffer, callback: AsyncCallback\): void -Reads the buffer. This API uses an asynchronous callback to return the result. +Writes the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------------- | :-------------------------- | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | -| callback | AsyncCallback | Yes | Callback used to return the buffer. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data)=> { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -audioCapturer.read(bufferSize, true, async(err, buffer) => { - if (!err) { - console.info('Success in reading the buffer data'); +console.info(`Buffer size: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf, (err, writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); } }); ``` -### read8+ - -read(size: number, isBlockingRead: boolean): Promise - -Reads the buffer. This API uses a promise to return the result. +### write8+ -**System capability**: SystemCapability.Multimedia.Audio.Capturer +write(buffer: ArrayBuffer): Promise\ -**Parameters** +Writes the buffer. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| :------------- | :------ | :-------- | :----------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------------- | -| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + console.info(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); -console.info(`Buffer size: ${bufferSize}`); -audioCapturer.read(bufferSize, true).then((buffer) => { - console.info('buffer read successfully'); +console.info(`BufferSize: ${bufferSize}`); +let context = featureAbility.getContext(); +let path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +let filePath = path + '/StarWars10s-2C-48000-4SW.wav'; +let ss = fileio.createStreamSync(filePath, 'r'); +let buf = new ArrayBuffer(bufferSize); +ss.readSync(buf); +audioRenderer.write(buf).then((writtenbytes) => { + if (writtenbytes < 0) { + console.error('write failed.'); + } else { + console.info(`Actual written bytes: ${writtenbytes}`); + } }).catch((err) => { - console.info(`ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### getAudioTime8+ -getAudioTime(callback: AsyncCallback): void +getAudioTime(callback: AsyncCallback\): void Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | **Example** ```js -audioCapturer.getAudioTime((err, timestamp) => { +audioRenderer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); @@ -4475,54 +4661,49 @@ audioCapturer.getAudioTime((err, timestamp) => { ### getAudioTime8+ -getAudioTime(): Promise +getAudioTime(): Promise\ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :--------------- | :------------------------------------ | -| Promise | Promise used to return the timestamp. | +| ---------------- | ------------------------------------- | +| Promise\ | Promise used to return the timestamp. | **Example** ```js -audioCapturer.getAudioTime().then((audioTime) => { - console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); +audioRenderer.getAudioTime().then((timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + console.error(`ERROR: ${err}`); }); ``` ### getBufferSize8+ -getBufferSize(callback: AsyncCallback): void +getBufferSize(callback: AsyncCallback\): void -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** | Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :--------------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size. | +| -------- | ---------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | **Example** ```js -audioCapturer.getBufferSize((err, bufferSize) => { - if (!err) { - console.info(`BufferSize : ${bufferSize}`); - audioCapturer.read(bufferSize, true).then((buffer) => { - console.info(`Buffer read is ${buffer}`); - }).catch((err) => { - console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); - }); +let bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { + if (err) { + console.error('getBufferSize error'); } }); @@ -4530,1546 +4711,1425 @@ audioCapturer.getBufferSize((err, bufferSize) => { ### getBufferSize8+ -getBufferSize(): Promise +getBufferSize(): Promise\ -Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. +Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Return value** | Type | Description | -| :--------------- | :-------------------------------------- | -| Promise | Promise used to return the buffer size. | +| ---------------- | --------------------------------------- | +| Promise\ | Promise used to return the buffer size. | **Example** ```js let bufferSize; -audioCapturer.getBufferSize().then((data) => { - console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); +audioRenderer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); ``` -### on('markReach')8+ +### setRenderRate8+ -on(type: "markReach", frame: number, callback: Callback<number>): void +setRenderRate(rate: AudioRendererRate, callback: AsyncCallback\): void -Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked. +Sets the render rate. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ----------------------------------- | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -audioCapturer.on('markReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => { + if (err) { + console.error('Failed to set params'); + } else { + console.info('Callback invoked to indicate a successful render rate setting.'); } }); ``` -### off('markReach')8+ - -off(type: 'markReach'): void - -Unsubscribes from mark reached events. - -**System capability**: SystemCapability.Multimedia.Audio.Capturer - -**Parameters** - -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'markReach'**. | - -**Example** - -```js -audioCapturer.off('markReach'); - -``` - -### on('periodReach')8+ +### setRenderRate8+ -on(type: "periodReach", frame: number, callback: Callback<number>): void +setRenderRate(rate: AudioRendererRate): Promise\ -Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. +Sets the render rate. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :---------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback\ | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | --------- | ------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | + +**Return value** + +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** ```js -audioCapturer.on('periodReach', 1000, (position) => { - if (position == 1000) { - console.info('ON Triggered successfully'); - } +audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() => { + console.info('setRenderRate SUCCESS'); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### off('periodReach')8+ +### getRenderRate8+ -off(type: 'periodReach'): void +getRenderRate(callback: AsyncCallback\): void -Unsubscribes from period reached events. +Obtains the current render rate. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :----- | :-------- | :--------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | **Example** ```js -audioCapturer.off('periodReach') +audioRenderer.getRenderRate((err, renderrate) => { + console.info(`getRenderRate: ${renderrate}`); +}); ``` -### on('stateChange')8+ +### getRenderRate8+ -on(type: 'stateChange', callback: Callback): void +getRenderRate(): Promise\ -Subscribes to state change events. +Obtains the current render rate. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Capturer +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **stateChange** means the state change event. | -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Type | Description | +| ------------------------------------------------- | --------------------------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | **Example** ```js -audioCapturer.on('stateChange', (state) => { - if (state == 1) { - console.info('audio capturer state is: STATE_PREPARED'); - } - if (state == 2) { - console.info('audio capturer state is: STATE_RUNNING'); - } +audioRenderer.getRenderRate().then((renderRate) => { + console.info(`getRenderRate: ${renderRate}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -## ToneType9+ +### setInterruptMode9+ -Enumerates the tone types of the player. +setInterruptMode(mode: InterruptMode): Promise<void> -**System API**: This is a system API. +Sets the audio interruption mode for the application. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Name | Default Value | Description | -| :----------------------------------------------- | :------------ | :-------------------------------------------- | -| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | -| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | -| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | -| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | -| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | -| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | -| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | -| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | -| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | -| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | -| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | -| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | -| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | -| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | -| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | -| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | -| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | -| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | -| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | -| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | -| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | -| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | -| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | -| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | -| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | -| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | +**Parameters** -## TonePlayer9+ +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------ | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | -Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. +**Return value** -**System API**: This is a system API. +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | -### load9+ +**Example** -load(type: ToneType, callback: AsyncCallback<void>): void +```js +let mode = 0; +audioRenderer.setInterruptMode(mode).then(data=>{ + console.info('setInterruptMode Success!'); +}).catch((err) => { + console.error(`setInterruptMode Fail: ${err}`); +}); -Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. +``` -**System capability**: SystemCapability.Multimedia.Audio.Tone +### setInterruptMode9+ + +setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void + +Sets the audio interruption mode for the application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Interrupt **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------- | :-------- | :---------------------------------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | --------- | ----------------------------------- | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { - if (err) { - console.error(`callback call load failed error: ${err.message}`); - return; - } else { - console.info('callback call load success'); +let mode = 1; +audioRenderer.setInterruptMode(mode, (err, data)=>{ + if(err){ + console.error(`setInterruptMode Fail: ${err}`); } + console.info('setInterruptMode Success!'); }); ``` -### load9+ +### setVolume9+ -load(type: ToneType): Promise<void> +setVolume(volume: number): Promise<void> -Loads the DTMF tone configuration. This API uses a promise to return the result. +Sets the volume for the application. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :--- | :--------------------- | :-------- | ----------- | -| type | [ToneType](#tonetype9) | Yes | Tone type. | +| Name | Type | Mandatory | Description | +| ------ | ------ | --------- | ------------------------------------------------------------ | +| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | **Return value** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | **Example** ```js -tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { - console.info('promise call load '); -}).catch(() => { - console.error('promise call load fail'); +audioRenderer.setVolume(0.5).then(data=>{ + console.info('setVolume Success!'); +}).catch((err) => { + console.error(`setVolume Fail: ${err}`); }); ``` -### start9+ +### setVolume9+ -start(callback: AsyncCallback<void>): void +setVolume(volume: number, callback: AsyncCallback\): void -Starts DTMF tone playing. This API uses an asynchronous callback to return the result. +Sets the volume for the application. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ------------------------------------------------------------ | +| volume | number | Yes | Volume to set, which can be within the range from 0.0 to 1.0. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -tonePlayer.start((err) => { - if (err) { - console.error(`callback call start failed error: ${err.message}`); - return; - } else { - console.info('callback call start success'); +audioRenderer.setVolume(0.5, (err, data)=>{ + if(err){ + console.error(`setVolume Fail: ${err}`); } + console.info('setVolume Success!'); }); ``` -### start9+ +### on('audioInterrupt')9+ -start(): Promise<void> +on(type: 'audioInterrupt', callback: Callback\): void -Starts DTMF tone playing. This API uses a promise to return the result. +Subscribes to audio interruption events. This API uses a callback to get interrupt events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +Same as [on('interrupt')](#oninterruptdeprecated), this API has obtained the focus before **start**, **pause**, or **stop** of **AudioRenderer** is called. Therefore, you do not need to request the focus. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Interrupt -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **'audioInterrupt'** means the audio interruption event, which is triggered when audio playback is interrupted. | +| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | + +**Error codes** + +For details about the error codes, see [Audio Error Codes](../errorcodes/errorcode-audio.md). + +| ID | Error Message | +| ------- | ------------------------------ | +| 6800101 | if input parameter value error | **Example** ```js -tonePlayer.start().then(() => { - console.info('promise call start'); -}).catch(() => { - console.error('promise call start fail'); -}); +let isPlay; +let started; +onAudioInterrupt(); + +async function onAudioInterrupt(){ + audioRenderer.on('audioInterrupt', async(interruptEvent) => { + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Force paused. Stop writing'); + isPlay = false; + break; + case audio.InterruptHint.INTERRUPT_HINT_STOP: + console.info('Force stopped. Stop writing'); + isPlay = false; + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + console.info('Resume force paused renderer or ignore'); + await audioRenderer.start().then(async function () { + console.info('AudioInterruptMusic: renderInstant started :SUCCESS '); + started = true; + }).catch((err) => { + console.error(`AudioInterruptMusic: renderInstant start :ERROR : ${err}`); + started = false; + }); + if (started) { + isPlay = true; + console.info(`AudioInterruptMusic Renderer started : isPlay : ${isPlay}`); + } else { + console.error('AudioInterruptMusic Renderer start failed'); + } + break; + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + console.info('Choose to pause or ignore'); + if (isPlay == true) { + isPlay == false; + console.info('AudioInterruptMusic: Media PAUSE : TRUE'); + } else { + isPlay = true; + console.info('AudioInterruptMusic: Media PLAY : TRUE'); + } + break; + } + } + }); +} ``` -### stop9+ +### on('markReach')8+ -stop(callback: AsyncCallback<void>): void +on(type: "markReach", frame: number, callback: Callback<number>): void -Stops the tone that is being played. This API uses an asynchronous callback to return the result. +Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is invoked. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -tonePlayer.stop((err) => { - if (err) { - console.error(`callback call stop error: ${err.message}`); - return; - } else { - console.error('callback call stop success '); +audioRenderer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### stop9+ -stop(): Promise<void> +### off('markReach') 8+ -Stops the tone that is being played. This API uses a promise to return the result. +off(type: 'markReach'): void -**System capability**: SystemCapability.Multimedia.Audio.Tone +Unsubscribes from mark reached events. -**Return value** +**System capability**: SystemCapability.Multimedia.Audio.Renderer -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | **Example** ```js -tonePlayer.stop().then(() => { - console.info('promise call stop finish'); -}).catch(() => { - console.error('promise call stop fail'); -}); +audioRenderer.off('markReach'); ``` -### release9+ +### on('periodReach') 8+ -release(callback: AsyncCallback<void>): void +on(type: "periodReach", frame: number, callback: Callback<number>): void -Releases the resources associated with the **TonePlayer** instance. This API uses an asynchronous callback to return the result. +Subscribes to period reached events. When the number of frames rendered reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :------------------- | :-------- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -tonePlayer.release((err) => { - if (err) { - console.error(`callback call release failed error: ${err.message}`); - return; - } else { - console.info('callback call release success '); +audioRenderer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } }); ``` -### release9+ +### off('periodReach') 8+ -release(): Promise<void> +off(type: 'periodReach'): void -Releases the resources associated with the **TonePlayer** instance. This API uses a promise to return the result. +Unsubscribes from period reached events. -**System capability**: SystemCapability.Multimedia.Audio.Tone +**System capability**: SystemCapability.Multimedia.Audio.Renderer -**Return value** +**Parameters** -| Type | Description | -| :------------- | :--------------------------------- | -| Promise | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | **Example** ```js -tonePlayer.release().then(() => { - console.info('promise call release'); -}).catch(() => { - console.error('promise call release fail'); -}); +audioRenderer.off('periodReach') ``` -## ActiveDeviceType(deprecated) - -Enumerates the active device types. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -| Name | Default Value | Description | -| ------------- | ------------- | ------------------------------------------------------------ | -| SPEAKER | 2 | Speaker. | -| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | - -## InterruptActionType(deprecated) +### on('stateChange')8+ -Enumerates the returned event types for audio interruption events. +on(type: 'stateChange', callback: Callback): void -> **NOTE** -> This API is supported since API version 7 and deprecated since API version 9. +Subscribes to state change events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Default Value | Description | -| -------------- | ------------- | ------------------------- | -| TYPE_ACTIVATED | 0 | Focus gain event. | -| TYPE_INTERRUPT | 1 | Audio interruption event. | - -## AudioInterrupt(deprecated) +**Parameters** -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | -Describes input parameters of audio interruption events. +**Example** -**System capability**: SystemCapability.Multimedia.Audio.Renderer +```js +audioRenderer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio renderer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio renderer state is: STATE_RUNNING'); + } +}); -| Name | Type | Mandatory | Description | -| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | -| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | -| contentType | [ContentType](#contenttype) | Yes | Audio content type. | -| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | +``` -## InterruptAction(deprecated) +## AudioCapturer8+ -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. +Provides APIs for audio capture. Before calling any API in **AudioCapturer**, you must use [createAudioCapturer](#audiocreateaudiocapturer8) to create an **AudioCapturer** instance. -Describes the callback invoked for audio interruption or focus gain events. +### Attributes -**System capability**: SystemCapability.Multimedia.Audio.Renderer +**System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------------- | --------- | ------------------------------------------------------------ | -| actionType | [InterruptActionType](#interruptactiontype) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | -| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | -| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | -| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | +| Name | Type | Readable | Writable | Description | +| :----------------- | :------------------------- | :------- | :------- | :-------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | -### setVolume(deprecated) +**Example** -setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback<void>): void +```js +let state = audioCapturer.state; -Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. +### getCapturerInfo8+ -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +getCapturerInfo(callback: AsyncCallback): void -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Obtains the capturer information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the capturer information. | **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10, (err) => { +audioCapturer.getCapturerInfo((err, capturerInfo) => { if (err) { - console.error(`Failed to set the volume. ${err}`); - return; + console.error('Failed to get capture info'); + } else { + console.info('Capturer getCapturerInfo:'); + console.info(`Capturer source: ${capturerInfo.source}`); + console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } - console.info('Callback invoked to indicate a successful volume setting.'); }); ``` -### setVolume(deprecated) - -setVolume(volumeType: AudioVolumeType, volume: number): Promise<void> - -Sets the volume for a stream. 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 [setVolume](#setvolume9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +### getCapturerInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getCapturerInfo(): Promise -**Parameters** +Obtains the capturer information of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| volume | number | Yes | Volume to set. The value range can be obtained by calling **getMinVolume** and **getMaxVolume**. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------------------------------------------ | :----------------------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | **Example** ```js -audioManager.setVolume(audio.AudioVolumeType.MEDIA, 10).then(() => { - console.info('Promise returned to indicate a successful volume setting.'); +audioCapturer.getCapturerInfo().then((audioParamsGet) => { + if (audioParamsGet != undefined) { + console.info('AudioFrameworkRecLog: Capturer CapturerInfo:'); + console.info(`AudioFrameworkRecLog: Capturer SourceType: ${audioParamsGet.source}`); + console.info(`AudioFrameworkRecLog: Capturer capturerFlags: ${audioParamsGet.capturerFlags}`); + } else { + console.info(`AudioFrameworkRecLog: audioParamsGet is : ${audioParamsGet}`); + console.info('AudioFrameworkRecLog: audioParams getCapturerInfo are incorrect'); + } +}).catch((err) => { + console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); ``` -### getVolume(deprecated) - -getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### getStreamInfo8+ -Obtains the volume of a stream. This API uses an asynchronous callback to return the result. +getStreamInfo(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getVolume](#getvolume9) in **AudioVolumeGroupManager**. +Obtains the stream information of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ----------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the volume. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.getStreamInfo((err, streamInfo) => { if (err) { - console.error(`Failed to obtain the volume. ${err}`); - return; + console.error('Failed to get stream info'); + } else { + console.info('Capturer GetStreamInfo:'); + console.info(`Capturer sampling rate: ${streamInfo.samplingRate}`); + console.info(`Capturer channel: ${streamInfo.channels}`); + console.info(`Capturer format: ${streamInfo.sampleFormat}`); + console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } - console.info('Callback invoked to indicate that the volume is obtained.'); }); ``` -### getVolume(deprecated) - -getVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the volume of a stream. 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 [getVolume](#getvolume9) in **AudioVolumeGroupManager**. +### getStreamInfo8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +getStreamInfo(): Promise -**Parameters** +Obtains the stream information of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ---------------------------------- | -| Promise<number> | Promise used to return the volume. | +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** ```js -audioManager.getVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the volume is obtained ${value} .`); +audioCapturer.getStreamInfo().then((audioParamsGet) => { + console.info('getStreamInfo:'); + console.info(`sampleFormat: ${audioParamsGet.sampleFormat}`); + console.info(`samplingRate: ${audioParamsGet.samplingRate}`); + console.info(`channels: ${audioParamsGet.channels}`); + console.info(`encodingType: ${audioParamsGet.encodingType}`); +}).catch((err) => { + console.error(`getStreamInfo :ERROR: ${err}`); }); ``` -### getMinVolume(deprecated) - -getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### getAudioStreamId9+ -Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +getAudioStreamId(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. +Obtains the stream ID of this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the minimum volume. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the stream ID. | **Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the minimum volume. ${err}`); - return; - } - console.info(`Callback invoked to indicate that the minimum volume is obtained. ${value}`); +audioCapturer.getAudioStreamId((err, streamid) => { + console.info(`audioCapturer GetStreamId: ${streamid}`); }); -``` - -### getMinVolume(deprecated) - -getMinVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the minimum volume allowed for a stream. 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 [getMinVolume](#getminvolume9) in **AudioVolumeGroupManager**. +``` -**System capability**: SystemCapability.Multimedia.Audio.Volume +### getAudioStreamId9+ -**Parameters** +getAudioStreamId(): Promise + +Obtains the stream ID of this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | -| Promise<number> | Promise used to return the minimum volume. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the stream ID. | **Example** ```js -audioManager.getMinVolume(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promised returned to indicate that the minimum volume is obtained. ${value}`); +audioCapturer.getAudioStreamId().then((streamid) => { + console.info(`audioCapturer getAudioStreamId: ${streamid}`); +}).catch((err) => { + console.error(`ERROR: ${err}`); }); ``` -### getMaxVolume(deprecated) - -getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): void +### start8+ -Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +start(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. +Starts capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------- | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<number> | Yes | Callback used to return the maximum volume. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.start((err) => { if (err) { - console.error(`Failed to obtain the maximum volume. ${err}`); - return; + console.error('Capturer start failed.'); + } else { + console.info('Capturer start success.'); } - console.info(`Callback invoked to indicate that the maximum volume is obtained. ${value}`); }); ``` -### getMaxVolume(deprecated) - -getMaxVolume(volumeType: AudioVolumeType): Promise<number> - -Obtains the maximum volume allowed for a stream. 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 [getMaxVolume](#getmaxvolume9) in **AudioVolumeGroupManager**. +### start8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +start(): Promise -**Parameters** +Starts capturing. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| --------------------- | ------------------------------------------ | -| Promise<number> | Promise used to return the maximum volume. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.getMaxVolume(audio.AudioVolumeType.MEDIA).then((data) => { - console.info('Promised returned to indicate that the maximum volume is obtained.'); +audioCapturer.start().then(() => { + console.info('AudioFrameworkRecLog: ---------START---------'); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer: STATE: ${audioCapturer.state}`); + console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_RUNNING)) { + console.info('AudioFrameworkRecLog: AudioCapturer is in Running State'); + } +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); ``` -### mute(deprecated) - -mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback<void>): void - -Mutes or unmutes a stream. 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 [mute](#mute9) in **AudioVolumeGroupManager**. +### stop8+ -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +stop(callback: AsyncCallback): void -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +Stops capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true, (err) => { +audioCapturer.stop((err) => { if (err) { - console.error(`Failed to mute the stream. ${err}`); - return; + console.error('Capturer stop failed'); + } else { + console.info('Capturer stopped.'); } - console.info('Callback invoked to indicate that the stream is muted.'); }); ``` -### mute(deprecated) - -mute(volumeType: AudioVolumeType, mute: boolean): Promise<void> - -Mutes or unmutes a stream. 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 [mute](#mute9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY -This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +### stop8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +stop(): Promise -**Parameters** +Stops capturing. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the stream, and **false** means the opposite. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** - ```js -audioManager.mute(audio.AudioVolumeType.MEDIA, true).then(() => { - console.info('Promise returned to indicate that the stream is muted.'); +audioCapturer.stop().then(() => { + console.info('AudioFrameworkRecLog: ---------STOP RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer stopped: SUCCESS'); + if ((audioCapturer.state == audio.AudioState.STATE_STOPPED)){ + console.info('AudioFrameworkRecLog: State is Stopped:'); + } +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### isMute(deprecated) - -isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### release8+ -Checks whether a stream is muted. This API uses an asynchronous callback to return the result. +release(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMute](#ismute9) in **AudioVolumeGroupManager**. +Releases this **AudioCapturer** instance. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA, (err, value) => { +audioCapturer.release((err) => { if (err) { - console.error(`Failed to obtain the mute status. ${err}`); - return; + console.error('capturer release failed'); + } else { + console.info('capturer released.'); } - console.info(`Callback invoked to indicate that the mute status of the stream is obtained. ${value}`); }); ``` -### isMute(deprecated) - -isMute(volumeType: AudioVolumeType): Promise<boolean> - -Checks whether a stream is muted. 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 [isMute](#ismute9) in **AudioVolumeGroupManager**. +### release8+ -**System capability**: SystemCapability.Multimedia.Audio.Volume +release(): Promise -**Parameters** +Releases this **AudioCapturer** instance. This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the stream. The value **true** means that the stream is muted, and **false** means the opposite. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the mute status of the stream is obtained ${value}.`); +let stateFlag; +audioCapturer.release().then(() => { + console.info('AudioFrameworkRecLog: ---------RELEASE RECORD---------'); + console.info('AudioFrameworkRecLog: Capturer release : SUCCESS'); + console.info(`AudioFrameworkRecLog: AudioCapturer : STATE : ${audioCapturer.state}`); + console.info(`AudioFrameworkRecLog: stateFlag : ${stateFlag}`); +}).catch((err) => { + console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); ``` -### isActive(deprecated) - -isActive(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): void +### read8+ -Checks whether a stream is active. This API uses an asynchronous callback to return the result. +read(size: number, isBlockingRead: boolean, callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. +Reads the buffer. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------------------------------------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------------- | :-------------------------- | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer. | **Example** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the stream. ${err}`); - return; +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.error(`AudioFrameworkRecLog: getBufferSize: ERROR: ${err}`); + }); +audioCapturer.read(bufferSize, true, async(err, buffer) => { + if (!err) { + console.info('Success in reading the buffer data'); } - console.info(`Callback invoked to indicate that the active status of the stream is obtained ${value}.`); }); ``` -### isActive(deprecated) - -isActive(volumeType: AudioVolumeType): Promise<boolean> +### read8+ -Checks whether a stream is active. This API uses a promise to return the result. +read(size: number, isBlockingRead: boolean): Promise -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isActive](#isactive9) in **AudioStreamManager**. +Reads the buffer. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ----------------------------------- | --------- | ------------------ | -| volumeType | [AudioVolumeType](#audiovolumetype) | Yes | Audio stream type. | +| Name | Type | Mandatory | Description | +| :------------- | :------ | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the active status of the stream. The value **true** means that the stream is active, and **false** means the opposite. | +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | **Example** ```js -audioManager.isActive(audio.AudioVolumeType.MEDIA).then((value) => { - console.info(`Promise returned to indicate that the active status of the stream is obtained ${value}.`); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize: SUCCESS ${data}`); + bufferSize = data; + }).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize: ERROR ${err}`); + }); +console.info(`Buffer size: ${bufferSize}`); +audioCapturer.read(bufferSize, true).then((buffer) => { + console.info('buffer read successfully'); +}).catch((err) => { + console.info(`ERROR : ${err}`); }); -``` - -### setRingerMode(deprecated) - -setRingerMode(mode: AudioRingMode, callback: AsyncCallback<void>): void - -Sets the ringer 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. +``` -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY +### getAudioTime8+ -This permission is required only for muting or unmuting the ringer. +getAudioTime(callback: AsyncCallback): void -**System capability**: SystemCapability.Multimedia.Audio.Communication +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------------- | --------- | ----------------------------------- | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL, (err) => { - if (err) { - console.error(`Failed to set the ringer mode.​ ${err}`); - return; - } - console.info('Callback invoked to indicate a successful setting of the ringer mode.'); +audioCapturer.getAudioTime((err, timestamp) => { + console.info(`Current timestamp: ${timestamp}`); }); ``` -### setRingerMode(deprecated) - -setRingerMode(mode: AudioRingMode): Promise<void> - -Sets the ringer 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 [setRingerMode](#setringermode9) in **AudioVolumeGroupManager**. - -**Required permissions**: ohos.permission.ACCESS_NOTIFICATION_POLICY - -This permission is required only for muting or unmuting the ringer. +### getAudioTime8+ -**System capability**: SystemCapability.Multimedia.Audio.Communication +getAudioTime(): Promise -**Parameters** +Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). This API uses a promise to return the result. -| Name | Type | Mandatory | Description | -| ---- | ------------------------------- | --------- | ------------ | -| mode | [AudioRingMode](#audioringmode) | Yes | Ringer mode. | +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the timestamp. | **Example** ```js -audioManager.setRingerMode(audio.AudioRingMode.RINGER_MODE_NORMAL).then(() => { - console.info('Promise returned to indicate a successful setting of the ringer mode.'); +audioCapturer.getAudioTime().then((audioTime) => { + console.info(`AudioFrameworkRecLog: AudioCapturer getAudioTime : Success ${audioTime}`); +}).catch((err) => { + console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); ``` -### getRingerMode(deprecated) - -getRingerMode(callback: AsyncCallback<AudioRingMode>): void +### getBufferSize8+ -Obtains the ringer mode. This API uses an asynchronous callback to return the result. +getBufferSize(callback: AsyncCallback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------------------- | --------- | ---------------------------------------- | -| callback | AsyncCallback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the ringer mode. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size. | **Example** ```js -audioManager.getRingerMode((err, value) => { - if (err) { - console.error(`Failed to obtain the ringer mode.​ ${err}`); - return; +audioCapturer.getBufferSize((err, bufferSize) => { + if (!err) { + console.info(`BufferSize : ${bufferSize}`); + audioCapturer.read(bufferSize, true).then((buffer) => { + console.info(`Buffer read is ${buffer}`); + }).catch((err) => { + console.error(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); + }); } - console.info(`Callback invoked to indicate that the ringer mode is obtained ${value}.`); }); ``` -### getRingerMode(deprecated) - -getRingerMode(): Promise<AudioRingMode> +### getBufferSize8+ -Obtains the ringer mode. This API uses a promise to return the result. +getBufferSize(): Promise -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRingerMode](#getringermode9) in **AudioVolumeGroupManager**. +Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a promise to return the result. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Return value** -| Type | Description | -| ---------------------------------------------- | --------------------------------------- | -| Promise<[AudioRingMode](#audioringmode)> | Promise used to return the ringer mode. | +| Type | Description | +| :--------------- | :-------------------------------------- | +| Promise | Promise used to return the buffer size. | **Example** ```js -audioManager.getRingerMode().then((value) => { - console.info(`Promise returned to indicate that the ringer mode is obtained ${value}.`); +let bufferSize; +audioCapturer.getBufferSize().then((data) => { + console.info(`AudioFrameworkRecLog: getBufferSize :SUCCESS ${data}`); + bufferSize = data; +}).catch((err) => { + console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); ``` -### getDevices(deprecated) - -getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback<AudioDeviceDescriptors>): void +### on('markReach')8+ -Obtains the audio devices with a specific flag. This API uses an asynchronous callback to return the result. +on(type: "markReach", frame: number, callback: Callback<number>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. +Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is invoked. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------------------------------ | --------- | ---------------------------------------- | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | -| callback | AsyncCallback<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Yes | Callback used to return the device list. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { - if (err) { - console.error(`Failed to obtain the device list. ${err}`); - return; +audioCapturer.on('markReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } - console.info('Callback invoked to indicate that the device list is obtained.'); }); ``` -### getDevices(deprecated) - -getDevices(deviceFlag: DeviceFlag): Promise<AudioDeviceDescriptors> +### off('markReach')8+ -Obtains the audio devices with a specific flag. This API uses a promise to return the result. +off(type: 'markReach'): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDevices](#getdevices9) in **AudioRoutingManager**. +Unsubscribes from mark reached events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------- | --------- | ------------------ | -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | --------------------------------------- | -| Promise<[AudioDeviceDescriptors](#audiodevicedescriptors)> | Promise used to return the device list. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'markReach'**. | **Example** ```js -audioManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG).then((data) => { - console.info('Promise returned to indicate that the device list is obtained.'); -}); +audioCapturer.off('markReach'); ``` -### setDeviceActive(deprecated) - -setDeviceActive(deviceType: ActiveDeviceType, active: boolean, callback: AsyncCallback<void>): void +### on('periodReach')8+ -Sets a device to the active state. This API uses an asynchronous callback to return the result. +on(type: "periodReach", frame: number, callback: Callback<number>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. +Subscribes to period reached events. When the number of frames captured reaches the value of the **frame** parameter, a callback is triggered and the specified value is returned. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :---------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback\ | Yes | Callback invoked when the event is triggered. | **Example** ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true, (err) => { - if (err) { - console.error(`Failed to set the active status of the device. ${err}`); - return; +audioCapturer.on('periodReach', 1000, (position) => { + if (position == 1000) { + console.info('ON Triggered successfully'); } - console.info('Callback invoked to indicate that the device is set to the active status.'); }); ``` -### setDeviceActive(deprecated) - -setDeviceActive(deviceType: ActiveDeviceType, active: boolean): Promise<void> +### off('periodReach')8+ -Sets a device to the active state. This API uses a promise to return the result. +off(type: 'periodReach'): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setCommunicationDevice](#setcommunicationdevice9) in **AudioRoutingManager**. +Unsubscribes from period reached events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| active | boolean | Yes | Active state to set. The value **true** means to set the device to the active state, and **false** means the opposite. | - -**Return value** - -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :--------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'periodReach'**. | **Example** - ```js -audioManager.setDeviceActive(audio.ActiveDeviceType.SPEAKER, true).then(() => { - console.info('Promise returned to indicate that the device is set to the active status.'); -}); +audioCapturer.off('periodReach') ``` -### isDeviceActive(deprecated) - -isDeviceActive(deviceType: ActiveDeviceType, callback: AsyncCallback<boolean>): void +### on('stateChange')8+ -Checks whether a device is active. This API uses an asynchronous callback to return the result. +on(type: 'stateChange', callback: Callback): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. +Subscribes to state change events. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Capturer **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------------------------------------------- | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the active state of the device. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------ | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | Callback\<[AudioState](#audiostate8)> | Yes | Callback used to return the state change. | **Example** ```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER, (err, value) => { - if (err) { - console.error(`Failed to obtain the active status of the device. ${err}`); - return; +audioCapturer.on('stateChange', (state) => { + if (state == 1) { + console.info('audio capturer state is: STATE_PREPARED'); + } + if (state == 2) { + console.info('audio capturer state is: STATE_RUNNING'); } - console.info('Callback invoked to indicate that the active status of the device is obtained.'); }); ``` -### isDeviceActive(deprecated) - -isDeviceActive(deviceType: ActiveDeviceType): Promise<boolean> - -Checks whether a device is active. 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 [isCommunicationDeviceActive](#iscommunicationdeviceactive9) in **AudioRoutingManager**. - -**System capability**: SystemCapability.Multimedia.Audio.Device - -**Parameters** +## ToneType9+ -| Name | Type | Mandatory | Description | -| ---------- | ------------------------------------- | --------- | ------------------ | -| deviceType | [ActiveDeviceType](#activedevicetype) | Yes | Audio device type. | +Enumerates the tone types of the player. -**Return value** +**System API**: This is a system API. -| Type | Description | -| ---------------------- | ------------------------------------------------------ | -| Promise<boolean> | Promise used to return the active state of the device. | +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Example** +| Name | Value | Description | +| :----------------------------------------------- | :---- | :-------------------------------------------- | +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available. | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone. | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone. | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | -```js -audioManager.isDeviceActive(audio.ActiveDeviceType.SPEAKER).then((value) => { - console.info(`Promise returned to indicate that the active status of the device is obtained ${value}.`); -}); +## TonePlayer9+ -``` +Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. -### setMicrophoneMute(deprecated) +**System API**: This is a system API. -setMicrophoneMute(mute: boolean, callback: AsyncCallback<void>): void +### load9+ -Mutes or unmutes the microphone. This API uses an asynchronous callback to return the result. +load(type: ToneType, callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. +Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | --------- | ------------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.setMicrophoneMute(true, (err) => { +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { if (err) { - console.error(`Failed to mute the microphone. ${err}`); + console.error(`callback call load failed error: ${err.message}`); return; + } else { + console.info('callback call load success'); } - console.info('Callback invoked to indicate that the microphone is muted.'); }); ``` -### setMicrophoneMute(deprecated) - -setMicrophoneMute(mute: boolean): Promise<void> +### load9+ -Mutes or unmutes the microphone. This API uses a promise to return the result. +load(type: ToneType): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [setMicrophoneMute](#setmicrophonemute9) in **AudioVolumeGroupManager**. +Loads the DTMF tone configuration. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| ---- | ------- | --------- | ------------------------------------------------------------ | -| mute | boolean | Yes | Mute status to set. The value **true** means to mute the microphone, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :--- | :--------------------- | :-------- | ----------- | +| type | [ToneType](#tonetype9) | Yes | Tone type. | **Return value** -| Type | Description | -| ------------------- | ---------------------------------- | -| Promise<void> | Promise used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.setMicrophoneMute(true).then(() => { - console.info('Promise returned to indicate that the microphone is muted.'); +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { + console.info('promise call load '); +}).catch(() => { + console.error('promise call load fail'); }); ``` -### isMicrophoneMute(deprecated) - -isMicrophoneMute(callback: AsyncCallback<boolean>): void +### start9+ -Checks whether the microphone is muted. This API uses an asynchronous callback to return the result. +start(callback: AsyncCallback<void>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. +Starts DTMF tone playing. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | --------- | ------------------------------------------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.isMicrophoneMute((err, value) => { +tonePlayer.start((err) => { if (err) { - console.error(`Failed to obtain the mute status of the microphone. ${err}`); + console.error(`callback call start failed error: ${err.message}`); return; + } else { + console.info('callback call start success'); } - console.info(`Callback invoked to indicate that the mute status of the microphone is obtained ${value}.`); }); ``` -### isMicrophoneMute(deprecated) - -isMicrophoneMute(): Promise<boolean> +### start9+ -Checks whether the microphone is muted. This API uses a promise to return the result. +start(): Promise<void> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isMicrophoneMute](#ismicrophonemute9) in **AudioVolumeGroupManager**. +Starts DTMF tone playing. This API uses a promise to return the result. -**Required permissions**: ohos.permission.MICROPHONE +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the mute status of the microphone. The value **true** means that the microphone is muted, and **false** means the opposite. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.isMicrophoneMute().then((value) => { - console.info(`Promise returned to indicate that the mute status of the microphone is obtained ${value}.`); +tonePlayer.start().then(() => { + console.info('promise call start'); +}).catch(() => { + console.error('promise call start fail'); }); ``` -### on('volumeChange')(deprecated) - -on(type: 'volumeChange', callback: Callback\): void +### stop9+ -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on](#on9) in **AudioVolumeManager**. +stop(callback: AsyncCallback<void>): void -Subscribes to system volume change events. +Stops the tone that is being played. This API uses an asynchronous callback to return the result. **System API**: This is a system API. -Currently, when multiple **AudioManager** instances are used in a single process, only the subscription of the last instance takes effect, and the subscription of other instances is overwritten (even if the last instance does not initiate a subscription). Therefore, you are advised to use a single **AudioManager** instance. - -**System capability**: SystemCapability.Multimedia.Audio.Volume +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'volumeChange'** means the system volume change event, which is triggered when a system volume change is detected. | -| callback | Callback<[VolumeEvent](#volumeevent8)> | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.on('volumeChange', (volumeEvent) => { - console.info(`VolumeType of stream: ${volumeEvent.volumeType} `); - console.info(`Volume level: ${volumeEvent.volume} `); - console.info(`Whether to updateUI: ${volumeEvent.updateUi} `); +tonePlayer.stop((err) => { + if (err) { + console.error(`callback call stop error: ${err.message}`); + return; + } else { + console.error('callback call stop success '); + } }); ``` -### on('ringerModeChange')(deprecated) - -on(type: 'ringerModeChange', callback: Callback\): void +### stop9+ -Subscribes to ringer mode change events. +stop(): Promise<void> -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [on('ringerModeChange')](#onringermodechange9) in **AudioVolumeGroupManager**. +Stops the tone that is being played. This API uses a promise to return the result. **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Communication +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | ----------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'ringerModeChange'** means the ringer mode change event, which is triggered when a ringer mode change is detected. | -| callback | Callback<[AudioRingMode](#audioringmode)> | Yes | Callback used to return the result. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.on('ringerModeChange', (ringerMode) => { - console.info(`Updated ringermode: ${ringerMode}`); +tonePlayer.stop().then(() => { + console.info('promise call stop finish'); +}).catch(() => { + console.error('promise call stop fail'); }); ``` -### on('deviceChange')(deprecated) +### release9+ -on(type: 'deviceChange', callback: Callback): void +release(callback: AsyncCallback<void>): void -Subscribes to device change events. When a device is connected or disconnected, registered clients will receive the callback. +Releases the resources associated with the **TonePlayer** instance. 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 [on](#on9) in **AudioRoutingManager**. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone **Parameters** -| Name | Type | Mandatory | Description | -| :------- | :--------------------------------------------------- | :-------- | :----------------------------------------------------------- | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)\> | Yes | Callback used to return the device update details. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -audioManager.on('deviceChange', (deviceChanged) => { - console.info(`device change type : ${deviceChanged.type} `); - console.info(`device descriptor size : ${deviceChanged.deviceDescriptors.length} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceRole} `); - console.info(`device change descriptor : ${deviceChanged.deviceDescriptors[0].deviceType} `); +tonePlayer.release((err) => { + if (err) { + console.error(`callback call release failed error: ${err.message}`); + return; + } else { + console.info('callback call release success '); + } }); ``` -### off('deviceChange')(deprecated) +### release9+ -off(type: 'deviceChange', callback?: Callback): void +release(): Promise<void> -Unsubscribes from device change events. +Releases the resources associated with the **TonePlayer** instance. 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 [off](#off9) in **AudioRoutingManager**. +**System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device +**System capability**: SystemCapability.Multimedia.Audio.Tone -**Parameters** +**Return value** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'deviceChange'** means the device change event, which is triggered when a device connection status change is detected. | -| callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -audioManager.off('deviceChange', (deviceChanged) => { - console.info('Should be no callback.'); +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); }); + ``` -### on('interrupt')(deprecated) +## ActiveDeviceType(deprecated) -on(type: 'interrupt', interrupt: AudioInterrupt, callback: Callback\): void +Enumerates the active device types. -Subscribes to audio interruption events. When the application's audio is interrupted by another playback event, the application will receive the callback. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [CommunicationDeviceType](#communicationdevicetype9) instead. -Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen for focus changes. However, this API is used in scenarios without audio streams (no **AudioRenderer** instance is created), such as frequency modulation (FM) and voice wakeup. +**System capability**: SystemCapability.Multimedia.Audio.Device + +| Name | Value | Description | +| ------------- | ----- | ------------------------------------------------------------ | +| SPEAKER | 2 | Speaker. | +| BLUETOOTH_SCO | 7 | Bluetooth device using Synchronous Connection Oriented (SCO) links. | + +## InterruptActionType(deprecated) + +Enumerates the returned event types for audio interruption events. > **NOTE** > @@ -6077,40 +6137,30 @@ Same as [on('audioInterrupt')](#onaudiointerrupt9), this API is used to listen f **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** +| Name | Value | Description | +| -------------- | ----- | ------------------------- | +| TYPE_ACTIVATED | 0 | Focus gain event. | +| TYPE_INTERRUPT | 1 | Audio interruption event. | -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | Yes | Callback invoked for the audio interruption event. | +## AudioInterrupt(deprecated) -**Example** +Describes input parameters of audio interruption events. -```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.on('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to gain the audio focus starts.'); - console.info(`Focus gain event: ${InterruptAction} `); - } - if (InterruptAction.actionType === 1) { - console.info('An audio interruption event starts.'); - console.info(`Audio interruption event: ${InterruptAction} `); - } -}); +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. -``` +**System capability**: SystemCapability.Multimedia.Audio.Renderer -### off('interrupt')(deprecated) +| Name | Type | Mandatory | Description | +| --------------- | --------------------------- | --------- | ------------------------------------------------------------ | +| streamUsage | [StreamUsage](#streamusage) | Yes | Audio stream usage. | +| contentType | [ContentType](#contenttype) | Yes | Audio content type. | +| pauseWhenDucked | boolean | Yes | Whether audio playback can be paused during audio interruption. The value **true** means that audio playback can be paused during audio interruption, and **false** means the opposite. | -off(type: 'interrupt', interrupt: AudioInterrupt, callback?: Callback\): void +## InterruptAction(deprecated) -Unsubscribes from audio interruption events. +Describes the callback invoked for audio interruption or focus gain events. > **NOTE** > @@ -6118,26 +6168,9 @@ Unsubscribes from audio interruption events. **System capability**: SystemCapability.Multimedia.Audio.Renderer -**Parameters** - -| Name | Type | Mandatory | Description | -| --------- | --------------------------------------------- | --------- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **'interrupt'** means the audio interruption event, which is triggered when the audio playback of the current application is interrupted by another application. | -| interrupt | AudioInterrupt | Yes | Audio interruption event type. | -| callback | Callback<[InterruptAction](#interruptaction)> | No | Callback invoked for the audio interruption event. | - -**Example** - -```js -let interAudioInterrupt = { - streamUsage:2, - contentType:0, - pauseWhenDucked:true -}; -audioManager.off('interrupt', interAudioInterrupt, (InterruptAction) => { - if (InterruptAction.actionType === 0) { - console.info('An event to release the audio focus starts.'); - console.info(`Focus release event: ${InterruptAction} `); - } -}); -``` \ No newline at end of file +| Name | Type | Mandatory | Description | +| ---------- | ----------------------------------------------------- | --------- | ------------------------------------------------------------ | +| actionType | [InterruptActionType](#interruptactiontypedeprecated) | Yes | Returned event type. The value **TYPE_ACTIVATED** means the focus gain event, and **TYPE_INTERRUPT** means the audio interruption event. | +| type | [InterruptType](#interrupttype) | No | Type of the audio interruption event. | +| hint | [InterruptHint](#interrupthint) | No | Hint provided along with the audio interruption event. | +| activated | boolean | No | Whether the focus is gained or released. The value **true** means that the focus is gained or released, and **false** means that the focus fails to be gained or released. | \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-avsession.md b/en/application-dev/reference/apis/js-apis-avsession.md index 14e4656758b6ef17f98345767a07d7759a691eda..5552792aadadd04fca72d4fe88ffdfc8219b3ec9 100644 --- a/en/application-dev/reference/apis/js-apis-avsession.md +++ b/en/application-dev/reference/apis/js-apis-avsession.md @@ -1,14 +1,16 @@ -# AVSession Management +# @ohos.multimedia.avsession (AVSession Management) The **avSession** module provides APIs for media playback control so that applications can access the system's Media Controller. This module provides the following common features related to media sessions: -- [AVSession](#section652893): used to set session metadata, playback state information, and more. -- [AVSessionController](#section974602): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. +- [AVSession](#avsession): used to set session metadata, playback state information, and more. +- [AVSessionController](#avsessioncontroller): used to obtain session IDs, send commands and events to sessions, and obtain the session metadata and playback state information. > **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. +> +> All the APIs provided by this module are system APIs. ## Modules to Import @@ -28,7 +30,7 @@ Creates a media session. This API uses a promise to return the result. An abilit | Name| Type | Mandatory| Description | | ------ | ------------------------------- | ---- | ------------------------------ | -| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information.| +| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information.| | tag | string | Yes | Custom session name. | | type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video.| @@ -39,13 +41,13 @@ Creates a media session. This API uses a promise to return the result. An abilit | --------------------------------- | ------------------------------------------------------------ | | Promise<[AVSession](#avsession)\> | Promise used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| -**Error codes** +**Error codes** For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -76,18 +78,17 @@ Creates a media session. This API uses an asynchronous callback to return the re | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ------------------------------------------------------------ | -| context| [Context](../../ability/context-userguide.md) | Yes| Application context, which provides application environment information. | +| context| [Context](js-apis-inner-app-context.md) | Yes| Application context, which provides application environment information. | | tag | string | Yes | Custom session name. | | type | [AVSessionType](#avsessiontype) | Yes | Session type, which can be audio or video. | | callback | AsyncCallback<[AVSession](#avsession)\> | Yes | Callback used to return the media session obtained, which can be used to obtain the session ID, set the metadata and playback state information, and send key events.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -127,12 +128,11 @@ Obtains the descriptors of all sessions. This API uses a promise to return the r | Promise\\>\> | Promise used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -168,12 +168,11 @@ Obtains the descriptors of all sessions. This API uses an asynchronous callback | callback | AsyncCallback\>\> | Yes | Callback used to return an array of **AVSessionDescriptor** objects, each of which is read only.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 |Session service exception | +| 6600101 |Session service exception. | **Example** @@ -217,13 +216,12 @@ Creates a session controller based on the session ID. Multiple session controlle | Promise<[AVSessionController](#avsessioncontroller)\> | Promise used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -270,13 +268,12 @@ Creates a session controller based on the session ID. Multiple session controlle | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller created, which can be used to obtain the session ID,
send commands and events to sessions, and obtain metadata and playback state information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -333,14 +330,13 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | Promise | Promise used to return the result. If the cast is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600104 | The remote session connection failed | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600104 | The remote session connection failed. | **Example** @@ -386,14 +382,13 @@ Before calling this API, import the **ohos.multimedia.audio** module to obtain t | callback | AsyncCallback | Yes | Callback used to return the result. If the casting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600104 | The remote session connection failed | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600104 | The remote session connection failed. | **Example** @@ -438,12 +433,11 @@ Subscribes to session creation, session destruction, and top session change even | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | Yes | Callback used to report the session descriptor. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -487,12 +481,11 @@ Unsubscribes from session creation, session destruction, and top session change | callback | (session: [AVSessionDescriptor](#avsessiondescriptor)) => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The **session** parameter in the callback describes a media session. The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -518,12 +511,11 @@ Subscribes to session service death events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -549,12 +541,11 @@ Unsubscribes from session service death events. | callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -587,13 +578,12 @@ Sends a system key event to the top session. This API uses a promise to return t | Promise | Promise used to return the result. If the event is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | **Example** @@ -630,13 +620,12 @@ Sends a system key event to the top session. This API uses an asynchronous callb | callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | **Example** @@ -678,14 +667,13 @@ Sends a system control command to the top session. This API uses a promise to re | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** @@ -733,14 +721,13 @@ Sends a system control command to the top session. This API uses an asynchronous | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600105 | Invalid session command | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600105 | Invalid session command. | +| 6600107 | Too many commands or events. | **Example** @@ -770,7 +757,7 @@ avSession.sendSystemControlCommand(avcommand, function (err) { }); ``` -## AVSession +## AVSession An **AVSession** object is created by calling [avSession.createAVSession](#avsessioncreateavsession). The object enables you to obtain the session ID and set the metadata and playback state. @@ -810,13 +797,12 @@ Sets session metadata. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -860,13 +846,12 @@ Sets session metadata. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -917,13 +902,12 @@ Sets information related to the session playback state. This API uses a promise | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -959,13 +943,12 @@ Sets information related to the session playback state. This API uses an asynchr | callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -997,9 +980,9 @@ Sets a launcher ability. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------------------------- | ---- | ----------------------------------------------------------- | +| ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| **Return value** @@ -1008,13 +991,12 @@ Sets a launcher ability. This API uses a promise to return the result. | Promise | Promise used to return the result. If the setting is successful, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1026,8 +1008,8 @@ let wantAgentInfo = { wants: [ { deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", action: "action1", entities: ["entity1"], type: "MIMETYPE", @@ -1068,19 +1050,18 @@ Sets a launcher ability. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------- | ---- | ----------------------------------------------------------- | -| ability | [WantAgent](js-apis-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| ability | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Application attributes, such as the bundle name, ability name, and deviceID. | +| callback | AsyncCallback | Yes | Callback used to return the result. If the setting is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1092,8 +1073,8 @@ let wantAgentInfo = { wants: [ { deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", action: "action1", entities: ["entity1"], type: "MIMETYPE", @@ -1141,13 +1122,12 @@ Obtains the controller corresponding to this session. This API uses a promise to | Promise<[AVSessionController](#avsessioncontroller)> | Promise used to return the session controller.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1176,13 +1156,12 @@ Obtains the controller corresponding to this session. This API uses an asynchron | callback | AsyncCallback<[AVSessionController](#avsessioncontroller)\> | Yes | Callback used to return the session controller.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1213,13 +1192,12 @@ Obtains information about the output device for this session. This API uses a pr | Promise<[OutputDeviceInfo](#outputdeviceinfo)> | Promise used to return the output device information.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1246,13 +1224,12 @@ Obtains information about the output device for this session. This API uses an a | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1281,13 +1258,12 @@ Activates this session. A session can be used only after being activated. This A | Promise | Promise used to return the result. If the session is activated, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1314,13 +1290,12 @@ Activates this session. A session can be used only after being activated. This A | callback | AsyncCallback | Yes | Callback used to return the result. If the session is activated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1349,13 +1324,12 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | Promise | Promise used to return the result. If the session is deactivated, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1384,13 +1358,12 @@ Deactivates this session. You can use [activate](#activate) to activate the sess | callback | AsyncCallback | Yes | Callback used to return the result. If the session is deactivated, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1419,13 +1392,12 @@ Destroys this session. This API uses a promise to return the result. | Promise | Promise used to return the result. If the session is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1453,13 +1425,12 @@ Destroys this session. This API uses an asynchronous callback to return the resu | callback | AsyncCallback | Yes | Callback used to return the result. If the session is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1489,13 +1460,12 @@ Subscribes to playback command events. | callback | callback: () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1539,13 +1509,12 @@ Subscribes to the seek event. | callback | (time: number) => void | Yes | Callback used for subscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** The session does not exist @@ -1571,13 +1540,12 @@ Subscribes to the event for setting the playback speed. | callback | (speed: number) => void | Yes | Callback used for subscription. The **speed** parameter in the callback indicates the playback speed. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1603,13 +1571,12 @@ Subscribes to the event for setting the loop mode. | callback | (mode: [LoopMode](#loopmode)) => void | Yes | Callback used for subscription. The **mode** parameter in the callback indicates the loop mode. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1635,13 +1602,12 @@ Subscribes to the event for favoriting a media asset. | callback | (assetId: string) => void | Yes | Callback used for subscription. The **assetId** parameter in the callback indicates the media asset ID. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1667,13 +1633,12 @@ Subscribes to the key event. | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | Yes | Callback used for subscription. The **event** parameter in the callback indicates the key event. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1699,13 +1664,12 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1731,13 +1695,12 @@ Unsubscribes from playback command events. | callback | callback: () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1767,13 +1730,12 @@ Unsubscribes from the seek event. | callback | (time: number) => void | No | Callback used for unsubscription. The **time** parameter in the callback indicates the time to seek to, in milliseconds.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1797,13 +1759,12 @@ Unsubscribes from the event for setting the playback speed. | callback | (speed: number) => void | No | Callback used for unsubscription. The **speed** parameter in the callback indicates the playback speed.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1827,13 +1788,12 @@ Unsubscribes from the event for setting loop mode. | callback | (mode: [LoopMode](#loopmode)) => void | No | Callback used for unsubscription. The **mode** parameter in the callback indicates the loop mode.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1857,13 +1817,12 @@ Unsubscribes from the event for favoriting a media asset. | callback | (assetId: string) => void | No | Callback used for unsubscription. The **assetId** parameter in the callback indicates the media asset ID.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1887,13 +1846,12 @@ Unsubscribes from the key event. | callback | (event: [KeyEvent](js-apis-keyevent.md)) => void | No | Callback used for unsubscription. The **event** parameter in the callback indicates the key event.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1917,13 +1875,12 @@ Unsubscribes from playback device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | **Example** @@ -1933,7 +1890,7 @@ session.off('outputDeviceChange'); -## AVSessionController +## AVSessionController An AV session controller is created by calling [avSession.createController](#avsessioncreatecontroller). Through the AV session controller, you can query the session ID, send commands and events to a session, and obtain session metadata and playback state information. @@ -1972,14 +1929,13 @@ Obtains the information related to the playback state. This API uses a promise t | Promise<[AVPlaybackState](#avplaybackstate)\> | Promise used to return the **AVPlaybackState** object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2005,14 +1961,13 @@ Obtains the information related to the playback state. This API uses an asynchro | callback | AsyncCallback<[AVPlaybackState](#avplaybackstate)\> | Yes | Callback used to return the **AVPlaybackState** object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2040,14 +1995,13 @@ Obtains the session metadata. This API uses a promise to return the result. | Promise<[AVMetadata](#avmetadata)\> | Promise used to return the metadata obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2073,14 +2027,13 @@ Obtains the session metadata. This API uses an asynchronous callback to return t | callback | AsyncCallback<[AVMetadata](#avmetadata)\> | Yes | Callback used to return the metadata obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2108,13 +2061,12 @@ Obtains the output device information. This API uses a promise to return the res | Promise<[OutputDeviceInfo](#outputdeviceinfo)\> | Promise used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** ```js @@ -2140,13 +2092,12 @@ Obtains the output device information. This API uses an asynchronous callback to | callback | AsyncCallback<[OutputDeviceInfo](#outputdeviceinfo)\> | Yes | Callback used to return the information obtained.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2175,16 +2126,15 @@ Sends a key event to the session corresponding to this controller. This API uses | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | **Return value** @@ -2218,19 +2168,18 @@ Sends a key event to the session corresponding to this controller. This API uses | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------- | | event | [KeyEvent](js-apis-keyevent.md) | Yes | Key event.| -| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback | Yes | Callback used to return the result. If the event is sent, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | **Example** @@ -2257,19 +2206,18 @@ Obtains the **WantAgent** object saved by the application in the session. This A **Return value** -| Type | Description | -| ------------------------------------------- | ------------------------------------------------------------ | -| Promise<[WantAgent](js-apis-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| +| Type | Description | +| ------------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Promise used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2293,19 +2241,18 @@ Obtains the **WantAgent** object saved by the application in the session. This A **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback<[WantAgent](js-apis-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<[WantAgent](js-apis-app-ability-wantAgent.md)\> | Yes | Callback used to return the object saved by calling [setLaunchAbility](#setlaunchability). The object includes the application attribute, such as the bundle name, ability name, and device ID.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2336,13 +2283,12 @@ Obtains the playback position. | number | Playback position, in milliseconds.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2365,14 +2311,13 @@ Checks whether the session is activated. This API uses a promise to return the r | Promise | Promise used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2399,14 +2344,13 @@ Checks whether the session is activated. This API uses an asynchronous callback | callback | AsyncCallback | Yes | Callback used to return the activation state. If the session is activated, **true** is returned; otherwise, **false** is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2435,13 +2379,12 @@ Destroys this controller. A controller can no longer be used after being destroy | Promise | Promise used to return the result. If the controller is destroyed, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2468,13 +2411,12 @@ Destroys this controller. A controller can no longer be used after being destroy | callback | AsyncCallback | Yes | Callback used to return the result. If the controller is destroyed, **err** is **undefined**; otherwise, **err** is an error object.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2503,14 +2445,13 @@ Obtains valid commands supported by the session. This API uses a promise to retu | Promise\> | Promise used to return a set of valid commands.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2537,14 +2478,13 @@ Obtains valid commands supported by the session. This API uses an asynchronous c | callback | AsyncCallback\\> | Yes | Callback used to return a set of valid commands.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | **Example** @@ -2579,17 +2519,16 @@ Sends a control command to the session through the controller. This API uses a p | Promise | Promise used to return the result. If the command is sent, no value is returned; otherwise, an error object is returned.| **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | **Example** @@ -2628,17 +2567,16 @@ Sends a control command to the session through the controller. This API uses an | callback | AsyncCallback | Yes | Callback used to return the result. If the command is sent, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------- | -| 6600101 | Session service exception | -| 6600102 | The session does not exist | -| 6600103 | The session controller does not exist | -| 6600105 | Invalid session command | -| 6600106 | The session not active | -| 6600107 | Command or event overload | +| 6600101 | Session service exception. | +| 6600102 | The session does not exist. | +| 6600103 | The session controller does not exist. | +| 6600105 | Invalid session command. | +| 6600106 | The session is not activated. | +| 6600107 | Too many commands or events. | **Example** @@ -2680,13 +2618,12 @@ Subscribes to the metadata change event. | callback | (data: [AVMetadata](#avmetadata)) => void | Yes | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2718,13 +2655,12 @@ Subscribes to the playback state change event. | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | Yes | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2755,13 +2691,12 @@ Subscribes to the session destruction event. | callback | () => void | Yes | Callback used for subscription. If the subscription is successful, **err** is **undefined**; otherwise, **err** is an error object. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2787,13 +2722,12 @@ Subscribes to the session activation state change event. | callback | (isActive: boolean) => void | Yes | Callback used for subscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the service is activated, and **false** means the opposite. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ----------------------------- | -| 6600101 | Session service exception | -| 6600103 |The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 |The session controller does not exist. | **Example** @@ -2819,13 +2753,12 @@ Subscribes to valid command changes. | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | Yes | Callback used for subscription. The **commands** parameter in the callback is a set of valid commands. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ------------------------------ | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2852,13 +2785,12 @@ Subscribes to output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | Yes | Callback used for subscription. The **device** parameter in the callback indicates the output device information. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ----------------------- | -| 6600101 | Session service exception | -| 6600103 | The session controller does not exist | +| 6600101 | Session service exception. | +| 6600103 | The session controller does not exist. | **Example** @@ -2884,12 +2816,11 @@ Unsubscribes from metadata changes. | callback | (data: [AVMetadata](#avmetadata)) => void | No | Callback used for subscription. The **data** parameter in the callback indicates the changed metadata.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2913,12 +2844,11 @@ Unsubscribes from playback state changes. | callback | (state: [AVPlaybackState](#avplaybackstate)) => void | No | Callback used for subscription. The **state** parameter in the callback indicates the changed playback state.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2942,12 +2872,11 @@ Unsubscribes from the session destruction event. | callback | () => void | No | Callback used for unsubscription. If the unsubscription is successful, **err** is **undefined**; otherwise, **err** is an error object.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -2971,12 +2900,11 @@ Unsubscribes from session activation state changes. | callback | (isActive: boolean) => void | No | Callback used for unsubscription. The **isActive** parameter in the callback specifies whether the session is activated. The value **true** means that the session is activated, and **false** means the opposite.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message| | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3000,12 +2928,11 @@ Unsubscribes from valid command changes. | callback | (commands: Array<[AVControlCommandType](#avcontrolcommandtype)\>) => void | No | Callback used for unsubscription. The **commands** parameter in the command is a set of valid commands.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID| Error Message | | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3029,12 +2956,11 @@ Unsubscribes from output device changes. | callback | (device: [OutputDeviceInfo](#outputdeviceinfo)) => void | No | Callback used for unsubscription. The **device** parameter in the callback indicates the output device information.
The callback parameter is optional. If it is not specified, the specified event is no longer listened for all sessions. | **Error codes** - For details about the error codes, see [AVSession Management Error Codes](../errorcodes/errorcode-avsession.md). | ID | Error Message | | -------- | ---------------- | -| 6600101 | Session service exception | +| 6600101 | Session service exception. | **Example** @@ -3132,7 +3058,7 @@ Describes the media metadata. | album | string | No | Album name. | | writer | string | No | Writer. | | composer | string | No | composer. | -| duration | string | No | Media duration, in ms. | +| duration | number | No | Media duration, in ms. | | mediaImage | image.PixelMap | string | No | Pixel map or image path (local path or network path) of the image. | | publishDate | Date | No | Release date. | | subtitle | string | No | Subtitle. | @@ -3217,10 +3143,10 @@ Enumerates the error codes used in the media session. | Name | Value | Description | | ------------------------------ | ------- | ------------------------------- | -| ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception | -| ERR_CODE_SESSION_NOT_EXIST | 6600102 | The session does not exist | -| ERR_CODE_CONTROLLER_NOT_EXIST | 6600103 | The session controller does not exist | -| ERR_CODE_REMOTE_CONNECTION_ERR | 6600104 | The remote session connection failed | -| ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command | -| ERR_CODE_SESSION_INACTIVE | 6600106 | The session not active | -| ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Command or event overload | +| ERR_CODE_SERVICE_EXCEPTION | 6600101 | Session service exception. | +| ERR_CODE_SESSION_NOT_EXIST | 6600102 | The session does not exist. | +| ERR_CODE_CONTROLLER_NOT_EXIST | 6600103 | The session controller does not exist. | +| ERR_CODE_REMOTE_CONNECTION_ERR | 6600104 | The remote session connection failed. | +| ERR_CODE_COMMAND_INVALID | 6600105 | Invalid session command. | +| ERR_CODE_SESSION_INACTIVE | 6600106 | The session is not activated. | +| ERR_CODE_MESSAGE_OVERLOAD | 6600107 | Too many commands or events. | diff --git a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md index c03f26ef70644a43ec969a5288843838b266f883..6080d2c9bc52e30b6fa987f9cb65ea9b42a28024 100644 --- a/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -1,4 +1,4 @@ -# Background Task Management +# @ohos.backgroundTaskManager (Background Task Management) The **BackgroundTaskManager** module provides APIs to manage background tasks. @@ -159,12 +159,12 @@ Requests a continuous task from the system. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -187,7 +187,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -205,7 +205,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; @@ -217,13 +217,13 @@ function callback(err, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -251,11 +251,11 @@ Requests a continuous task from the system. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description | -| --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| bgMode | [BackgroundMode](#backgroundmode8) | Yes | Background mode requested. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** @@ -276,7 +276,7 @@ let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -297,17 +297,17 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "com.example.myapplication.MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -339,7 +339,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -365,7 +365,7 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callbac Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; function callback(err, data) { @@ -376,7 +376,7 @@ function callback(err, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { backgroundTaskManager.stopBackgroundRunning(this.context, callback); } @@ -395,7 +395,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -422,10 +422,10 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() Stage model: ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.backgroundTaskManager'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { console.info("Operation stopBackgroundRunning succeeded"); @@ -452,14 +452,14 @@ Provides the information about the suspension delay. **System capability**: SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask -| Name | Description | -| ----------------------- | --------------------- | -| DATA_TRANSFER | Data transfer. | -| AUDIO_PLAYBACK | Audio playback. | -| AUDIO_RECORDING | Audio recording. | -| LOCATION | Positioning and navigation. | -| BLUETOOTH_INTERACTION | Bluetooth-related task. | -| MULTI_DEVICE_CONNECTION | Multi-device connection. | -| WIFI_INTERACTION | WLAN-related (system API).| -| VOIP | Audio and video calls (system API). | -| TASK_KEEPING | Computing task (effective only for specific devices). | +| Name | Value | Description | +| ----------------------- | ---- | --------------------- | +| DATA_TRANSFER | 1 | Data transfer. | +| AUDIO_PLAYBACK | 2 | Audio playback. | +| AUDIO_RECORDING | 3 | Audio recording. | +| LOCATION | 4 | Positioning and navigation. | +| BLUETOOTH_INTERACTION | 5 | Bluetooth-related task. | +| MULTI_DEVICE_CONNECTION | 6 | Multi-device connection. | +| WIFI_INTERACTION | 7 | WLAN-related.
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). | diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md index 2d7e9fab8a62e7d68dae92e66359a2704414bc01..41d13ba5741ecf4324b1f4c859fb2a0a4bdf1d19 100644 --- a/en/application-dev/reference/apis/js-apis-battery-info.md +++ b/en/application-dev/reference/apis/js-apis-battery-info.md @@ -1,11 +1,9 @@ -# Battery Info +# @ohos.batteryInfo (Battery 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. - -The Battery Info module provides APIs for querying the charger type, battery health status, and battery charging status. +The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status. +> **NOTE**
+> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -13,67 +11,100 @@ The Battery Info module provides APIs for querying the charger type, battery hea import batteryInfo from '@ohos.batteryInfo'; ``` -## System Capabilities - -SystemCapability.PowerManager.BatteryManager - ## Attributes Describes battery information. -| Name | Type | Readable | Writable | Description | -| ----------------------------- | ----------------------------------------- | -------- | -------- | ------------------------------------------------------------ | -| batterySOC | number | Yes | No | Battery state of charge (SoC) of the current device, in unit of percentage. | -| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the current device. | -| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the current device. | -| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the current device. | -| voltage | number | Yes | No | Battery voltage of the current device, in unit of microvolt. | -| technology | string | Yes | No | Battery technology of the current device. | -| batteryTemperature | number | Yes | No | Battery temperature of the current device, in unit of 0.1°C. | -| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | - -**Example** - -```js -import batteryInfo from '@ohos.batteryInfo'; -var batterySoc = batteryInfo.batterySOC; -``` - +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Type | Readable| Writable| Description | +| --------------- | ------------------- | ---- | ---- | ---------------------| +| batterySOC | number | Yes | No | Battery state of charge (SoC) of the device, in unit of percentage. | +| chargingStatus | [BatteryChargeState](#batterychargestate) | Yes | No | Battery charging state of the device. | +| healthStatus | [BatteryHealthState](#batteryhealthstate) | Yes | No | Battery health state of the device. | +| pluggedType | [BatteryPluggedType](#batterypluggedtype) | Yes | No | Charger type of the device. | +| voltage | number | Yes | No | Battery voltage of the device, in unit of microvolt. | +| technology | string | Yes | No | Battery technology of the device. | +| batteryTemperature | number | Yes | No | Battery temperature of the device, in unit of 0.1°C. | +| isBatteryPresent7+ | boolean | Yes | No | Whether the battery is supported or present. | +| batteryCapacityLevel9+ | [BatteryCapacityLevel](#batterycapacitylevel9) | Yes | No | Battery level of the device. | +| estimatedRemainingChargeTime9+ | number | Yes | No | Estimated time for fully charging the current device, in unit of milliseconds. | +| totalEnergy9+ | number | Yes | No | Total battery capacity of the device, in unit of mAh. This is a system API. | +| nowCurrent9+ | number | Yes | No | Battery current of the device, in unit of mA. This is a system API. | +| remainingEnergy9+ | number | Yes | No | Remaining battery capacity of the device, in unit of mAh. This is a system API.| ## BatteryPluggedType Enumerates charger types. -| Name | Default Value | Description | -| -------- | ------------- | ----------------- | -| NONE | 0 | Unknown type. | -| AC | 1 | AC charger. | -| USB | 2 | USB charger. | -| WIRELESS | 3 | Wireless charger. | +**System capability**: SystemCapability.PowerManager.BatteryManager.Core +| Name | Value | Description | +| -------- | ---- | ----------------- | +| NONE | 0 | Unknown type | +| AC | 1 | AC charger| +| USB | 2 | USB charger | +| WIRELESS | 3 | Wireless charger| ## BatteryChargeState Enumerates charging states. -| Name | Default Value | Description | -| ------- | ------------- | --------------------------------- | -| NONE | 0 | Unknown state. | -| ENABLE | 1 | The battery is being charged. | -| DISABLE | 2 | The battery is not being charged. | -| FULL | 3 | The battery is fully charged. | +**System capability**: SystemCapability.PowerManager.BatteryManager.Core +| Name | Value | Description | +| ------- | ---- | --------------- | +| NONE | 0 | Unknown state. | +| ENABLE | 1 | The battery is being charged. | +| DISABLE | 2 | The battery is not being charged. | +| FULL | 3 | The battery is fully charged.| ## BatteryHealthState Enumerates battery health states. -| Name | Default Value | Description | -| ----------- | ------------- | ------------------------------------ | -| UNKNOWN | 0 | Unknown state. | -| GOOD | 1 | The battery is in the healthy state. | -| OVERHEAT | 2 | The battery is overheated. | -| OVERVOLTAGE | 3 | The battery voltage is over high. | -| COLD | 4 | The battery temperature is low. | -| DEAD | 5 | The battery is dead. | - +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value | Description | +| ----------- | ---- | -------------- | +| UNKNOWN | 0 | Unknown state. | +| GOOD | 1 | The battery is in the healthy state. | +| OVERHEAT | 2 | The battery is overheated. | +| OVERVOLTAGE | 3 | The battery voltage is over high. | +| COLD | 4 | The battery temperature is low. | +| DEAD | 5 | The battery is dead.| + +## BatteryCapacityLevel9+ + +Enumerates battery levels. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value| Description | +| -------------- | ------ | ---------------------------- | +| LEVEL_NONE | 0 | Unknown battery level. | +| LEVEL_FULL | 1 | Full battery level. | +| LEVEL_HIGH | 2 | High battery level. | +| LEVEL_NORMAL | 3 | Normal battery level.| +| LEVEL_LOW | 4 | Low battery level. | +| LEVEL_CRITICAL | 5 | Ultra-low battery level.| + +## CommonEventBatteryChangedCode9+ + +Enumerates keys for querying the additional information about the **COMMON_EVENT_BATTERY_CHANGED** event. + +**System capability**: SystemCapability.PowerManager.BatteryManager.Core + +| Name | Value| Description | +| -------------------- | ------ | -------------------------------------------------- | +| EXTRA_SOC | 0 | Remaining battery level in percentage. | +| EXTRA_VOLTAGE | 1 | Battery voltage of the device. | +| EXTRA_TEMPERATURE | 2 | Battery temperature of the device. | +| EXTRA_HEALTH_STATE | 3 | Battery health status of the device. | +| EXTRA_PLUGGED_TYPE | 4 | Type of the charger connected to the device. | +| EXTRA_MAX_CURRENT | 5 | Maximum battery current of the device. | +| EXTRA_MAX_VOLTAGE | 6 | Maximum battery voltage of the device. | +| EXTRA_CHARGE_STATE | 7 | Battery charging status of the device. | +| EXTRA_CHARGE_COUNTER | 8 | Number of battery charging times of the device. | +| EXTRA_PRESENT | 9 | Whether the battery is supported by the device or installed.| +| EXTRA_TECHNOLOGY | 10 | Battery technology of the device. | diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md new file mode 100644 index 0000000000000000000000000000000000000000..2bb3159fc3912a6a1fe272451ce31aa812052432 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md @@ -0,0 +1,287 @@ +# @ohos.batteryStatistics (Battery Statistics) + +The **batteryStatistics** module provides APIs for querying software and hardware power consumption statistics. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are system APIs. + +## Modules to Import + +```js +import batteryStats from '@ohos.batteryStatistics'; +``` + +## batteryStats.getBatteryStats + +getBatteryStats(): Promise + +Obtains the power consumption information list, using a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Return value** + +| Type | Description | +| ----------------------------------------------------- | ------------------------------- | +| Promise> | Promise used to return the power consumption information list.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +batteryStats.getBatteryStats() +.then(data => { + console.info('battery statistics info: ' + data); +}) +.catch(err => { + console.error('get battery statisitics failed, err: ' + err); +}); +``` + +## batteryStats.getBatteryStats + +getBatteryStats(callback: AsyncCallback): void + +Obtains the power consumption information list. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the array of power consumption information obtained. If the operation failed, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +batteryStats.getBatteryStats((err, data) => { + if (typeof err === 'undefined') { + console.info('battery statistics info: ' + data); + } else { + console.error('get battery statisitics failed, err: ' + err); + } +}); +``` + +## batteryStats.getAppPowerValue + +getAppPowerValue(uid: number): number + +Obtains the power consumption of an application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------- | +| uid | number | Yes | Application UID.| + +**Return value** + +| Type | Description | +| ------ | --------------------------------- | +| number | Power consumption of the application with this UID, in unit of mAh.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getAppPowerValue(10021); + console.info('battery statistics value of app is: ' + value); +} catch(err) { + console.error('get battery statisitics value of app failed, err: ' + err); +} +``` + +## batteryStats.getAppPowerPercent + +getAppPowerPercent(uid: number): number + +Obtains the proportion of the power consumption of an application. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------- | +| uid | number | Yes | Application UID.| + +**Return value** + +| Type | Description | +| ------ | ------------------------- | +| number | Proportion of the power consumption of an application with this UID.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var percent = batteryStats.getAppPowerPercent(10021); + console.info('battery statistics percent of app is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of app failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerValue + +getHardwareUnitPowerValue(type: ConsumptionType): number + +Obtains the power consumption of a hardware unit according to the consumption type. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------------------ | +| number | Power consumption of the hardware unit corresponding to the power consumption type, in unit of mAh.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getHardwareUnitPowerValue(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## batteryStats.getHardwareUnitPowerPercent + +getHardwareUnitPowerPercent(type: ConsumptionType): number + +Obtains the proportion of the power consumption of a hardware unit according to the power consumption type. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------- | +| type | [ConsumptionType](#consumptiontype) | Yes | Power consumption type.| + +**Return value** + +| Type | Description | +| ------ | ---------------------------------- | +| number | Proportion of the power consumption of the hardware unit corresponding to the power consumption type.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-batteryStatistics.md). + +| Code| Error Message | +| -------- | -------------- | +| 4600101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var value = batteryStats.getHardwareUnitPowerPercent(ConsumptionType.CONSUMPTION_TYPE_SCREEN); + console.info('battery statistics percent of hardware is: ' + percent); +} catch(err) { + console.error('get battery statisitics percent of hardware failed, err: ' + err); +} +``` + +## BatteryStatsInfo + +Describes the device power consumption information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +### Attributes + +| Name | Type | Readable| Writable| Description | +| ----- | ----------------------------------- | ---- | ---- | ---------------------- | +| uid | number | Yes | No | UID related to power consumption information. | +| type | [ConsumptionType](#consumptiontype) | Yes | No | Power consumption type. | +| power | number | Yes | No | Power consumption, in unit of mAh.| + +## ConsumptionType + +Enumerates power consumption types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.PowerManager.BatteryStatistics + +| Name | Value | Description | +| -------------------------- | ---- | ----------------------------- | +| CONSUMPTION_TYPE_INVALID | -17 | Unknown type. | +| CONSUMPTION_TYPE_APP | -16 | Power consumption of an application. | +| CONSUMPTION_TYPE_BLUETOOTH | -15 | Power consumption of Bluetooth. | +| CONSUMPTION_TYPE_IDLE | -14 | Power consumption when the CPU is idle.| +| CONSUMPTION_TYPE_PHONE | -13 | Power consumption of a phone call. | +| CONSUMPTION_TYPE_RADIO | -12 | Power consumption of wireless communication. | +| CONSUMPTION_TYPE_SCREEN | -11 | Power consumption of the screen. | +| CONSUMPTION_TYPE_USER | -10 | Power consumption of the user. | +| CONSUMPTION_TYPE_WIFI | -9 | Power consumption of Wi-Fi. | diff --git a/en/application-dev/reference/apis/js-apis-bluetooth.md b/en/application-dev/reference/apis/js-apis-bluetooth.md index b852a673ab6ca120497e1c40443d19990cfbd74b..aa9e1937cd66e83262211280f42f11f468e2d200 100644 --- a/en/application-dev/reference/apis/js-apis-bluetooth.md +++ b/en/application-dev/reference/apis/js-apis-bluetooth.md @@ -1,8 +1,9 @@ -# Bluetooth +# @ohos.bluetooth The **Bluetooth** module provides classic Bluetooth capabilities and Bluetooth Low Energy (BLE) scan and advertising. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -202,7 +203,7 @@ Obtains the connection state of a profile. | Name | Type | Mandatory | Description | | --------- | --------- | ---- | ------------------------------------- | -| ProfileId | profileId | Yes | ID of the target profile, for example, **PROFILE_A2DP_SOURCE**.| +| ProfileId | profileId | Yes | ID of the profile to obtain, for example, **PROFILE_A2DP_SOURCE**.| **Return value** @@ -1280,10 +1281,6 @@ Obtains the connected devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - -No value is returned. - **Return value** | Type | Description | @@ -2695,8 +2692,6 @@ Obtains all services of the remote BLE device. This API uses a promise to return **System capability**: SystemCapability.Communication.Bluetooth.Core -**Parameters** - **Return value** | Type | Description | @@ -2830,7 +2825,7 @@ Reads the descriptor contained in the specific characteristic of the remote BLE | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ----------------------- | | descriptor | [BLEDescriptor](#bledescriptor) | Yes | Descriptor to read. | -| callback | AsyncCallback<[BLECharacteristic](#blecharacteristic)> | Yes | Callback invoked to return the descriptor read.| +| callback | AsyncCallback<[BLEDescriptor](#bledescriptor)> | Yes | Callback invoked to return the descriptor read.| **Return value** @@ -3309,7 +3304,7 @@ Enumerates the scan modes. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ---- | --------------- | | SCAN_MODE_NONE | 0 | No scan mode. | | SCAN_MODE_CONNECTABLE | 1 | Connectable mode. | @@ -3324,7 +3319,7 @@ Enumerates the pairing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------ | ---- | ------ | | BOND_STATE_INVALID | 0 | Invalid pairing.| | BOND_STATE_BONDING | 1 | Pairing. | @@ -3350,7 +3345,7 @@ Enumerates the SPP link types. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------- | ---- | ------------- | | SPP_RFCOMM | 0 | Radio frequency communication (RFCOMM) link type.| @@ -3510,7 +3505,7 @@ Enumerates the profile connection states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ---- | -------------- | | STATE_DISCONNECTED | 0 | Disconnected. | | STATE_CONNECTING | 1 | Connecting.| @@ -3558,7 +3553,7 @@ Enumerates the scan duty options. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------ | | SCAN_MODE_LOW_POWER | 0 | Low-power mode, which is the default value.| | SCAN_MODE_BALANCED | 1 | Balanced mode. | @@ -3571,7 +3566,7 @@ Enumerates the hardware match modes of BLE scan filters. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ---------------------------------------- | | MATCH_MODE_AGGRESSIVE | 1 | Hardware reports the scan result with a lower threshold of signal strength and few number of matches in a duration. This is the default value.| | MATCH_MODE_STICKY | 2 | Hardware reports the scan result with a higher threshold of signal strength and sightings. | @@ -3596,7 +3591,7 @@ Enumerates the Bluetooth states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ------------------ | | STATE_OFF | 0 | Bluetooth is turned off. | | STATE_TURNING_ON | 1 | Bluetooth is being turned on. | @@ -3641,7 +3636,7 @@ Defines the content of a BLE advertisement packet. | Name | Type | Readable | Writable | Description | | ---------------- | ------------------- | ---- | ---- | ------------------ | -| manufactureId | Array<string> | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| +| manufactureId | number | Yes | Yes | Manufacturer ID allocated by the Bluetooth SIG.| | manufactureValue | ArrayBuffer | Yes | Yes | Manufacturer data. | @@ -3713,7 +3708,7 @@ Enumerates the major classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------------- | ------ | ---------- | | MAJOR_MISC | 0x0000 | Miscellaneous device. | | MAJOR_COMPUTER | 0x0100 | Computer. | @@ -3734,7 +3729,7 @@ Enumerates the major and minor classes of Bluetooth devices. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------------------------- | ------ | --------------- | | COMPUTER_UNCATEGORIZED | 0x0100 | Unclassified computer. | | COMPUTER_DESKTOP | 0x0104 | Desktop computer. | @@ -3830,7 +3825,7 @@ Enumerates the A2DP playing states. **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ------ | ------- | | STATE_NOT_PLAYING | 0x0000 | Not playing. | | STATE_PLAYING | 0x0001 | Playing.| @@ -3842,9 +3837,9 @@ Enumerates the Bluetooth profiles. API version 9 is added with **PROFILE_HID_HOS **System capability**: SystemCapability.Communication.Bluetooth.Core -| Name | Default Value | Description | +| Name | Value | Description | | -------------------------------- | ------ | --------------- | -| PROFILE_A2DP_SOURCE | 0x0001 | A2DP profile.| -| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 0x0004 | HFP profile. | -| PROFILE_HID_HOST9+ | 0x0006 | Human Interface Device (HID) profile. | -| PROFILE_PAN_NETWORK9+ | 0x0007 | PAN profile. | +| PROFILE_A2DP_SOURCE | 1 | A2DP profile.| +| PROFILE_HANDS_FREE_AUDIO_GATEWAY | 4 | HFP profile. | +| PROFILE_HID_HOST9+ | 6 | Human Interface Device (HID) profile. | +| PROFILE_PAN_NETWORK9+ | 7 | PAN profile. | diff --git a/en/application-dev/reference/apis/js-apis-brightness.md b/en/application-dev/reference/apis/js-apis-brightness.md index 6bbea8b08a752972bcc9354b63841831ae837a88..bd003733a485c1601ac251697461e78b863976a8 100644 --- a/en/application-dev/reference/apis/js-apis-brightness.md +++ b/en/application-dev/reference/apis/js-apis-brightness.md @@ -1,10 +1,12 @@ -# Brightness +# @ohos.brightness (Screen Brightness) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
-> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -The Brightness module provides an API for setting the screen brightness. +The **brightness** module provides an API for setting the screen brightness. +> **NOTE** +> +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -18,18 +20,30 @@ setValue(value: number): void Sets the screen brightness. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. -**System capability:** SystemCapability.PowerManager.DisplayPowerManager +**System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** -| Name | Type | Mandatory | Description | -| ----- | ------ | ---- | ----------- | -| value | number | Yes | Brightness value, ranging from **0** to **255**.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------------- | +| value | number | Yes | Brightness value. The value ranges from 0 to 255.| + +**Error codes** + +For details about the error codes, see [Screen Brightness Error Codes](../errorcodes/errorcode-brightness.md). + +| Code | Error Message | +|---------|---------| +| 4700101 | Operation failed. Cannot connect to service.| **Example** ```js -brightness.setValue(128); +try { + brightness.setValue(128); +} catch(err) { + console.error('set brightness failed, err: ' + err); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index c055385384fc9c1a28818fc0a1bd23a355e83076..72e65e53e63380ef4ea0aa9b33796e236bc7ee84 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -1,12 +1,12 @@ -# Buffer +# @ohos.buffer (Buffer) -> **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. +A **Buffer** object represents a byte sequence of a fixed length. It is used to store binary data. -A **Buffer** object represents a fixed-length sequence of bytes. It is used to store binary data. +You can use the APIs provided by the Buffer module to process images and a large amount of binary data, and receive or upload files. -You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, and receive or upload files. +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -14,23 +14,31 @@ You can use the APIs provided by the **Buffer** module to process images and a l import buffer from '@ohos.buffer'; ``` -## Buffer +## BufferEncoding -### Attributes +Enumerates the supported encoding formats of strings. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Length of the buffer, in bytes.| -| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| -| byteOffset | number | Yes| No| Offset of the buffer in the memory pool.| +| Encoding Format | Description | +| ------- | -------------------- | +| 'ascii' | ASCII format, which is case insensitive.| +| 'utf8' | UTF-8 format, which is case insensitive.| +| 'utf-8' | UTF-8 format, which is case insensitive.| +| 'utf16le' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs2' | UTF-16 little-endian format, which is case insensitive.| +| 'ucs-2' | UTF-16 little-endian format, which is case insensitive.| +| 'base64' | Base64 format, which is case insensitive.| +| 'base64url' | Base64 format, which is case insensitive.| +| 'latin1' | ASCII format, which is case insensitive.| +| 'binary' | Binary format, which is case insensitive.| +| 'hex' | Hexadecimal format, which is case insensitive.| -### alloc +## buffer.alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer -Allocates and initializes a **Buffer** instance of the specified size. +Creates and initializes a **Buffer** instance of the specified length. **System capability**: SystemCapability.Utils.Lang @@ -38,9 +46,9 @@ Allocates and initializes a **Buffer** instance of the specified size. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| -| fill | string \| Buffer \| number | No| Pre-filled value. The default value is **0**.| -| encoding | BufferEncoding | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| +| fill | string \| Buffer \| number | No| Value to be filled in the buffer. The default value is **0**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.| **Return value** @@ -58,12 +66,12 @@ let buf2 = buffer.alloc(5, 'a'); let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); ``` -### allocUninitializedFromPool +## buffer.allocUninitializedFromPool allocUninitializedFromPool(size: number): Buffer -Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it. -To initialize the **Buffer** instance, call **fill()**. +Creates a **Buffer** instance of the specified size from the buffer pool, without initializing it. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -71,7 +79,7 @@ To initialize the **Buffer** instance, call **fill()**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes| Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -88,11 +96,12 @@ let buf = buffer.allocUninitializedFromPool(10); buf.fill(0); ``` -### allocUninitialized +## buffer.allocUninitialized allocUninitialized(size: number): Buffer -Allocates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +Creates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool. +You need to use [fill()](#fill) to initialize the **Buffer** instance created. **System capability**: SystemCapability.Utils.Lang @@ -100,7 +109,7 @@ Allocates a **Buffer** instance of the specified size, without initializing it. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| size | number | Yes|Size of the **Buffer** instance to allocate, in bytes.| +| size | number | Yes|Size of the **Buffer** instance to create, in bytes.| **Return value** @@ -117,7 +126,7 @@ let buf = buffer.allocUninitialized(10); buf.fill(0); ``` -### byteLength +## buffer.byteLength byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number @@ -130,7 +139,7 @@ Obtains the number of bytes of a string based on the encoding format. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.| -| encoding | BufferEncoding | No| Encoding format. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format of the string. The default value is **utf-8**.| **Return value** @@ -148,7 +157,7 @@ console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8') // Print: ½ + ¼ = ¾: 9 characters, 12 bytes ``` -### compare +## buffer.compare compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1 @@ -179,15 +188,14 @@ let buf1 = buffer.from('1234'); let buf2 = buffer.from('0123'); let res = buf1.compare(buf2); -console.log(Number(res).toString()); -// Print 1 +console.log(Number(res).toString()); // Print 1. ``` -### concat +## buffer.concat concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer -Concatenates an array of **Buffer** instances into a new instance of the specified length. +Concatenates an array of **Buffer** instances of the specified length into a new instance. **System capability**: SystemCapability.Utils.Lang @@ -196,7 +204,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.| -| totalLength | number | No| Total length of the new **Buffer** instance, in bytes.| +| totalLength | number | No| Total length of bytes to be copied.| **Return value** @@ -204,6 +212,14 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi | -------- | -------- | | Buffer | **Buffer** instance created.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "totalLength" is out of range. | + **Example** ```ts @@ -215,7 +231,7 @@ let buf = buffer.concat([buf1, buf2]); console.log(buf.toString('hex')); // 3132333461626364 ``` -### from +## buffer.from from(array: number[]): Buffer; @@ -244,11 +260,11 @@ let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); console.log(buf.toString('hex')); // 627566666572 ``` -### from +## buffer.from from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer -Creates a **Buffer** instance that shares memory with the specified array of **Buffer** instances. +Creates a **Buffer** instance of the specified length that shares memory with **arrayBuffer**. **System capability**: SystemCapability.Utils.Lang @@ -266,6 +282,14 @@ Creates a **Buffer** instance that shares memory with the specified array of **B | -------- | -------- | | Buffer | **Buffer** instance with shared memory.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[byteOffset/length]" is out of range. | + **Example** ```ts @@ -275,7 +299,7 @@ let ab = new ArrayBuffer(10); let buf = buffer.from(ab, 0, 2); ``` -### from +## buffer.from from(buffer: Buffer | Uint8Array): Buffer @@ -287,7 +311,7 @@ Creates a **Buffer** instance with the copy of another instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy. | +| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy.| **Return value** @@ -304,7 +328,7 @@ let buf1 = buffer.from('buffer'); let buf2 = buffer.from(buf1); ``` -### from +## buffer.from from(object: Object, offsetOrEncoding: number | string, length: number): Buffer @@ -317,8 +341,8 @@ Creates a **Buffer** instance based on the specified object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | object | Object | Yes| Object that supports **Symbol.toPrimitive** or **valueOf()**.| -| offsetOrEncoding | number \| string | No| Byte offset or encoding format.| -| length | number | No| Length of the **Buffer** instance to create.| +| offsetOrEncoding | number \| string | Yes| Byte offset or encoding format.| +| length | number | Yes| Length of the **Buffer** instance to create.| **Return value** @@ -331,10 +355,10 @@ Creates a **Buffer** instance based on the specified object. ```ts import buffer from '@ohos.buffer'; -let buf = buffer.from(new String('this is a test')); +let buf = buffer.from(new String('this is a test'), 'utf8', 14); ``` -### from +## buffer.from from(string: String, encoding?: BufferEncoding): Buffer @@ -347,7 +371,7 @@ Creates a **Buffer** instance based on a string in the given encoding format. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | string | String | Yes| String.| -| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format of the string. The default value is **utf-8**.| **Return value** @@ -364,11 +388,11 @@ let buf1 = buffer.from('this is a test'); let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex'); console.log (buf1.toString()); // Print: this is a test -console.log(buf2.toString()); +console.log (buf2.toString()); // print: this is a test ``` -### isBuffer +## buffer.isBuffer isBuffer(obj: Object): boolean @@ -400,7 +424,7 @@ buffer.isBuffer([]); // false buffer.isBuffer(new Uint8Array(1024)); // false ``` -### isEncoding +## buffer.isEncoding isEncoding(encoding: string): boolean @@ -431,6 +455,70 @@ console.log(buffer.isEncoding('utf/8').toString()); // Print: false console.log(buffer.isEncoding('').toString()); // Print: false ``` +## buffer.transcode + +transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer + +Transcodes the given **Buffer** or **Uint8Array** object from one encoding format to another. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | Buffer \| Uint8Array | Yes| Instance to encode.| +| fromEnc | string | Yes| Current encoding format.| +| toEnc | string | Yes| Target encoding format.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Buffer | New **Buffer** instance in the target encoding format.| + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.alloc(50); +let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); +console.log(newBuf.toString('ascii')); +``` + +## Buffer + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Length of the **Buffer** instance, in bytes.| +| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| +| byteOffset | number | Yes| No| Offset of the **Buffer** instance in the memory pool.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. | + +**Example** + +```ts +import buffer from '@ohos.buffer'; + +let buf = buffer.from("1236"); +console.log(JSON.stringify(buf.length)); +let arrayBuffer = buf.buffer; +console.log(JSON.stringify(new Uint8Array(arrayBuffer))); +console.log(JSON.stringify(buf.byteOffset)); +``` + ### compare compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1 @@ -453,7 +541,15 @@ Compares this **Buffer** instance with another instance. | Type| Description| | -------- | -------- | -| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted. | +| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[targetStart/targetEnd/sourceStart/sourceEnd]" is out of range. | **Example** @@ -491,6 +587,14 @@ Copies data at the specified position in this **Buffer** instance to the specifi | -------- | -------- | | number | Total length of the data copied, in bytes.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[targetStart/sourceStart/sourceEnd]" is out of range. | + **Example** ```ts @@ -516,6 +620,13 @@ Creates and returns an iterator that contains key-value pairs of this **Buffer** **System capability**: SystemCapability.Utils.Lang +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Key of the iterator.| +| number | Value of the iterator.| + **Example** ```ts @@ -558,7 +669,6 @@ let buf3 = buffer.from('ABCD'); console.log(buf1.equals(buf2).toString()); // Print: true console.log(buf1.equals(buf3).toString()); // Print: false - ``` ### fill @@ -576,7 +686,7 @@ Fills this **Buffer** instance at the specified position. By default, data is fi | value | string \| Buffer \| Uint8Array \| number | Yes| Value to fill.| | offset | number | No| Offset to the start position in this **Buffer** instance where data is filled. The default value is **0**.| | end | number | No| Offset to the end position in this **Buffer** instance (not inclusive). The default value is the length of this **Buffer** instance.| -| encoding | BufferEncoding | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **value** is a string). The default value is **utf-8**.| **Return value** @@ -584,6 +694,14 @@ Fills this **Buffer** instance at the specified position. By default, data is fi | -------- | -------- | | Buffer | **Buffer** instance filled with the specified value.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[offset/end]" is out of range. | + **Example** ```ts @@ -607,8 +725,8 @@ Checks whether this **Buffer** instance contains the specified value. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| -| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. | -| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| **Return value** @@ -639,8 +757,8 @@ Obtains the index of the first occurrence of the specified value in this **Buffe | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| -| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. | -| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| **Return value** @@ -670,7 +788,7 @@ Creates and returns an iterator that contains the keys of this **Buffer** instan | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator.| +| IterableIterator<number> | Iterator created.| **Example** @@ -696,8 +814,8 @@ Obtains the index of the last occurrence of the specified value in this **Buffer | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | value | string \| number \| Buffer \| Uint8Array | Yes| Value to match.| -| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**. | -| encoding | BufferEncoding | No| Encoding format used if **value** is a string. The default value is **utf-8**.| +| byteOffset | number | No| Number of bytes to skip before starting to check data. If the offset is a negative number, data is checked from the end of the **Buffer** instance. The default value is **0**.| +| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format used if **value** is a string. The default value is **utf-8**.| **Return value** @@ -720,7 +838,7 @@ console.log(buf.lastIndexOf('buffer').toString()); // Print: 17 readBigInt64BE(offset?: number): bigint -Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset. +Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the specified offset. **System capability**: SystemCapability.Utils.Lang @@ -736,6 +854,14 @@ Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at t | -------- | -------- | | bigint | A signed, big-endian 64-bit Big integer. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -744,6 +870,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigInt64BE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigInt64BE(0x0102030405060708n, 0); ``` ### readBigInt64LE @@ -766,6 +895,14 @@ Reads a signed, little-endian 64-bit Big integer from this **Buffer** instance a | -------- | -------- | | bigint | A signed, little-endian 64-bit Big integer. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -774,6 +911,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigInt64LE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigInt64BE(0x0102030405060708n, 0); ``` ### readBigUInt64BE @@ -796,6 +936,14 @@ Reads an unsigned, big-endian 64-bit Big integer from this **Buffer** instance a | -------- | -------- | | bigint | An unsigned, big-endian 64-bit Big integer. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -804,6 +952,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigUInt64BE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); ``` ### readBigUInt64LE @@ -826,6 +977,14 @@ Reads an unsigned, little-endian 64-bit Big integer from this **Buffer** instanc | -------- | -------- | | bigint | An unsigned, little-endian 64-bit Big integer. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -834,6 +993,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x69, 0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77, 0x78]); console.log(buf.readBigUInt64LE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeBigUInt64BE(0xdecafafecacefaden, 0); ``` ### readDoubleBE @@ -856,6 +1018,14 @@ Reads a big-endian double-precision floating-point number from this **Buffer** i | -------- | -------- | | number | A big-endian double-precision floating-point number. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -863,6 +1033,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readDoubleBE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeDoubleBE(123.456, 0); ``` ### readDoubleLE @@ -885,6 +1058,14 @@ Reads a little-endian double-precision floating-point number from this **Buffer* | -------- | -------- | | number | A little-endian double-precision floating-point number. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -892,6 +1073,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readDoubleLE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(8); +buf1.writeDoubleLE(123.456, 0); ``` ### readFloatBE @@ -914,6 +1098,14 @@ Reads a big-endian single-precision floating-point number from this **Buffer** i | -------- | -------- | | number | A big-endian single-precision floating-point number. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -921,6 +1113,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readFloatBE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeFloatBE(0xcabcbcbc, 0); ``` ### readFloatLE @@ -943,6 +1138,14 @@ Reads a little-endian single-precision floating-point number from this **Buffer* | -------- | -------- | | number | A little-endian single-precision floating-point number. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -950,6 +1153,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); console.log(buf.readFloatLE(0).toString()); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeFloatLE(0xcabcbcbc, 0); ``` ### readInt8 @@ -972,6 +1178,14 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs | -------- | -------- | | number | A signed 8-bit integer. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -980,6 +1194,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([-1, 5]); console.log(buf.readInt8(0).toString()); // Print: -1 console.log(buf.readInt8(1).toString()); // Print: 5 + +let buf1 = buffer.allocUninitializedFromPool(2); +buf1.writeInt8(0x12); ``` ### readInt16BE @@ -1002,6 +1219,14 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s | -------- | -------- | | number | A signed, big-endian 16-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1009,6 +1234,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 5]); console.log(buf.readInt16BE(0).toString()); // Print: 5 + +let buf1 = buffer.alloc(2); +buf1.writeInt16BE(0x1234, 0); ``` ### readInt16LE @@ -1031,6 +1259,14 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th | -------- | -------- | | number | A signed, little-endian 16-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1038,6 +1274,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 5]); console.log(buf.readInt16LE(0).toString()); // Print: 1280 + +let buf1 = buffer.alloc(2); +buf1.writeInt16BE(0x1234, 0); ``` ### readInt32BE @@ -1060,6 +1299,14 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s | -------- | -------- | | number | A signed, big-endian 32-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1067,6 +1314,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 0, 0, 5]); console.log(buf.readInt32BE(0).toString()); // Print: 5 + +let buf1 = buffer.alloc(4); +buf1.writeInt32BE(0x12345678, 0); ``` ### readInt32LE @@ -1089,6 +1339,14 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th | -------- | -------- | | number | A signed, little-endian 32-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1096,6 +1354,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0, 0, 0, 5]); console.log(buf.readInt32LE(0).toString()); // Print: 83886080 + +let buf1 = buffer.alloc(4); +buf1.writeInt32BE(0x12345678, 0); ``` ### readIntBE @@ -1120,6 +1381,14 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi | -------- | -------- | | number | Data read.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | + **Example** ```ts @@ -1128,6 +1397,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from("ab"); let num = buf.readIntBE(0, 1); console.log(num.toString()); // 97 + +let buf1 = buffer.allocUninitializedFromPool(6); +buf1.writeIntBE(0x123456789011, 0, 6); ``` @@ -1153,6 +1425,14 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi | -------- | -------- | | number | Data read.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | + **Example** ```ts @@ -1160,6 +1440,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readIntLE(0, 6).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(6); +buf1.writeIntLE(0x123456789011, 0, 6); ``` ### readUInt8 @@ -1183,6 +1466,14 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o | -------- | -------- | | number | An unsigned 8-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1191,6 +1482,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([1, -2]); console.log(buf.readUInt8(0).toString()); console.log(buf.readUInt8(1).toString()); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt8(0x42); ``` ### readUInt16BE @@ -1214,6 +1508,14 @@ Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at th | -------- | -------- | | number | An unsigned, big-endian 16-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1222,6 +1524,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56]); console.log(buf.readUInt16BE(0).toString(16)); console.log(buf.readUInt16BE(1).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt16BE(0x1234, 0); ``` ### readUInt16LE @@ -1245,6 +1550,14 @@ Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at | -------- | -------- | | number | An unsigned, little-endian 16-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1253,6 +1566,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56]); console.log(buf.readUInt16LE(0).toString(16)); console.log(buf.readUInt16LE(1).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt16LE(0x1234, 0); ``` ### readUInt32BE @@ -1276,6 +1592,14 @@ Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at th | -------- | -------- | | number | An unsigned, big-endian 32-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1283,6 +1607,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); console.log(buf.readUInt32BE(0).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt32BE(0x12345678, 0); ``` ### readUInt32LE @@ -1306,6 +1633,14 @@ Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at | -------- | -------- | | number | An unsigned, little-endian 32-bit integer.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "offset" is out of range. | + **Example** ```ts @@ -1313,6 +1648,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78]); console.log(buf.readUInt32LE(0).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUInt32LE(0x12345678, 0); ``` ### readUIntBE @@ -1337,6 +1675,14 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi | -------- | -------- | | number | Data read.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | + **Example** ```ts @@ -1344,6 +1690,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readUIntBE(0, 6).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUIntBE(0x13141516, 0, 4); ``` ### readUIntLE @@ -1366,7 +1715,15 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi | Type| Description| | -------- | -------- | -| number | Data read.| +| number | A signed, big-endian 64-bit integer.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[offset/byteLength]" is out of range. | **Example** @@ -1375,6 +1732,9 @@ import buffer from '@ohos.buffer'; let buf = buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); console.log(buf.readUIntLE(0, 6).toString(16)); + +let buf1 = buffer.allocUninitializedFromPool(4); +buf1.writeUIntLE(0x13141516, 0, 4); ``` ### subarray @@ -1428,6 +1788,14 @@ Interprets this **Buffer** instance as an array of unsigned 16-bit integers and | -------- | -------- | | Buffer | **Buffer** instance swapped.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200009 | Buffer size must be a multiple of 16-bits | + **Example** ```ts @@ -1455,6 +1823,14 @@ Interprets this **Buffer** instance as an array of unsigned 32-bit integers and | -------- | -------- | | Buffer | **Buffer** instance swapped.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200009 | Buffer size must be a multiple of 32-bits | + **Example** ```ts @@ -1482,6 +1858,14 @@ Interprets this **Buffer** instance as an array of unsigned 64-bit integers and | -------- | -------- | | Buffer | **Buffer** instance swapped.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200009 | Buffer size must be a multiple of 64-bits | + **Example** ```ts @@ -1566,7 +1950,7 @@ Creates and returns an iterator that contains the values of this **Buffer** inst | Type| Description| | -------- | -------- | -| IterableIterator<number> | Iterator created.| +| IterableIterator<number> | Iterator.| **Example** @@ -1594,7 +1978,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci | str | string | Yes| String to write.| | offset | number | No| Number of bytes to skip before starting to write data. The default value is **0**.| | length | number | No| Maximum number of bytes to write. The default value is the length of the **Buffer** instance minus the offset.| -| encoding | BufferEncoding | No| Encoding format of the string. The default value is **utf-8**.| +| encoding | string | No| Encoding format of the string. The default value is **utf-8**.| **Return value** @@ -1603,6 +1987,14 @@ Writes a string of the specified length to this **Buffer** instance at the speci | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[offset/length]" is out of range. | + **Example** ```ts @@ -1639,6 +2031,14 @@ Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at th | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1670,6 +2070,14 @@ Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1701,6 +2109,14 @@ Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1732,6 +2148,14 @@ Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1763,6 +2187,14 @@ Writes a big-endian double-precision floating-point number to this **Buffer** in | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1794,6 +2226,14 @@ Writes a little-endian double-precision floating-point number to this **Buffer** | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1825,6 +2265,14 @@ Writes a big-endian single-precision floating-point number to this **Buffer** in | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1857,6 +2305,14 @@ Writes a little-endian single-precision floating-point number to this **Buffer** | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1888,6 +2344,14 @@ Writes a signed 8-bit integer to this **Buffer** instance at the specified offse | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1921,6 +2385,14 @@ Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the sp | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1953,6 +2425,14 @@ Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -1984,6 +2464,14 @@ Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the sp | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -2016,6 +2504,14 @@ Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -2048,6 +2544,14 @@ Writes a big-endian signed value of the specified length to this **Buffer** inst | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | + **Example** ```ts @@ -2081,6 +2585,14 @@ Writes a little-endian signed value of the specified length to this **Buffer** i | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | + **Example** ```ts @@ -2112,6 +2624,14 @@ Writes an unsigned 8-bit integer to this **Buffer** instance at the specified of | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -2146,6 +2666,14 @@ Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -2178,6 +2706,14 @@ Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -2210,6 +2746,14 @@ Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -2241,6 +2785,14 @@ Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset]" is out of range. | + **Example** ```ts @@ -2273,6 +2825,14 @@ Writes an unsigned big-endian value of the specified length to this **Buffer** i | -------- | -------- | | number | Number of bytes written.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | + **Example** ```ts @@ -2305,45 +2865,21 @@ Writes an unsigned little-endian value of the specified length to this **Buffer* | -------- | -------- | | number | Number of bytes written.| -**Example** - -```ts -import buffer from '@ohos.buffer'; - -let buf = buffer.allocUninitializedFromPool(6); -buf.writeUIntLE(0x1234567890ab, 0, 6); -``` - -### transcode - -transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer - -Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| source | Buffer \| Uint8Array | Yes| Instance to transcode. | -| fromEnc | string | Yes| Current encoding format.| -| toEnc | string | Yes| Target encoding format.| +**Error codes** -**Return value** +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). -| Type| Description| +| ID| Error Message| | -------- | -------- | -| Buffer | New **Buffer** instance in the target encoding format.| +| 10200001 | The value of "[value/offset/byteLength]" is out of range. | **Example** ```ts import buffer from '@ohos.buffer'; -let buf = buffer.alloc(50); -let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii'); -console.log(newBuf.toString('ascii')); +let buf = buffer.allocUninitializedFromPool(6); +buf.writeUIntLE(0x1234567890ab, 0, 6); ``` ## Blob @@ -2374,7 +2910,6 @@ A constructor used to create a **Blob** instance. **Example** - ```ts import buffer from '@ohos.buffer'; @@ -2382,7 +2917,7 @@ let blob = new buffer.Blob(['a', 'b', 'c']); let blob1 = new buffer.Blob(['a', 'b', 'c'], {endings:'native', type: 'MIME'}); ``` -### encode +### arrayBuffer arrayBuffer(): Promise<ArrayBuffer> @@ -2396,14 +2931,14 @@ Puts the **Blob** data into an **ArrayBuffer** instance. This API uses a promise | Promise<ArrayBuffer> | Promise used to return the **ArrayBuffer** containing the **Blob** data.| **Example** - ```ts - let blob = new buffer.Blob(['a', 'b', 'c']); - let pro = blob.arrayBuffer(); - pro.then(val => { - let uintarr = new Uint8Array(val); - console.log(uintarr.toString()); - }); - ``` +```ts +let blob = new buffer.Blob(['a', 'b', 'c']); +let pro = blob.arrayBuffer(); +pro.then(val => { + let uintarr = new Uint8Array(val); + console.log(uintarr.toString()); +}); +``` ### slice slice(start?: number, end?: number, type?: string): Blob @@ -2423,20 +2958,20 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc **Return value** | Type| Description| | -------- | -------- | -| Blob | **Blob** instance created. | +| Blob | New **Blob** instance created.| **Example** - ```ts - let blob = new buffer.Blob(['a', 'b', 'c']); - let blob2 = blob.slice(0, 2); - let blob3 = blob.slice(0, 2, "MIME"); - ``` +```ts +let blob = new buffer.Blob(['a', 'b', 'c']); +let blob2 = blob.slice(0, 2); +let blob3 = blob.slice(0, 2, "MIME"); +``` ### text text(): Promise<string> -Returns text in UTF-8 format. +Returns text in UTF-8 format. This API uses a promise to return the result. **System capability**: SystemCapability.Utils.Lang @@ -2446,10 +2981,10 @@ Returns text in UTF-8 format. | Promise<string> | Promise used to return the text encoded in UTF-8.| **Example** - ```ts - let blob = new buffer.Blob(['a', 'b', 'c']); - let pro = blob.text(); - pro.then(val => { - console.log(val) - }); - ``` +```ts +let blob = new buffer.Blob(['a', 'b', 'c']); +let pro = blob.text(); +pro.then(val => { + console.log(val) +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md index 7f6d5b0196b97a252564d4c29f761aefa2117db3..315e7c0f045ba3b26520ed2a69f41f242872b8e6 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @@ -1,6 +1,6 @@ # AbilityInfo -Unless otherwise specified, ability information is obtained through **GET_BUNDLE_DEFAULT**. +The **AbilityInfo** module provides information about an ability. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,13 +8,13 @@ Unless otherwise specified, ability information is obtained through **GET_BUNDLE ## AbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [AbilityInfo](js-apis-bundleManager-abilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-AbilityInfo](js-apis-bundleManager-abilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------- | -------------------------------------------------------- | ---- | ---- | ----------------------------------------- | -| bundleName | string | Yes | No | Bundle name of the application. | +| bundleName | string | Yes | No | Bundle name. | | name | string | Yes | No | Ability name. | | label | string | Yes | No | Ability name visible to users. | | description | string | Yes | No | Ability description. | @@ -25,17 +25,17 @@ Unless otherwise specified, ability information is obtained through **GET_BUNDLE | process | string | Yes | No | Process in which the ability runs. If this parameter is not set, the bundle name is used.| | targetAbility | string | Yes | No | Target ability that the ability alias points to.
This attribute can be used only in the FA model.| | backgroundModes | number | Yes | No | Background service mode of the ability.
This attribute can be used only in the FA model. | -| isVisible | boolean | Yes | No | Whether the ability can be called by other applications. | +| isVisible | boolean | Yes | No | Whether the ability can be called by other bundles. | | formEnabled | boolean | Yes | No | Whether the ability provides the service widget capability.
This attribute can be used only in the FA model.| | type | AbilityType | Yes | No | Ability type.
This attribute can be used only in the FA model. | -| orientation | DisplayOrientation | Yes | No | Ability display orientation. | -| launchMode | LaunchMode | Yes | No | Ability launch mode. | +| orientation | [DisplayOrientation](js-apis-Bundle.md#displayorientationdeprecated) | Yes | No | Ability display orientation. | +| launchMode | [LaunchMode](js-apis-Bundle.md#launchmodedeprecated) | Yes | No | Ability launch mode. | | permissions | Array\ | Yes | No | Permissions required for other applications to call the ability.
The value is obtained by passing **GET_ABILITY_INFO_WITH_PERMISSION**.| | deviceTypes | Array\ | Yes | No | Device types supported by the ability. | | deviceCapabilities | Array\ | Yes | No | Device capabilities required for the ability. | | readPermission | string | Yes | No | Permission required for reading the ability data.
This attribute can be used only in the FA model.| | writePermission | string | Yes | No | Permission required for writing data to the ability.
This attribute can be used only in the FA model.| -| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing **GET_ABILITY_INFO_WITH_APPLICATION**.| +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application configuration information.
The value is obtained by passing [GET_ABILITY_INFO_WITH_APPLICATION](js-apis-Bundle.md).| | uri | string | Yes | No | URI of the ability.
This attribute can be used only in the FA model.| | labelId | number | Yes | No | Ability label ID. | | subType | AbilitySubType | Yes | No | Subtype of the template that can be used by the ability.
This attribute can be used only in the FA model.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md index fb5aa288eaaf2f8eb65940f33902906c04c654c2..c1667a66eb011d24a1b7ce79061eab0f454604a3 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @@ -1,6 +1,6 @@ # ApplicationInfo -The **ApplicationInfo** module provides application information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **ApplicationInfo** module provides application information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,30 +8,30 @@ The **ApplicationInfo** module provides application information. Unless otherwis ## ApplicationInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ApplicationInfo](js-apis-bundleManager-applicationInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework -| Name | Type | Readable| Writable| Description | -| -------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | -| name | string | Yes | No | Application name. | -| description | string | Yes | No | Application description. | -| descriptionId | number | Yes | No | Application description ID. | -| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | -| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | -| label | string | Yes | No | Application label. | -| labelId(deprecated) | string | Yes | No | Application label ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **labelIndex** instead.| -| icon | string | Yes | No | Application icon. | -| iconId(deprecated) | string | Yes | No | Application icon ID.
\- **NOTE**: This attribute is deprecated from API version 9. Use **iconIndex** instead.| -| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | -| supportedModes | number | Yes | No | Running modes supported by the application. | -| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | -| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_PERMISSION**.| -| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | -| entryDir | string | Yes | No | Path for storing application files. | -| codePath8+ | string | Yes | No | Installation directory of the application. | -| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing **GET_APPLICATION_INFO_WITH_METADATA**.| -| removable8+ | boolean | Yes | No | Whether the application is removable. | -| accessTokenId8+ | number | Yes | No | Access token ID of the application. | -| uid8+ | number | Yes | No | UID of the application. | -| entityType8+ | string | Yes | No | Entity type of the application. | +| Name | Type | Readable | Writable | Description | +|----------------------------|------------------------------------------------------------------------|-----|-----|----------------------------------------------------------------------------------------------------------------------------------------------------------------------| +| name | string | Yes | No | Application name. | +| description | string | Yes | No | Application description. | +| descriptionId | number | Yes | No | Application description ID. | +| systemApp | boolean | Yes | No | Whether the application is a system application. The default value is **false**. | +| enabled | boolean | Yes | No | Whether the application is enabled. The default value is **true**. | +| label | string | Yes | No | Application label. | +| labelId | string | Yes | No | Application label ID. | +| icon | string | Yes | No | Application icon. | +| iconId | string | Yes | No | Application icon ID. | +| process | string | Yes | No | Process in which the application runs. If this parameter is not set, the bundle name is used. | +| supportedModes | number | Yes | No | Modes supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units. | +| moduleSourceDirs | Array\ | Yes | No | Relative paths for storing application resources. | +| permissions | Array\ | Yes | No | Permissions required for accessing the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_PERMISSION](js-apis-Bundle.md). | +| moduleInfos | Array\<[ModuleInfo](js-apis-bundle-ModuleInfo.md)> | Yes | No | Application module information. | +| entryDir | string | Yes | No | Path for storing application files. | +| codePath8+ | string | Yes | No | Installation directory of the application. | +| metaData8+ | Map\> | Yes | No | Custom metadata of the application.
The value is obtained by passing [GET_APPLICATION_INFO_WITH_METADATA](js-apis-Bundle.md). | +| removable8+ | boolean | Yes | No | Whether the application is removable. | +| accessTokenId8+ | number | Yes | No | Access token ID of the application. | +| uid8+ | number | Yes | No | UID of the application. | +| entityType8+ | string | Yes | No | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| 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 f1d0240513193f217b71ccfc900acc5a211d07c3..c14419e736e1c2142fb47157826c42fb0d5cff34 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @@ -1,18 +1,16 @@ # BundleInfo -The **BundleInfo** module provides bundle information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **BundleInfo** module provides bundle information. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.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. - - ## BundleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-BundleInfo](js-apis-bundleManager-bundleInfo.md) instead. - **System capability**: SystemCapability.BundleManager.BundleFramework +**System capability**: SystemCapability.BundleManager.BundleFramework | Name | Type | Readable| Writable| Description | | --------------------------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | @@ -25,7 +23,7 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie | 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**.| +| reqPermissionDetails | Array\<[ReqPermissionDetail](#reqpermissiondetaildeprecated)> | 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. | @@ -38,7 +36,7 @@ The **BundleInfo** module provides bundle information. Unless otherwise specifie | 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. | +| reqPermissionStates8+ | Array\ | Yes | No | Permission grant state. The value **0** means that the request is successful, and **-1** means the opposite. | @@ -54,7 +52,7 @@ Provides the detailed information of the permissions to request from the system. | --------------------- | ----------------------- | ---- | ---- | ---------------------- | | name | string | Yes | Yes | Name of the permission to request. | | reason | string | Yes | Yes | Reason for requesting the permission. | -| usedScene | [UsedScene](#usedscene) | Yes | Yes | Application scenario and timing for using the permission.| +| usedScene | [UsedScene](#usedscenedeprecated) | Yes | Yes | Application scenario and timing for using the permission.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md index 9ab7fb823fc00cc663c909c48fca2e6cee047545..0570453b5cb9c1bfa6a1e0f0acb9dda16562005e 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md +++ b/en/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @@ -12,7 +12,7 @@ The **BundleInstaller** module provides APIs for you to install, uninstall, and install(bundleFilePaths: Array<string>, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; -Installs a bundle. This API uses an asynchronous callback to return the result. +Installs a bundle. Multiple HAP files can be installed. This API uses an asynchronous callback to return the result. **Required permissions** @@ -28,9 +28,33 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | --------------- | ---------------------------------------------------- | ---- | ------------------------------------------------------------ | -| bundleFilePaths | Array<string> | Yes | Paths where the HAP files of the bundle are stored. Each path should point to a relative directory of the current bundle's data directory.| -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle installation. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status. | +| bundleFilePaths | Array<string> | Yes | Sandbox path where the HAP files of the bundle are stored. For details about how to obtain the sandbox path, see [Obtaining the Sandbox Path](#obtaining-the-sandbox-path).| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle installation. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status. | + +**Example** + +```ts +import bundle from '@ohos.bundle'; +let hapFilePaths = ['/data/storage/el2/base/haps/entry/files/']; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.install(hapFilePaths, installParam, err => { + if (err) { + console.error('install failed:' + JSON.stringify(err)); + } else { + console.info('install successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## BundleInstaller.uninstall(deprecated) @@ -55,16 +79,39 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle uninstall. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| - +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle uninstall. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the installation status.| + +**Example** + +```ts +import bundle from '@ohos.bundle'; +let bundleName = 'com.example.myapplication'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.uninstall(bundleName, installParam, err => { + if (err) { + console.error('uninstall failed:' + JSON.stringify(err)); + } else { + console.info('uninstall successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## BundleInstaller.recover(deprecated) > This API is deprecated since API version 9. You are advised to use [recover](js-apis-installer.md) instead. recover(bundleName: string, param: InstallParam, callback: AsyncCallback<InstallStatus>): void; -Recovers a bundle. This API uses an asynchronous callback to return the result. +Recovers a bundle. This API uses an asynchronous callback to return the result. After a pre-installed bundle is uninstalled, you can call this API to recover it. **Required permissions** @@ -81,12 +128,37 @@ SystemCapability.BundleManager.BundleFramework | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------------------- | ---- | ---------------------------------------------- | | bundleName | string | Yes | Bundle name. | -| param | [InstallParam](#installparam) | Yes | Parameters required for bundle recovering. | -| callback | AsyncCallback<[InstallStatus](#installstatus)> | Yes | Callback used to return the installation status.| +| param | [InstallParam](#installparamdeprecated) | Yes | Parameters required for bundle recovery. | +| callback | AsyncCallback<[InstallStatus](#installstatusdeprecated)> | Yes | Callback used to return the recovery status.| + +**Example** + +```ts +import bundle from '@ohos.bundle'; + +let bundleName = 'com.example.myapplication'; +let installParam = { + userId: 100, + isKeepData: false, + installFlag: 1, +}; + +bundle.getBundleInstaller().then(installer=>{ + installer.recover(bundleName, installParam, err => { + if (err) { + console.error('recover failed:' + JSON.stringify(err)); + } else { + console.info('recover successfully.'); + } + }); +}).catch(error => { + console.error('getBundleInstaller failed. Cause: ' + error.message); +}); +``` ## InstallParam(deprecated) -Describes the parameters required for bundle installation or uninstall. +Describes the parameters required for bundle installation, recovery, or uninstall. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -100,7 +172,7 @@ Describes the parameters required for bundle installation or uninstall. ## InstallStatus(deprecated) -Describes the bundle installation status. +Describes the bundle installation or uninstall status. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -110,3 +182,27 @@ Describes the bundle installation status. | ------------- | ------------------------------------------------------------ | ---- | ---- | ------------------------------ | | status | bundle.[InstallErrorCode](js-apis-Bundle.md#installerrorcode) | Yes | No | Installation or uninstall error code. | | statusMessage | string | Yes | No | Installation or uninstall status message.| + +## Obtaining the Sandbox Path +For the FA model, the sandbox path of a bundle can be obtained using the APIs in [Context](js-apis-inner-app-context.md). For the sage model, the sandbox path can be obtained using the attribute in [Context](js-apis-ability-context.md#abilitycontext). The following describes how to obtain the sandbox path. + +**Example** +``` ts +// Stage model +import Ability from '@ohos.application.Ability'; +class MainAbility extends Ability { + onWindowStageCreate(windowStage) { + let context = this.context; + let pathDir = context.filesDir; + console.info('sandbox path is ' + pathDir); + } +} + +// FA model +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); +context.getFilesDir().then((data) => { + let pathDir = data; + console.info('sandbox path is ' + pathDir); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md index 246f1420fbb328cab877fa7e83476a558530b9f9..e54a37c697a4b44df566aa8f517a4b0befd8297b 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md +++ b/en/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @@ -14,6 +14,6 @@ The **CustomizeData** module provides custom metadata. | Name | Type | Readable| Writable| Description | | ------------------ | ------ | ---- | ---- | ---------------- | -| name | string | Yes | Yes | Custom metadata name.| -| value | string | Yes | Yes | Custom metadata value. | -| extra8+ | string | Yes | Yes | Custom metadata resources. | +| name | string | Yes | Yes | Key that identifies a data element.| +| value | string | Yes | Yes | Value of the data element. | +| extra8+ | string | Yes | Yes | Custom format of the data element. The value is an index to the resource that identifies the data. | 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 54f43e7a56376caf4ea623d358fc27bec2d54dbc..b20de58d074a83dea5cb0992e21087ae64b990bb 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -1,6 +1,6 @@ # ElementName -The **ElementName** module provides the element name information, which can be obtained through [Context.getElementName](js-apis-Context.md). +The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.md). > **NOTE** > @@ -8,7 +8,9 @@ The **ElementName** module provides the element name information, which can be o ## ElementName(deprecated) -> This API is deprecated since API version 9. You are advised to use [ElementName](js-apis-bundleManager-elementName.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ElementName](js-apis-bundleManager-elementName.md) instead. + +Describes the element name information, which identifies the basic information about an ability and is obtained through [Context.getElementName](js-apis-inner-app-context.md). **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md index 0e252cc3fe46c45114a2d9cb9738c6ec3e0a9ffe..5540aa2bc56b9f8e34fda11d11048b8177816b95 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @@ -1,6 +1,6 @@ # HapModuleInfo -The **HapModuleInfo** module provides module information. Unless otherwise specified, all attributes are obtained through **GET_BUNDLE_DEFAULT**. +The **HapModuleInfo** module provides information about an HAP module. Unless otherwise specified, the information is obtained through [GET_BUNDLE_DEFAULT](js-apis-Bundle.md). > **NOTE** > @@ -8,7 +8,7 @@ The **HapModuleInfo** module provides module information. Unless otherwise speci ## HapModuleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework diff --git a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md index 781b34f89b8a954c5f0be626fcbfe0d3fc5ab3f8..18707feeb05902b5740b00544b3a23a43c09acce 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @@ -7,10 +7,9 @@ The **ModuleInfo** module provides module information of an application. > 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. ## ModuleInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework - | Name | Type | Readable| Writable| Description | | --------------- | ------ | ---- | ---- | -------- | | moduleName | string | Yes | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md index aa7b5da045a32bb53590a8b3a5f9ec1f3dffce0e..ded02c772794179d9e8276292ab1be939a208d8f 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md +++ b/en/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @@ -8,7 +8,7 @@ The **PermissionDef** module provides permission details defined in the configur ## **PermissionDef**(deprecated) -> This API is deprecated since API version 9. You are advised to use [PermissionDef](js-apis-bundleManager-permissionDef.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-PermissionDef](js-apis-bundleManager-permissionDef.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -17,6 +17,6 @@ The **PermissionDef** module provides permission details defined in the configur | Name | Type | Readable| Writable| Description | | -------------- | ------ | ---- | ---- | -------------- | | permissionName | string | Yes | No | Name of the permission. | -| grantMode | number | Yes | No | Grant mode of the permission.| +| grantMode | number | Yes | No | Grant mode of the permission. The value **0** means that the system automatically grants the permission after the application installation, and **1** means that the application needs to dynamically request the permission from the user.| | labelId | number | Yes | No | Label ID of the permission. | | descriptionId | number | Yes | No | Description ID of the permission. | diff --git a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index adf30d8b7442dd67e822f200a0114f93957bd892..1a603da33b3403dafbac79e1bfcd31c5dde9896c 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -1,16 +1,14 @@ -# ShortcutInfo(deprecated) +# shortcutInfo -The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute). +The **shortcutInfo** module defines shortcut information configured in the configuration file. For the FA model, the shortcut information is configured in the [config.json](../../quick-start/application-configuration-file-overview-fa.md) file. For the stage model, the information is configured in the configuration file under **resources/base/profile** in the development view. > **NOTE** > -> This module is deprecated since API version 9. You are advised to use [ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. -> > 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. ## ShortcutWant(deprecated) -> This API is deprecated since API version 9. You are advised to use [ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutWant](js-apis-bundleManager-shortcutInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -23,7 +21,7 @@ The **ShortcutInfo** module provides shortcut information defined in the configu ## ShortcutInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-ShortcutInfo](js-apis-bundleManager-shortcutInfo.md) instead. **System capability**: SystemCapability.BundleManager.BundleFramework @@ -35,10 +33,12 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | hostAbility | string | Yes | No | Local ability information of the shortcut. | | icon | string | Yes | No | Icon of the shortcut. | | iconId8+ | number | Yes | No | Icon ID of the shortcut. | -| label | string | Yes | No | Label of the shortcut. | -| labelId8+ | number | Yes | No | Label ID of the shortcut. | +| label | string | Yes | No | Name of the shortcut. | +| labelId8+ | number | Yes | No | Name ID of the shortcut. | | disableMessage | string | Yes | No | Message displayed when the shortcut is disabled. | -| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | +| wants | Array<[ShortcutWant](#shortcutwant)> | Yes | No | Want list for the shortcut. | | isStatic | boolean | Yes | No | Whether the shortcut is static. | | isHomeShortcut | boolean | Yes | No | Whether the shortcut is a home shortcut.| | isEnabled | boolean | Yes | No | Whether the shortcut is enabled. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index ffde8d4356caee1dde9f47bdbb424d2dbdda57bb..f95125fb1c7228f9eade37f423b624c3289c0e34 100644 --- a/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -8,7 +8,7 @@ The **RemoteAbilityInfo** module provides information about a remote ability. ## RemoteAbilityInfo(deprecated) -> This API is deprecated since API version 9. You are advised to use [RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) instead. +> This API is deprecated since API version 9. You are advised to use [bundleManager-RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md) instead. **System capability**: SystemCapability.BundleManager.DistributedBundleFramework @@ -16,6 +16,6 @@ The **RemoteAbilityInfo** module provides information about a remote ability. | Name | Type | Readable| Writable| Description | | ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | -| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name of the ability. | -| label | string | Yes | No | Label of the ability. | +| elementName | [ElementName](js-apis-bundle-ElementName.md) | Yes | No | Element name information of the ability. | +| label | string | Yes | No | Ability name. | | icon | string | Yes | No | Icon of the ability.| diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md index 6948fac50faf7146b4bc0a8aabfb1eef2d1c719f..662f0e37640287de5e10273a45d8db327a4551da 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -1,6 +1,6 @@ # ElementName -The **ElementName** module provides information about an element name. The information can be obtained through [Context.getElementName](js-apis-Context.md). +The **ElementName** module provides element name information, which can be obtained through [Context.getElementName](js-apis-inner-app-context.md). > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md index 0f1d6b7e992484875d65479a3734b00484141d21..2c06d138b5bfda6383fabc14e28d3fb008af0bf0 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -1,10 +1,12 @@ # ShortcutInfo -The **ShortcutInfo** module provides shortcut information defined in the configuration file. For details about the configuration in the FA model, see [config.json](../../quick-start/package-structure.md). For details about the configuration in the stage model, see [Internal Structure of the shortcuts Attribute](../../quick-start/stage-structure.md#internal-structure-of-the-shortcuts-attribute). +The **ShortcutInfo** module defines shortcut information configured in the configuration file. The information can be obtained through [getShortcutInfo](js-apis-launcherBundleManager.md#launcherbundlemanagergetshortcutinfo9). > **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. +> +> For the FA model, the shortcut information is configured in the [config.json](../../quick-start/module-structure.md) file. For details about the shortcut information in the stage model, see [shortcuts](../../quick-start/module-configuration-file.md#shortcuts). ## ShortcutWant @@ -16,7 +18,7 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | ------------------------- | ------ | ---- | ---- | -------------------- | | targetBundle | string | Yes | No | Target bundle name of the shortcut.| | targetModule | string | Yes | No | Target module name of the shortcut. | -| targetAbility | string | Yes | No | Target ability name of the shortcut.| +| targetAbility | string | Yes | No | Target ability name of the shortcut.| ## ShortcutInfo @@ -35,3 +37,5 @@ The **ShortcutInfo** module provides shortcut information defined in the configu | label | string | Yes | No | Label of the shortcut. | | labelId | number | Yes | No | Label ID of the shortcut. | | wants | Array\<[ShortcutWant](#shortcutwant)> | Yes | No | Want information required for the shortcut. | + + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-bundleManager.md b/en/application-dev/reference/apis/js-apis-bundleManager.md index 9d616bbe15fd929b2808d117891bf441e3ecff35..3dab120c4667c563047b5cc48da6ed378e4a29aa 100644 --- a/en/application-dev/reference/apis/js-apis-bundleManager.md +++ b/en/application-dev/reference/apis/js-apis-bundleManager.md @@ -1,4 +1,4 @@ -# bundleManager +# @ohos.bundle.bundleManager The **bundleManager** module provides APIs for querying information about bundles, applications, abilities, Extension abilities, and more. @@ -9,11 +9,12 @@ The **bundleManager** module provides APIs for querying information about bundle ## Modules to Import ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; ``` + ## Required Permissions -| Required Permissions | Permission Level | Description | +| Permission | Permission Level | Description | | ------------------------------------------ | ------------ | ------------------| | ohos.permission.GET_BUNDLE_INFO | normal | Permission to query information about a specified bundle. | | ohos.permission.GET_BUNDLE_INFO_PRIVILEGED| system_basic | Permission to query information about all bundles.| @@ -97,17 +98,17 @@ Enumerates the types of Extension abilities. | Name| Value| Description| |:----------------:|:---:|-----| -| FORM | 0 | [FormExtensionAbility](../../ability/stage-formextension.md): provides APIs for widget development.| +| FORM | 0 | [FormExtensionAbility](../../application-models/widget-development-stage.md): provides APIs for widget development.| | WORK_SCHEDULER | 1 | [WorkSchedulerExtensionAbility](../../task-management/work-scheduler-dev-guide.md): enables applications to execute non-real-time tasks when the system is idle.| | INPUT_METHOD | 2 | [InputMethodExtensionAbility](js-apis-inputmethod-extension-ability.md): provides APIs for developing input method applications.| -| SERVICE | 3 | [ServiceExtensionAbility](../../ability/stage-serviceextension.md): enables applications to run in the background and provide services.| -| ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-AccessibilityExtensionAbility.md): provides accessibility for access to and operations on the UI.| +| SERVICE | 3 | [ServiceExtensionAbility](../../application-models/serviceextensionability.md): enables applications to run in the background and provide services.| +| ACCESSIBILITY | 4 | [AccessibilityExtensionAbility](js-apis-application-accessibilityExtensionAbility.md): provides accessibility for access to and operations on the UI.| | DATA_SHARE | 5 | [DataShareExtensionAbility](../../database/database-datashare-guidelines.md): enables applications to read and write data.| | FILE_SHARE | 6 | FileShareExtensionAbility: enables file sharing between applications. This ability is reserved.| | STATIC_SUBSCRIBER| 7 | [StaticSubscriberExtensionAbility](js-apis-application-staticSubscriberExtensionAbility.md): provides APIs for processing static events, such as the startup event.| | WALLPAPER | 8 | WallpaperExtensionAbility: provides APIs to implement the home screen wallpaper. This ability is reserved.| | BACKUP | 9 | BackupExtensionAbility: provides APIs for backing up and restoring application data and public data. This ability is reserved.| -| WINDOW | 10 | [WindowExtensionAbility](js-apis-application-WindowExtensionAbility.md): allows system applications to display UIs of other applications.| +| WINDOW | 10 | [WindowExtensionAbility](js-apis-application-windowExtensionAbility.md): allows system applications to display UIs of other applications.| | ENTERPRISE_ADMIN | 11 | [EnterpriseAdminExtensionAbility](js-apis-EnterpriseAdminExtensionAbility.md): provides APIs for processing enterprise management events, such as application installation events on devices and events indicating too many incorrect screen-lock password attempts.| | THUMBNAIL | 13 | ThumbnailExtensionAbility: provides thumbnails for files. This ability is reserved.| | PREVIEW | 14 | PreviewExtensionAbility: provides APIs for file preview so that other applications can be embedded and displayed in the current application. This ability is reserved.| @@ -185,7 +186,7 @@ Enumerates the display orientations of the ability. This attribute applies only | AUTO_ROTATION_PORTRAIT_RESTRICTED |11|Switched-determined auto rotation in the vertical direction.| | LOCKED |12|Locked.| -## Methods +## APIs ### bundleManager.getBundleInfoForSelf @@ -210,16 +211,17 @@ Obtains the bundle information of this bundle based on the given bundle flags. T **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfoForSelf(bundleFlags).then((data) => { - console.info('getBundleInfoForSelf successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfoForSelf failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfoForSelf failed:' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } ``` @@ -241,19 +243,20 @@ Obtains the bundle information of this bundle based on the given bundle flags. T **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfoForSelf(bundleFlags, (err, data) => { if (err) { - console.error('getBundleInfoForSelf failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } else { - console.info('getBundleInfoForSelf successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoForSelf successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfoForSelf failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoForSelf failed: %{public}s', err.message); } ``` @@ -263,6 +266,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, userId: number, callback: Obtains the bundle information based on the given bundle name, bundle flags, and user ID. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -273,7 +278,7 @@ Obtains the bundle information based on the given bundle name, bundle flags, and | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| | userId | number | Yes | User ID. | | callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the bundle information obtained. Otherwise, **err** is an error object.| @@ -292,7 +297,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the ability information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_ABILITY; let userId = 100; @@ -300,19 +306,20 @@ let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` ```ts // Obtain the bundle information with the metadata in the application information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_METADATA; let userId = 100; @@ -320,13 +327,13 @@ let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` @@ -336,6 +343,8 @@ getBundleInfo(bundleName: string, bundleFlags: number, callback: AsyncCallback\< Obtains the bundle information based on the given bundle name and bundle flags. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -346,7 +355,7 @@ Obtains the bundle information based on the given bundle name and bundle flags. | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| | callback | AsyncCallback\<[BundleInfo](js-apis-bundleManager-bundleInfo.md)> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the bundle information obtained. Otherwise, **err** is an error object.| @@ -364,20 +373,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the Extension ability information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_HAP_MODULE | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_EXTENSION_ABILITY; try { bundleManager.getBundleInfo(bundleName, bundleFlags, (err, data) => { if (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } else { - console.info('getBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfo failed: %{public}s', err.message); } ``` @@ -387,6 +397,8 @@ getBundleInfo(bundleName: string, bundleFlags: [number](#bundleflag), userId?: n Obtains the bundle information based on the given bundle name, bundle flags, and user ID. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -410,6 +422,7 @@ Obtains the bundle information based on the given bundle name, bundle flags, and **Error codes** For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). + | ID| Error Message | | -------- | --------------------------------------| | 17700001 | The specified bundleName is not found. | @@ -420,35 +433,37 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts // Obtain the bundle information with the application and signature information. -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_APPLICATION | bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_SIGNATURE_INFO; let userId = 100; try { bundleManager.getBundleInfo(bundleName, bundleFlags, userId).then((data) => { - console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleInfo(bundleName, bundleFlags).then((data) => { - console.info('getBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleInfo failed. Cause: %{public}s', err.message); } ``` @@ -459,6 +474,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), use Obtains the application information based on the given bundle name, application flags, and user ID. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -487,7 +504,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; @@ -495,13 +513,13 @@ let userId = 100; try { bundleManager.getApplicationInfo(bundleName, appFlags, userId, (err, data) => { if (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } else { - console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } ``` @@ -511,6 +529,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), cal Obtains the application information based on the given bundle name and application flags. This API uses an asynchronous callback to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -538,20 +558,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; try { bundleManager.getApplicationInfo(bundleName, appFlags, (err, data) => { if (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } else { - console.info('getApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed: %{public}s', err.message); } ``` @@ -561,6 +582,8 @@ getApplicationInfo(bundleName: string, appFlags: [number](#applicationflag), use Obtains the application information based on the given bundle name, application flags, and user ID. This API uses a promise to return the result. +No permission is required for obtaining the caller's own information. + **System API**: This is a system API. **Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO @@ -594,19 +617,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_WITH_PERMISSION; let userId = 100; try { bundleManager.getApplicationInfo(bundleName, appFlags, userId).then((data) => { - console.info('getApplicationInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getApplicationInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getApplicationInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getApplicationInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getApplicationInfo failed. Cause: %{public}s', err.message); } ``` @@ -614,7 +638,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), userId: number, callback: AsyncCallback>): void; -Obtains an array of bundle information based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. +Obtains the information about all bundles based on the given bundle flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -641,20 +665,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; let userId = 100; try { bundleManager.getAllBundleInfo(bundleFlags, userId, (err, data) => { if (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } else { - console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } ``` @@ -662,7 +687,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), callback: AsyncCallback>): void; -Obtains an array of bundle information based on the given bundle flags. This API uses an asynchronous callback to return the result. +Obtains the information about all bundles based on the given bundle flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -688,19 +713,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getAllBundleInfo(bundleFlags, (err, data) => { if (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } else { - console.info('getAllBundleInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllBundleInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed: %{public}s', err.message); } ``` @@ -708,7 +734,7 @@ try { getAllBundleInfo(bundleFlags: [number](#bundleflag), userId?: number): Promise>; -Obtains an array of bundle information based on the given bundle flags and user ID. This API uses a promise to return the result. +Obtains the information about all bundles based on the given bundle flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -740,17 +766,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getAllBundleInfo(bundleFlags).then((data) => { - console.info('getAllBundleInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAllBundleInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAllBundleInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAllBundleInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllBundleInfo failed. Cause: %{public}s', err.message); } ``` @@ -758,7 +785,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), userId: number, callback: AsyncCallback>): void; -Obtains an array of application information based on the given application flags and user ID. This API uses an asynchronous callback to return the result. +Obtains the information about all applications based on the given application flags and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -785,20 +812,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; try { bundleManager.getAllApplicationInfo(appFlags, userId, (err, data) => { if (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } else { - console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } ``` @@ -806,7 +834,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), callback: AsyncCallback>): void; -Obtains an array of application information based on the given application flags. This API uses an asynchronous callback to return the result. +Obtains the information about all applications based on the given application flags. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -832,19 +860,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { bundleManager.getAllApplicationInfo(appFlags, (err, data) => { if (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } else { - console.info('getAllApplicationInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAllApplicationInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed: %{public}s', err.message); } ``` @@ -852,7 +881,7 @@ try { getAllApplicationInfo(appFlags: [number](#applicationflag), userId?: number): Promise>; -Obtains an array of application information based on the given application flags and user ID. This API uses a promise to return the result. +Obtains the information about all applications based on the given application flags and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -884,17 +913,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let appFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { bundleManager.getAllApplicationInfo(appFlags).then((data) => { - console.info('getAllApplicationInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAllApplicationInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAllApplicationInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAllApplicationInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAllApplicationInfo failed. Cause: %{public}s', err.message); } ``` @@ -915,7 +945,7 @@ Obtains an array of ability information based on the given want, ability flags, | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ------------------------------------------------------- | -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain. | | userId | number | Yes | User ID. | | callback | AsyncCallback> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of ability information obtained. Otherwise, **err** is an error object.| @@ -935,24 +965,25 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId, (err, data) => { if (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } ``` @@ -972,7 +1003,7 @@ Obtains an array of ability information based on the given want and ability flag | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | -------------------------------------------------------| -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain. | | callback | AsyncCallback> | Yes| Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of ability information obtained. Otherwise, **err** is an error object.| @@ -991,23 +1022,24 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, (err, data) => { if (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed: %{public}s', err.message); } ``` @@ -1027,7 +1059,7 @@ Obtains the ability information based on the given want, ability flags, and user | Name | Type | Mandatory| Description | | ------------ | ------ | ---- | ------------------------------------------------------- | -| want | Want | Yes | Want containing the bundle name to query. | +| want | Want | Yes | Want containing the bundle name to query. | | abilityFlags | [number](#abilityflag) | Yes | Type of the ability information to obtain.| | userId | number | No | User ID. | @@ -1052,41 +1084,43 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((data) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryAbilityInfo(want, abilityFlags).then((data) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }) -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1106,10 +1140,10 @@ Obtains the Extension ability information based on the given want, Extension abi | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want containing the bundle name to query. | -| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | -| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | -| userId | number | Yes | User ID. | +| want | Want | Yes | Want containing the bundle name to query. | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | +| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | +| userId | number | Yes | User ID. | | callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of Extension ability information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -1126,25 +1160,26 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId, (err, data) => { if (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } ``` @@ -1164,9 +1199,9 @@ Obtains the Extension ability information based on the given want, Extension abi | Name | Type | Mandatory| Description | | --------------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| want | Want | Yes | Want containing the bundle name to query. | -| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | -| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | +| want | Want | Yes | Want containing the bundle name to query. | +| extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | +| extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain. | | callback | AsyncCallback> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the array of Extension ability information obtained. Otherwise, **err** is an error object.| **Error codes** @@ -1183,24 +1218,25 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, (err, data) => { if (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } else { - console.info('queryExtensionAbilityInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('queryExtensionAbilityInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed: %{public}s', err.message); } ``` @@ -1218,8 +1254,8 @@ Obtains the Extension ability information based on the given want, Extension abi **Parameters** -| Name | Type | Mandatory| Description | -| --------------------- | --------------------------------------------- | ---- | ------------------------------------------------------- | +| Name | Type | Mandatory| Description | +| --------------------- | --------------------------------------------- | ---- | --------------------------------------------------------- | | want | Want | Yes | Want containing the bundle name to query. | | extensionAbilityType | [ExtensionAbilityType](#extensionabilitytype) | Yes | Type of the Extension ability. | | extensionAbilityFlags | [number](#extensionabilityflag) | Yes | Type of the Extension ability information to obtain.| @@ -1245,44 +1281,46 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags, userId).then((data) => { - console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let extensionAbilityType = bundleManager.ExtensionAbilityType.FORM; let extensionFlags = bundleManager.ExtensionAbilityFlag.GET_EXTENSION_ABILITY_INFO_DEFAULT; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; try { bundleManager.queryExtensionAbilityInfo(want, extensionAbilityType, extensionFlags).then((data) => { - console.info('queryExtensionAbilityInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'queryExtensionAbilityInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); }) -} catch (error) { - console.error('queryExtensionAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryExtensionAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1316,18 +1354,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let uid = 20010005; try { bundleManager.getBundleNameByUid(uid, (err, data) => { if (err) { - console.error('getBundleNameByUid failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed: %{public}s', err.message); } else { - console.info('getBundleNameByUid successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleNameByUid successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleNameByUid failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed: %{public}s', err.message); } ``` @@ -1366,16 +1405,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let uid = 20010005; try { bundleManager.getBundleNameByUid(uid).then((data) => { - console.info('getBundleNameByUid successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleNameByUid failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleNameByUid successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleNameByUid failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleNameByUid failed. Cause: %{public}s', err.message); } ``` @@ -1410,20 +1450,21 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let hapFilePath = "/data/xxx/test.hap"; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags, (err, data) => { if (err) { - console.error('getBundleArchiveInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } else { - console.info('getBundleArchiveInfo successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleArchiveInfo successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getBundleArchiveInfo failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } ``` @@ -1463,18 +1504,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let hapFilePath = "/data/xxx/test.hap"; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_DEFAULT; try { bundleManager.getBundleArchiveInfo(hapFilePath, bundleFlags).then((data) => { - console.info('getBundleArchiveInfo successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getBundleArchiveInfo failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getBundleArchiveInfo successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getBundleArchiveInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getBundleArchiveInfo failed. Cause: %{public}s', err.message); } ``` @@ -1482,7 +1524,7 @@ try { cleanBundleCacheFiles(bundleName: string, callback: AsyncCallback\): void; -Clears cache files of a bundle. This API uses an asynchronous callback to return the result. +Clears the cache files based on the given bundle name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -1509,19 +1551,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { bundleManager.cleanBundleCacheFiles(bundleName, err => { if (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } else { - console.info('cleanBundleCacheFiles successfully.'); + hilog.info(0x0000, 'testTag', 'cleanBundleCacheFiles successfully.'); } }); } catch (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } ``` @@ -1529,7 +1572,7 @@ try { cleanBundleCacheFiles(bundleName: string): Promise\; -Clears cache files of a bundle. This API uses a promise to return the result. +Clears the cache files based on the given bundle name. This API uses a promise to return the result. **System API**: This is a system API. @@ -1547,7 +1590,7 @@ Clears cache files of a bundle. This API uses a promise to return the result. | Type | Description | | -------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, no value is returned. Otherwise, an error message is returned.| +| Promise\ | Promise that returns no value. If clearing the cache files fails, an error object is thrown.| **Error codes** @@ -1556,22 +1599,23 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ---------------------------------------------------------- | | 17700001 | The specified bundleName is not found. | -| 17700030 | The specified bundle does not support cleaning cache files. | +| 17700030 | The specified bundle does not support clearing of cache files. | **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { - bundleManager.cleanBundleCacheFiles(bundleName).then(()=> { - console.info('cleanBundleCacheFiles successfully.'); - }).catch(err=> { - console.error('cleanBundleCacheFiles failed:' + err.message); + bundleManager.cleanBundleCacheFiles(bundleName).then(() => { + hilog.info(0x0000, 'testTag', 'cleanBundleCacheFiles successfully.'); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); }); } catch (err) { - console.error('cleanBundleCacheFiles failed:' + err.message); + hilog.error(0x0000, 'testTag', 'cleanBundleCacheFiles failed: %{public}s', err.message); } ``` @@ -1606,19 +1650,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { bundleManager.setApplicationEnabled(bundleName, false, err => { if (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } else { - console.info('setApplicationEnabled successfully.'); + hilog.info(0x0000, 'testTag', 'setApplicationEnabled successfully.'); } }); } catch (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1658,17 +1703,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = "com.ohos.myapplication"; try { - bundleManager.setApplicationEnabled(bundleName, false).then(()=> { - console.info('setApplicationEnabled successfully.'); - }).catch(err=> { - console.error('setApplicationEnabled failed:' + err.message); + bundleManager.setApplicationEnabled(bundleName, false).then(() => { + hilog.info(0x0000, "testTag", "setApplicationEnabled successfully."); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); }); } catch (err) { - console.error('setApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1704,32 +1750,33 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.setAbilityEnabled(info, false, err => { if (err) { - console.error('setAbilityEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'setAbilityEnabled failed: %{public}s', err.message); } else { - console.info('setAbilityEnabled successfully.'); + hilog.info(0x0001, "testTag", "setAbilityEnabled successfully."); } }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1770,30 +1817,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; - bundleManager.setAbilityEnabled(info, false).then(()=> { - console.info('setAbilityEnabled successfully.'); - }).catch(err=> { - console.error('setAbilityEnabled failed:' + err.message); + bundleManager.setAbilityEnabled(info, false).then(() => { + hilog.info(0x0000, "testTag", "setAbilityEnabled successfully."); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'setAbilityEnabled failed: %{public}s', err.message); }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1825,19 +1873,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.isApplicationEnabled(bundleName, (err, data) => { if (err) { - console.error('isApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed: %{public}s', err.message); } else { - console.info('isApplicationEnabled successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isApplicationEnabled successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('isApplicationEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed: %{public}s', err.message); } ``` @@ -1874,17 +1923,18 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.isApplicationEnabled(bundleName).then((data) => { - console.info('isApplicationEnabled successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('isApplicationEnabled failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'isApplicationEnabled successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('isApplicationEnabled failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'isApplicationEnabled failed. Cause: %{public}s', err.message); } ``` @@ -1917,32 +1967,33 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.isAbilityEnabled(info, (err, data) => { if (err) { - console.error('isAbilityEnabled failed:' + err.message); + hilog.error(0x0000, 'testTag', 'isAbilityEnabled failed: %{public}s', err.message); } else { - console.info('isAbilityEnabled successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isAbilityEnabled successfully: %{public}s', JSON.stringify(data)); } }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -1980,30 +2031,31 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let abilityFlags = bundleManager.AbilityFlag.GET_ABILITY_INFO_DEFAULT; let userId = 100; let want = { bundleName : "com.example.myapplication", - abilityName : "com.example.myapplication.MainAbility" + abilityName : "EntryAbility" }; -var info; +let info; try { bundleManager.queryAbilityInfo(want, abilityFlags, userId).then((abilitiesInfo) => { - console.info('queryAbilityInfo successfully. Data: ' + JSON.stringify(abilitiesInfo)); + hilog.info(0x0000, 'testTag', 'queryAbilityInfo successfully. Data: %{public}s', JSON.stringify(abilitiesInfo)); info = abilitiesInfo[0]; bundleManager.isAbilityEnabled(info).then((data) => { - console.info('isAbilityEnabled successfully. Data: ' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'isAbilityEnabled successfully. Data: %{public}s', JSON.stringify(data)); }).catch(err => { - console.error('isAbilityEnabled failed. Cause: ' + err.message); + hilog.error(0x0000, 'testTag', 'isAbilityEnabled failed. Cause: %{public}s', err.message); }); - }).catch(error => { - console.error('queryAbilityInfo failed. Cause: ' + error.message); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('queryAbilityInfo failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'queryAbilityInfo failed. Cause: %{public}s', err.message); } ``` @@ -2011,7 +2063,7 @@ try { getLaunchWantForBundle(bundleName: string, userId: number, callback: AsyncCallback\): void; -Obtains the want used to launch the bundle based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. +Obtains the Want used to launch the bundle based on the given bundle name and user ID. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2034,26 +2086,27 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | --------------------------------------| | 17700001 | The specified bundleName is not found. | -| 17700004 | The specified user ID is not found | +| 17700004 | The specified user ID is not found. | | 17700026 | The specified bundle is disabled. | **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let userId = 100; try { bundleManager.getLaunchWantForBundle(bundleName, userId, (err, data) => { if (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } else { - console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } ``` @@ -2061,7 +2114,7 @@ try { getLaunchWantForBundle(bundleName: string, callback: AsyncCallback\): void; -Obtains the want used to launch the bundle based on the given bundle name. This API uses an asynchronous callback to return the result. +Obtains the Want used to launch the bundle based on the given bundle name. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2083,25 +2136,26 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | --------------------------------------| | 17700001 | The specified bundleName is not found. | -| 17700004 | The specified user ID is not found | +| 17700004 | The specified user ID is not found. | | 17700026 | The specified bundle is disabled. | **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; try { bundleManager.getLaunchWantForBundle(bundleName, (err, data) => { if (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } else { - console.info('getLaunchWantForBundle successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getLaunchWantForBundle failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed: %{public}s', err.message); } ``` @@ -2109,7 +2163,7 @@ try { getLaunchWantForBundle(bundleName: string, userId?: number): Promise\; -Obtains the want used to launch the bundle based on the given bundle name and user ID. This API uses a promise to return the result. +Obtains the Want used to launch the bundle based on the given bundle name and user ID. This API uses a promise to return the result. **System API**: This is a system API. @@ -2143,18 +2197,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let userId = 100; try { bundleManager.getLaunchWantForBundle(bundleName, userId).then((data) => { - console.info('getLaunchWantForBundle successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getLaunchWantForBundle failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getLaunchWantForBundle successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getLaunchWantForBundle failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getLaunchWantForBundle failed. Cause: %{public}s', err.message); } ``` @@ -2181,8 +2236,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified abilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified abilityName does not exist. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2190,21 +2245,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByAbility(moduleName, abilityName, metadataName, (err, data) => { if (err) { - console.error('getProfileByAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } else { - console.info('getProfileByAbility successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getProfileByAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` @@ -2236,8 +2292,8 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified abilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified abilityName does not exist. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | | 17700029 | The specified ability is disabled. | @@ -2245,34 +2301,36 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getProfileByAbility(moduleName, abilityName).then((data) => { - console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByAbility(moduleName, abilityName, metadataName).then((data) => { - console.info('getProfileByAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByAbility failed. Cause: %{public}s', err.message); } ``` @@ -2299,15 +2357,16 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified extensionAbilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; let extensionAbilityName = 'com.example.myapplication.extension'; let metadataName = 'com.example.myapplication.metadata'; @@ -2315,13 +2374,13 @@ let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName, (err, data) => { if (err) { - console.error('getProfileByExtensionAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed: %{public}s', err.message); } else { - console.info('getProfileByExtensionAbility successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getProfileByExtensionAbility failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed: %{public}s', err.message); } ``` @@ -2353,37 +2412,38 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | ------------------------------------------------------------ | -| 17700002 | The specified moduleName is not existed. | -| 17700003 | The specified extensionAbilityName is not existed. | +| 17700002 | The specified moduleName does not exist. | +| 17700003 | The specified extensionAbilityName not existed. | | 17700024 | Failed to get the profile because there is no profile in the HAP. | | 17700026 | The specified bundle is disabled. | **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let moduleName = 'entry'; let extensionAbilityName = 'com.example.myapplication.extension'; let metadataName = 'com.example.myapplication.metadata'; try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName).then((data) => { - console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); } try { bundleManager.getProfileByExtensionAbility(moduleName, extensionAbilityName, metadataName).then((data) => { - console.info('getProfileByExtensionAbility successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getProfileByExtensionAbility successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getProfileByExtensionAbility failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getProfileByExtensionAbility failed. Cause: %{public}s', err.message); } ``` @@ -2391,7 +2451,7 @@ try { getPermissionDef(permissionName: string, callback: AsyncCallback\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>): void; -Obtains the details of a permission. This API uses an asynchronous callback to return the result. +Obtains the details of a permission in the form of a **PermissionDef** struct. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2417,18 +2477,19 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let permission = "ohos.permission.GET_BUNDLE_INFO"; try { bundleManager.getPermissionDef(permission, (err, data) => { if (err) { - console.error('getPermissionDef failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getPermissionDef failed: %{public}s', err.message); } else { - console.info('getPermissionDef successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getPermissionDef successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getPermissionDef failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getPermissionDef failed: %{public}s', err.message); } ``` @@ -2436,7 +2497,7 @@ try { getPermissionDef(permissionName: string): Promise\<[PermissionDef](js-apis-bundleManager-permissionDef.md)>; -Obtains the details of a permission. This API uses a promise to return the result. +Obtains the details of a permission in the form of a **PermissionDef** struct. This API uses a promise to return the result. **System API**: This is a system API. @@ -2467,16 +2528,17 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let permissionName = "ohos.permission.GET_BUNDLE_INFO"; try { bundleManager.getPermissionDef(permissionName).then((data) => { - console.info('getPermissionDef successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getPermissionDef failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getPermissionDef successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getPermissionDef failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getPermissionDef failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getPermissionDef failed. Cause: %{public}s', err.message); } ``` @@ -2516,21 +2578,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityLabel(bundleName, moduleName, abilityName, (err, data) => { if (err) { - console.error('getAbilityLabel failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed: %{public}s', err.message); } else { - console.info('getAbilityLabel successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAbilityLabel successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAbilityLabel failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed: %{public}s', err.message); } ``` @@ -2575,19 +2638,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityLabel(bundleName, moduleName, abilityName).then((data) => { - console.info('getAbilityLabel successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAbilityLabel failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAbilityLabel successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAbilityLabel failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAbilityLabel failed. Cause: %{public}s', err.message); } ``` @@ -2627,21 +2691,22 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityIcon(bundleName, moduleName, abilityName, (err, data) => { if (err) { - console.error('getAbilityIcon failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); } else { - console.info('getAbilityIcon successfully:' + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully: %{public}s', JSON.stringify(data)); } }); } catch (err) { - console.error('getAbilityIcon failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed: %{public}s', err.message); } ``` @@ -2686,19 +2751,20 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let moduleName = 'entry'; -let abilityName = 'MainAbility'; +let abilityName = 'EntryAbility'; try { bundleManager.getAbilityIcon(bundleName, moduleName, abilityName).then((data) => { - console.info('getAbilityIcon successfully. Data: ' + JSON.stringify(data)); - }).catch(error => { - console.error('getAbilityIcon failed. Cause: ' + error.message); + hilog.info(0x0000, 'testTag', 'getAbilityIcon successfully. Data: %{public}s', JSON.stringify(data)); + }).catch(err => { + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); }); -} catch (error) { - console.error('getAbilityIcon failed. Cause: ' + error.message); +} catch (err) { + hilog.error(0x0000, 'testTag', 'getAbilityIcon failed. Cause: %{public}s', err.message); } ``` @@ -2720,7 +2786,7 @@ Synchronously obtains the application information based on the given bundle name | ----------- | ------ | ---- | ----------------------------------------------------------| | bundleName | string | Yes | Bundle name. | | applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain. | -| userId | number | Yes | User ID. | +| userId | number | No | User ID. | **Return value** @@ -2735,71 +2801,37 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc | ID| Error Message | | -------- | -------------------------------------- | | 17700001 | The specified bundleName is not found. | -| 17700004 | The specified userId is not found. | +| 17700004 | The specified user ID is not found. | | 17700026 | The specified bundle is disabled. | **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; let userId = 100; try { let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags, userId); - console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getApplicationInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfoSync failed: %{public}s', err.message); } ``` -### bundleManager.getApplicationInfoSync - -getApplicationInfoSync(bundleName: string, applicationFlags: number) : [ApplicationInfo](js-apis-bundleManager-applicationInfo.md); - -Synchronously obtains the application information based on the given bundle name and application flags. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO - -**System capability**: SystemCapability.BundleManager.BundleFramework.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------------------------------------------| -| bundleName | string | Yes | Bundle name. | -| applicationFlags | [number](#applicationflag) | Yes | Type of the application information to obtain. | - -**Return value** - -| Type | Description | -| --------------- | ------------------------- | -| [ApplicationInfo](js-apis-bundleManager-applicationInfo.md) | Application information obtained.| - -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - -| ID| Error Message | -| -------- | -------------------------------------- | -| 17700001 | The specified bundleName is not found. | -| 17700026 | The specified bundle is disabled. | - -**Example** - ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let applicationFlags = bundleManager.ApplicationFlag.GET_APPLICATION_INFO_DEFAULT; try { let data = bundleManager.getApplicationInfoSync(bundleName, applicationFlags); - console.info("getApplicationInfoSync successfully:" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getApplicationInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getApplicationInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getApplicationInfoSync failed: %{public}s', err.message); } ``` @@ -2821,7 +2853,7 @@ Synchronously obtains the bundle information based on the given bundle name, bun | ----------- | ------ | ---- | -------------------------------------------------------- | | bundleName | string | Yes | Bundle name. | | bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| -| userId | number | Yes | User ID. | +| userId | number | No | User ID. | **Return value** @@ -2842,64 +2874,29 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; let userId = 100; try { let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags, userId); - console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getBundleInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` -### bundleManager.getBundleInfoSync - -getBundleInfoSync(bundleName: string, bundleFlags: [number](#bundleflag)): [BundleInfo](js-apis-bundleManager-bundleInfo.md); - -Synchronously obtains the bundle information based on the given bundle name and bundle flags. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO - -**System capability**: SystemCapability.BundleManager.BundleFramework.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------------------------------------- | -| bundleName | string | Yes | Bundle name. | -| bundleFlags | [number](#bundleflag) | Yes | Type of the bundle information to obtain.| - -**Return value** - -| Type | Description | -| ---------- | -------------------- | -| [BundleInfo](js-apis-bundleManager-bundleInfo.md) | Bundle information obtained.| - -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - -| ID| Error Message | -| -------- | ------------------------------------- | -| 17700001 | The specified bundleName is not found. | -| 17700004 | The specified user ID is not found. | -| 17700026 | The specified bundle is disabled. | - -**Example** - ```ts -import bundleManager from '@ohos.bundle.bundleManager' +import bundleManager from '@ohos.bundle.bundleManager'; +import hilog from '@ohos.hilog'; let bundleName = 'com.example.myapplication'; let bundleFlags = bundleManager.BundleFlag.GET_BUNDLE_INFO_WITH_REQUESTED_PERMISSION; try { let data = bundleManager.getBundleInfoSync(bundleName, bundleFlags); - console.info("getBundleInfoSync successfully :" + JSON.stringify(data)); + hilog.info(0x0000, 'testTag', 'getBundleInfoSync successfully: %{public}s', JSON.stringify(data)); } catch (err) { - console.error('getBundleInfoSync failed:' + err.message); + hilog.error(0x0000, 'testTag', 'getBundleInfoSync failed: %{public}s', err.message); } ``` diff --git a/en/application-dev/reference/apis/js-apis-bundleMonitor.md b/en/application-dev/reference/apis/js-apis-bundleMonitor.md index ceef9d85218006916a52300887103c838d5bcd56..cf2d7aab46c5d8ea80d49fe66b61ae68e56885a0 100644 --- a/en/application-dev/reference/apis/js-apis-bundleMonitor.md +++ b/en/application-dev/reference/apis/js-apis-bundleMonitor.md @@ -1,4 +1,4 @@ -# Bundle.bundleMonitor +# @ohos.bundle.bundleMonitor The **Bundle.bundleMonitor** module provides APIs for listens for bundle installation, uninstall, and updates. @@ -18,7 +18,7 @@ import bundleMonitor from '@ohos.bundle.bundleMonitor'; | ------------------------------------ | ----------- | ------------------------------ | | ohos.permission.LISTEN_BUNDLE_CHANGE | system_core | Permission to listen for bundle installation, uninstall, and updates.| -For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). +For details, see [Permission Levels](../../security/accesstoken-overview.md). ## BundleChangeInfo @@ -50,10 +50,6 @@ Subscribes to bundle installation, uninstall, and update events. | BundleChangedEvent | string | Yes | Type of the event to subscribe to.| | Callback\ | callback | Yes | Callback used for the subscription.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts @@ -87,10 +83,6 @@ Unsubscribes from bundle installation, uninstall, and update events. | BundleChangedEvent | string | Yes | Type of the event to unsubscribe from. | | Callback\ | callback | Yes | Callback used for the unsubscription. If this parameter is left empty, all callbacks of the current event are unsubscribed from.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md index 544a4ba0d27e6c39794e063fc63282ba5455bf5e..89e14f7ad3e4fb3f525ccd9d5aab83b56e8c6521 100644 --- a/en/application-dev/reference/apis/js-apis-bytrace.md +++ b/en/application-dev/reference/apis/js-apis-bytrace.md @@ -1,4 +1,4 @@ -# Performance Tracing +# @ohos.bytrace (Performance Tracing) > **NOTE** > - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead. diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md index a04f49f6d46bd886af5b23c01e65ce7d0b689e85..0ccd49a5dc2a8b8e3577b7614f8219573de7cf7d 100644 --- a/en/application-dev/reference/apis/js-apis-call.md +++ b/en/application-dev/reference/apis/js-apis-call.md @@ -1,6 +1,6 @@ -# Call +# @ohos.telephony.call (Call) -The call module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. +The **call** module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers. To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-observer.md#observeroncallstatechange). @@ -55,7 +55,7 @@ Initiates a call based on the specified options. This API uses an asynchronous c | Name | Type | Mandatory | Description | | ----------- | ---------------------------- | ---- | --------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [DialOptions](#dialoptions) | Yes | Call option, which indicates whether the call is a voice call or video call. | +| options | [DialOptions](#dialoptions) | No | Call option, which indicates whether the call is a voice call or video call. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: success
- **false**: failure | **Example** @@ -313,7 +313,7 @@ Checks whether the called number is an emergency number based on the specified p | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------------- | ---- | -------------------------------------------- | | phoneNumber | string | Yes | Phone number. | -| options | [EmergencyNumberOptions](#emergencynumberoptions7) | Yes | Phone number options. | +| options | [EmergencyNumberOptions](#emergencynumberoptions7) | No | Phone number options. | | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.
- **true**: The called number is an emergency number.
- **false**: The called number is not an emergency number. | **Example** @@ -397,7 +397,7 @@ A formatted phone number is a standard numeric string, for example, 555 0100. | Name | Type | Mandatory | Description | | ----------- | -------------------------------------------- | ---- | ------------------------------------ | | phoneNumber | string | Yes | Phone number. | -| options | [NumberFormatOptions](#numberformatoptions7) | Yes | Number formatting options, for example, country code. | +| options | [NumberFormatOptions](#numberformatoptions7) | No | Number formatting options, for example, country code. | | callback | AsyncCallback<string> | Yes | Callback used to return the result. | **Example** @@ -566,33 +566,6 @@ promise.then(data => { }); ``` -## call.answer7+ - -answer\(callback: AsyncCallback\): void - -Answers a call. This API uses an asynchronous callback to return the result. - -This is a system API. - -**Required permission**: ohos.permission.ANSWER_CALL - -**System capability**: SystemCapability.Telephony.CallManager - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -call.answer((err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); -}); -``` - - ## call.answer7+ answer\(callId: number, callback: AsyncCallback\): void @@ -658,50 +631,54 @@ promise.then(data => { ## call.hangup7+ -hangup\(callback: AsyncCallback\): void +hangup\(callId: number, callback: AsyncCallback\): void Ends a call. This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | +| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -call.hangup((err, data) => { +call.hangup(1, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` -## call.hangup7+ +## call.answer9+ -hangup\(callId: number, callback: AsyncCallback\): void +answer\(callback: AsyncCallback\): void -Ends a call based on the specified call ID. This API uses an asynchronous callback to return the result. +Answers a call.This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ----------------------------------------------- | -| callId | number | Yes | Call ID. You can obtain the value by subscribing to **callDetailsChange** events.| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** ```js -call.hangup(1, (err, data) => { +call.answer((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -715,6 +692,8 @@ Ends a call based on the specified call ID. This API uses a promise to return th This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -740,14 +719,16 @@ promise.then(data => { }); ``` -## call.reject7+ +## call.hangup9+ -reject\(callback: AsyncCallback\): void +hangup\(callback: AsyncCallback\): void -Rejects a call. This API uses an asynchronous callback to return the result. +Ends a call. This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -759,36 +740,7 @@ This is a system API. **Example** ```js -call.reject((err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); -}); -``` - - -## call.reject7+ - -reject\(options: RejectMessageOptions, callback: AsyncCallback\): void - -Rejects a call based on the specified options. This API uses an asynchronous callback to return the result. - -This is a system API. - -**System capability**: SystemCapability.Telephony.CallManager - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------------- | ---- | -------------- | -| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | - -**Example** - -```js -let rejectMessageOptions={ - messageContent: "Unknown number blocked" -} -call.reject(rejectMessageOptions, (err, data) => { +call.hangup((err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -802,6 +754,8 @@ Rejects a call based on the specified call ID. This API uses an asynchronous cal This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -828,6 +782,8 @@ Rejects a call based on the specified call ID and options. This API uses an asyn This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -858,6 +814,8 @@ Rejects a call based on the specified call ID and options. This API uses a promi This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -887,6 +845,65 @@ promise.then(data => { }); ``` + +## call.reject9+ + +reject\(callback: AsyncCallback\): void + +Rejects a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example:** + +```js +call.reject((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + +## call.reject9+ + +reject\(options: RejectMessageOptions, callback: AsyncCallback\): void + +Rejects a call. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permission**: ohos.permission.ANSWER_CALL + +**System capability**: SystemCapability.Telephony.CallManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | -------------- | +| options | [RejectMessageOptions](#rejectmessageoptions7) | Yes | Options for the call rejection message.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example:** + +```js +let rejectMessageOptions={ + messageContent: "Unknown number blocked" +} +call.reject(rejectMessageOptions, (err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + + ## call.holdCall7+ holdCall\(callId: number, callback: AsyncCallback\): void @@ -895,6 +912,8 @@ Holds a call based on the specified call ID. This API uses an asynchronous callb This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -921,6 +940,8 @@ Holds a call based on the specified call ID. This API uses a promise to return t This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -954,6 +975,8 @@ Unholds a call based on the specified call ID. This API uses an asynchronous cal This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -980,6 +1003,8 @@ Unholds a call based on the specified call ID. This API uses a promise to return This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1013,6 +1038,8 @@ Switches a call. This API uses an asynchronous callback to return the result. This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1039,6 +1066,8 @@ Switches a call. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.ANSWER_CALL + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1308,14 +1337,16 @@ Obtains the call waiting status. This API uses an asynchronous callback to retur This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.

- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | +| callback | AsyncCallback<[CallWaitingStatus](#callwaitingstatus7)\> | Yes | Callback used to return the result.
- **0**: Call waiting is disabled.
- **1**: Call waiting is enabled.| **Example** @@ -1334,6 +1365,8 @@ Obtains the call waiting status. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1367,6 +1400,8 @@ Sets the call waiting switch. This API uses an asynchronous callback to return t This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1394,6 +1429,8 @@ Sets the call waiting switch. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1604,6 +1641,8 @@ Subscribes to **callDetailsChange** events. This API uses an asynchronous callba This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1629,6 +1668,8 @@ Subscribes to **callEventChange** events. This API uses an asynchronous callback This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1654,6 +1695,8 @@ Subscribes to **callDisconnectedCause** events. This API uses an asynchronous ca This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1661,7 +1704,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------ | ---- | -------------------------- | | type | string | Yes | Cause of the call disconnection.| -| callback | Callback<[DisconnectedDetails](#disconnecteddetails8)> | Yes | Callback used to return the result. | +| callback | Callback<[DisconnectedDetails](#disconnecteddetails9)> | Yes | Callback used to return the result. | **Example** @@ -1679,6 +1722,8 @@ Subscribes to **mmiCodeResult** events. This API uses an asynchronous callback t This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1704,6 +1749,8 @@ Unsubscribes from **callDetailsChange** events. This API uses an asynchronous ca This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1729,6 +1776,8 @@ Unsubscribes from **callEventChange** events. This API uses an asynchronous call This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1754,6 +1803,8 @@ Unsubscribes from **callDisconnectedCause** events. This API uses an asynchronou This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1761,7 +1812,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ---------------------------------------------------------- | ---- | -------------------- | | type | 'callDisconnectedCause' | Yes | Unsubscription from the call disconnection cause when a call ends.| -| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails8)> | No | Callback used to return the result. | +| callback | Callback**<**[DisconnectedDetails](#disconnecteddetails9)> | No | Callback used to return the result. | **Example** @@ -1779,6 +1830,8 @@ Unsubscribes from **mmiCodeResult** events. This API uses an asynchronous callba This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1915,6 +1968,8 @@ Obtains the call restriction status. This API uses an asynchronous callback to r This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1942,6 +1997,8 @@ Obtains the call restriction status. This API uses a promise to return the resul This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -1976,6 +2033,8 @@ Sets the call restriction status. This API uses an asynchronous callback to retu This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2008,6 +2067,8 @@ Sets the call restriction status. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2047,6 +2108,8 @@ Obtains call transfer information. This API uses an asynchronous callback to ret This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2074,6 +2137,8 @@ Obtains call transfer information. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2108,6 +2173,8 @@ Sets call transfer information. This API uses an asynchronous callback to return This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2140,6 +2207,8 @@ Sets call transfer information. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2331,7 +2400,7 @@ promise.then(data => { }); ``` -## call.setAudioDevice8+ +## call.setAudioDevice9+ setAudioDevice\(device: AudioDevice, callback: AsyncCallback\): void @@ -2357,7 +2426,7 @@ call.setAudioDevice(1, (err, data) => { ``` -## call.setAudioDevice8+ +## call.setAudioDevice9+ setAudioDevice\(device: AudioDevice, options: AudioDeviceOptions, callback: AsyncCallback\): void @@ -2558,6 +2627,8 @@ Enables the IMS switch. This API uses an asynchronous callback to return the res This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2583,6 +2654,8 @@ Enables the IMS switch. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2616,6 +2689,8 @@ Disables the IMS switch. This API uses an asynchronous callback to return the re This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2641,6 +2716,8 @@ Disables the IMS switch. This API uses a promise to return the result. This is a system API. +**Required permission**: ohos.permission.SET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CallManager **Parameters** @@ -2831,11 +2908,15 @@ This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Type | Mandatory| Description | -| ----------- | ---------------------------------------------------- | ---- | ---------------- | -| transferNum | string | Yes | Call transfer number. | -| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | -| settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.| +| Name | Type | Mandatory| Description | +| ------------------------ | ---------------------------------------------------- | ---- | ---------------- | +| transferNum | string | Yes | Call transfer number. | +| type | [CallTransferType](#calltransfertype8) | Yes | Call transfer type. | +| settingType | [CallTransferSettingType](#calltransfersettingtype8) | Yes | Call transfer setting type.| +| startHour9+ | number | No | Hour in the start time.| +| startMinute9+ | number | No | Minute in the start time.| +| endHour9+ | number | No | Hour in the end time.| +| endMinute9+ | number | No | Minute in the end time.| ## CallTransferType8+ @@ -3051,10 +3132,14 @@ This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name| Type | Mandatory| Description | -| ------ | ---------------------------------- | ---- | -------- | -| status | [TransferStatus](#transferstatus8) | Yes | Transfer status.| -| number | string | Yes | Number. | +| Name | Type | Mandatory| Description | +| ------------------------ | ---------------------------------- | ---- | ---------------- | +| status | [TransferStatus](#transferstatus8) | Yes | Call transfer status. | +| number | string | Yes | Call transfer number. | +| startHour9+ | number | Yes | Hour in the start time.| +| startMinute9+ | number | Yes | Minute in the start time.| +| endHour9+ | number | Yes | Hour in the end time.| +| endMinute9+ | number | Yes | Minute in the end time.| ## CallWaitingStatus7+ @@ -3095,7 +3180,20 @@ This is a system API. | TRANSFER_DISABLE | 0 | Call transfer disabled.| | TRANSFER_ENABLE | 1 | Call transfer enabled.| -## DisconnectedDetails8+ +## DisconnectedDetails9+ + +Defines the cause of a call disconnection. + +This is a system API. + +**System capability**: SystemCapability.Telephony.CallManager + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------ | ---- | --------------- | +| reason | [DisconnectedReason](#disconnectedreason8) | Yes | Cause of the call disconnection. | +| message | string | Yes | Message indicating the call disconnection.| + +## DisconnectedReason8+ Enumerates causes of call disconnection. @@ -3103,28 +3201,87 @@ This is a system API. **System capability**: SystemCapability.Telephony.CallManager -| Name | Value | Description | -| --------------------------- | ---- | ---------------------- | -| UNASSIGNED_NUMBER | 1 | Unallocated number. | -| NO_ROUTE_TO_DESTINATION | 3 | No route to the destination. | -| CHANNEL_UNACCEPTABLE | 6 | Unacceptable channel. | -| OPERATOR_DETERMINED_BARRING | 8 | Operator determined barring (ODB). | -| NORMAL_CALL_CLEARING | 16 | Normal call clearing. | -| USER_BUSY | 17 | User busy. | -| NO_USER_RESPONDING | 18 | No user response. | -| USER_ALERTING_NO_ANSWER | 19 | Alerting but no answer.| -| CALL_REJECTED | 21 | Call rejected. | -| NUMBER_CHANGED | 22 | Number changed. | -| DESTINATION_OUT_OF_ORDER | 27 | Destination fault. | -| INVALID_NUMBER_FORMAT | 28 | Invalid number format. | -| NETWORK_OUT_OF_ORDER | 38 | Network fault. | -| TEMPORARY_FAILURE | 41 | Temporary fault. | -| INVALID_PARAMETER | 1025 | Invalid parameter. | -| SIM_NOT_EXIT | 1026 | SIM card not exit. | -| SIM_PIN_NEED | 1027 | SIM card PIN required. | -| CALL_NOT_ALLOW | 1029 | Call not allowed. | -| SIM_INVALID | 1045 | Invalid SIM card. | -| UNKNOWN | 1279 | Unknown reason. | +| Name | Value | Description | +| ------------------------------------------------------------ | ---- | --------------------------------------- | +| UNASSIGNED_NUMBER | 1 | Unallocated (unassigned) number. | +| NO_ROUTE_TO_DESTINATION | 3 | No route to destination. | +| CHANNEL_UNACCEPTABLE | 6 | Channel unacceptable. | +| OPERATOR_DETERMINED_BARRING | 8 | Operator determined barring (ODB). | +| CALL_COMPLETED_ELSEWHERE9+ | 13 | Call completed elsewhere. | +| NORMAL_CALL_CLEARING | 16 | Normal call clearing. | +| USER_BUSY | 17 | User busy. | +| NO_USER_RESPONDING | 18 | No user responding. | +| USER_ALERTING_NO_ANSWER | 19 | User alerting, no answer. | +| CALL_REJECTED | 21 | Call rejected. | +| NUMBER_CHANGED | 22 | Number changed. | +| CALL_REJECTED_DUE_TO_FEATURE_AT_THE_DESTINATION9+ | 24 | Call rejected due to feature at the destination.| +| FAILED_PRE_EMPTION9+ | 25 | Failed preemption. | +| NON_SELECTED_USER_CLEARING9+ | 26 | Non-selected user clearing. | +| DESTINATION_OUT_OF_ORDER | 27 | Destination out of order. | +| INVALID_NUMBER_FORMAT | 28 | Invalid number format (incomplete number). | +| FACILITY_REJECTED9+ | 29 | Facility rejected. | +| RESPONSE_TO_STATUS_ENQUIRY9+ | 30 | Response to status enquiry. | +| NORMAL_UNSPECIFIED9+ | 31 | Normal, unspecified. | +| NO_CIRCUIT_CHANNEL_AVAILABLE9+ | 34 | No circuit/channel available. | +| NETWORK_OUT_OF_ORDER | 38 | Network fault. | +| TEMPORARY_FAILURE | 41 | Temporary failure. | +| SWITCHING_EQUIPMENT_CONGESTION9+ | 42 | Switching equipment congestion. | +| ACCESS_INFORMATION_DISCARDED9+ | 43 | Access information discarded. | +| REQUEST_CIRCUIT_CHANNEL_NOT_AVAILABLE9+ | 44 | Requested circuit/channel unavailable | +| RESOURCES_UNAVAILABLE_UNSPECIFIED9+ | 47 | Resources unavailable, unspecified. | +| QUALITY_OF_SERVICE_UNAVAILABLE9+ | 49 | QoS unavailable. | +| REQUESTED_FACILITY_NOT_SUBSCRIBED9+ | 50 | Requested facility not subscribed. | +| INCOMING_CALLS_BARRED_WITHIN_THE_CUG9+ | 55 | Incoming calls barred within the CUG. | +| BEARER_CAPABILITY_NOT_AUTHORIZED9+ | 57 | Bearer capability not authorized. | +| BEARER_CAPABILITY_NOT_PRESENTLY_AVAILABLE9+ | 58 | Bearer capability presently available. | +| SERVICE_OR_OPTION_NOT_AVAILABLE_UNSPECIFIED9+ | 63 | Service or option not available, unspecified. | +| BEARER_SERVICE_NOT_IMPLEMENTED9+ | 65 | Bearer service not implemented. | +| ACM_EQUALTO_OR_GREATER_THAN_THE_MAXIMUM_VALUE9+ | 68 | ACM greater than or equal to the maximum value. | +| REQUESTED_FACILITY_NOT_IMPLEMENTED9+ | 69 | Requested facility not implemented. | +| ONLY_RESTRICTED_DIGITAL_INFO_BEARER_CAPABILITY_IS_AVAILABLE9+ | 70 | Only restricted digital information capability available. | +| SERVICE_OR_OPTION_NOT_IMPLEMENTED_UNSPECIFIED9+ | 79 | Service or option not implemented, unspecified. | +| INVALID_TRANSACTION_IDENTIFIER_VALUE9+ | 81 | Invalid transaction identifier value. | +| USER_NOT_MEMBER_OF_CUG9+ | 87 | User not member of CUG. | +| INCOMPATIBLE_DESTINATION9+ | 88 | Incompatible destination. | +| INVALID_TRANSIT_NETWORK_SELECTION9+ | 91 | Invalid transit network selection. | +| SEMANTICALLY_INCORRECT_MESSAGE9+ | 95 | Semantically incorrect message. | +| INVALID_MANDATORY_INFORMATION9+ | 96 | Invalid mandatory information. | +| MESSAGE_TYPE_NON_EXISTENT_OR_NOT_IMPLEMENTED9+ | 97 | Message type non-existent or not implemented. | +| MESSAGE_TYPE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE9+ | 98 | Message type not compatible with protocol state. | +| INFORMATION_ELEMENT_NON_EXISTENT_OR_NOT_IMPLEMENTED9+ | 99 | IE non-existent or not implemented. | +| CONDITIONAL_IE_ERROR9+ | 100 | Conditional IE error. | +| MESSAGE_NOT_COMPATIBLE_WITH_PROTOCOL_STATE9+ | 101 | Message not compatible with protocol state. | +| RECOVERY_ON_TIMER_EXPIRED9+ | 102 | Recovery on timer expiry. | +| PROTOCOL_ERROR_UNSPECIFIED9+ | 111 | Protocol error, unspecified. | +| INTERWORKING_UNSPECIFIED9+ | 127 | Interworking, unspecified. | +| CALL_BARRED9+ | 240 | Call barred. | +| FDN_BLOCKED9+ | 241 | FDN blocked. | +| IMSI_UNKNOWN_IN_VLR9+ | 242 | IMSI unknown in VLR. | +| IMEI_NOT_ACCEPTED9+ | 243 | IMEI not accepted. | +| DIAL_MODIFIED_TO_USSD9+ | 244 | Dial request modified to USSD request. | +| DIAL_MODIFIED_TO_SS9+ | 245 | Dial request modified to SS request. | +| DIAL_MODIFIED_TO_DIAL9+ | 246 | Dial request modified to dial with different number. | +| RADIO_OFF9+ | 247 | Radio off. | +| OUT_OF_SERVICE9+ | 248 | Out of service. | +| NO_VALID_SIM9+ | 249 | No valid SIM. | +| RADIO_INTERNAL_ERROR9+ | 250 | Radio internal error. | +| NETWORK_RESP_TIMEOUT9+ | 251 | Network response timeout. | +| NETWORK_REJECT9+ | 252 | Request rejected by network. | +| RADIO_ACCESS_FAILURE9+ | 253 | Radio access failure. | +| RADIO_LINK_FAILURE9+ | 254 | Radio link failure. | +| RADIO_LINK_LOST9+ | 255 | Radio link lost. | +| RADIO_UPLINK_FAILURE9+ | 256 | Radio uplink failure. | +| RADIO_SETUP_FAILURE9+ | 257 | Radio setup failure. | +| RADIO_RELEASE_NORMAL9+ | 258 | Radio release normal. | +| RADIO_RELEASE_ABNORMAL9+ | 259 | Radio release abnormal. | +| ACCESS_CLASS_BLOCKED9+ | 260 | Access class blocked. | +| NETWORK_DETACH9+ | 261 | Network detached. | +| INVALID_PARAMETER | 1025 | Invalid parameter. | +| SIM_NOT_EXIT | 1026 | SIM not exit. | +| SIM_PIN_NEED | 1027 | SIM PIN needed. | +| CALL_NOT_ALLOW | 1029 | Call not allowed. | +| SIM_INVALID | 1045 | No valid SIM. | +| UNKNOWN | 1279 | Unknown reason. | ## MmiCodeResults9+ diff --git a/en/application-dev/reference/apis/js-apis-camera.md b/en/application-dev/reference/apis/js-apis-camera.md index cc34ebefa765c63b14d0bf65e1d8d26ebe64e4e1..cb1311397a52d39e41466c33135bdc93164a0807 100644 --- a/en/application-dev/reference/apis/js-apis-camera.md +++ b/en/application-dev/reference/apis/js-apis-camera.md @@ -1,4 +1,4 @@ -# Camera Management +# @ohos.multimedia.camera (Camera Management) > **NOTE** > @@ -22,7 +22,7 @@ Obtains a **CameraManager** instance. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ---------------------------- | -| context | [Context](../../ability/context-userguide.md) | Yes | Application context. | +| context | [Context](js-apis-inner-app-context.md) | Yes | Application context. | | callback | AsyncCallback<[CameraManager](#cameramanager)\> | Yes | Callback used to return the **CameraManager** instance.| **Example** @@ -49,7 +49,7 @@ Obtains a **CameraManager** instance. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------- | ------- | ---- | ------------ | -| context | [Context](../../ability/context-userguide.md) | Yes | Application context.| +| context | [Context](js-apis-inner-app-context.md) | Yes | Application context.| **Return value** @@ -84,7 +84,7 @@ Defines the camera profile. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read Only| Description | +| Name | Type | Mandatory| Description | | -------- | ----------------------------- |---- | ------------- | | format | [CameraFormat](#cameraformat) | Yes | Output format. | | size | [Size](#size) | Yes | Resolution. | @@ -95,7 +95,7 @@ Defines the frame rate range. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read Only| Description | +| Name | Type | Mandatory| Description | | -------- | ----------------------------- |---- | ------------- | | min | number | Yes | Minimum frame rate. | | max | number | Yes | Maximum frame rate. | @@ -106,7 +106,7 @@ Defines the video profile. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read Only| Description | +| Name | Type | Mandatory| Description | | ------------------------- | ----------------------------------------- | --- |----------- | | frameRateRange | [FrameRateRange](#frameraterange) | Yes | Frame rate range. | @@ -116,7 +116,7 @@ Defines the camera output capability. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read Only| Description | +| Name | Type | Mandatory| Description | | ----------------------------- | -------------------------------------------------- | --- |------------------- | | previewProfiles | Array<[Profile](#profile)\> | Yes | Supported preview profiles. | | photoProfiles | Array<[Profile](#profile)\> | Yes | Supported shooting profiles. | @@ -171,8 +171,8 @@ Obtains supported cameras. This API uses a promise to return the result. **Example** ```js -cameraManager.getSupportedCameras().then((cameraArray) => { - console.log(`Promise returned with an array of supported cameras: ${cameraArray.length}`); +cameraManager.getSupportedCameras().then((cameras) => { + console.log(`Promise returned with an array of supported cameras: ${cameras.length}`); }) ``` @@ -188,18 +188,21 @@ Obtains the output capability supported by a camera. This API uses an asynchrono | Name | Type | Mandatory| Description | | ------------ |--------------------------------------------------------------- | -- | -------------------------- | -| CameraDevice | [CameraDevice](#cameradevice) | Yes| Camera device. | +| cameraDevice | [CameraDevice](#cameradevice) | Yes| Target camera, which is obtained through **getSupportedCameras**. | | callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | Yes| Callback used to return the output capability.| **Example** ```js -cameraManager.getSupportedOutputCapability(cameradevice, (err, cameras) => { - if (err) { - console.error(`Failed to get the cameras. ${err.message}`); - return; - } - console.log('Callback returned with an array of supported outputCapability'); +cameraManager.getSupportedCameras().then((cameras) => { + let cameraDevice = cameras[0]; + cameraManager.getSupportedOutputCapability(cameraDevice, (err, CameraOutputCapability) => { + if (err) { + console.error(`Failed to get the outputCapability. ${err.message}`); + return; + } + console.log('Callback returned with an array of supported outputCapability'); + }) }) ``` @@ -215,7 +218,7 @@ Obtains the output capability supported by a camera. This API uses a promise to | Name | Type | Mandatory | Description | | -------- | --------------------------------- | ---- | ---------- | -| camera | [CameraDevice](#cameradevice) | Yes | Camera device. | +| cameradevice | [CameraDevice](#cameradevice) | Yes | Target camera, which is obtained through **getSupportedCameras**. | **Return value** @@ -226,8 +229,11 @@ Obtains the output capability supported by a camera. This API uses a promise to **Example** ```js -cameraManager.getSupportedOutputCapability(cameradevice).then((cameraoutputcapability) => { - console.log('Promise returned with an array of supported outputCapability'); +cameraManager.getSupportedCameras().then((cameras) => { + let cameraDevice = cameras[0]; + cameraManager.getSupportedOutputCapability(cameraDevice).then((cameraoutputcapability) => { + console.log('Promise returned with an array of supported outputCapability'); + }) }) ``` @@ -250,7 +256,7 @@ Before calling the API, ensure that the camera can be muted. You can use [isCame **Example** ```js -let ismuted = await cameraManager.isCameraMuted(); +let ismuted = cameraManager.isCameraMuted(); ``` ### isCameraMuteSupported @@ -259,6 +265,8 @@ isCameraMuteSupported(): boolean Checks whether the camera can be muted. +This is a system API. + **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** @@ -270,7 +278,7 @@ Checks whether the camera can be muted. **Example** ```js -let ismutesuppotred = await cameraManager.isCameraMuteSupported(); +let ismutesuppotred = cameraManager.isCameraMuteSupported(); ``` ### muteCamera @@ -279,6 +287,8 @@ muteCamera(mute: boolean): void Mutes or unmutes the camera. +This is a system API. + **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** @@ -290,6 +300,7 @@ Mutes or unmutes the camera. **Example** ```js +let mute = true; cameraManager.muteCamera(mute); ``` @@ -299,8 +310,6 @@ createCameraInput(camera: CameraDevice, callback: AsyncCallback): Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses an asynchronous callback to return the result. -This is a system API. - **Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core @@ -309,13 +318,14 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | --------------------------------- | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object. | +| cameraDevice | [CameraDevice](#cameradevice) | Yes | Target **CameraDevice** object, which is obtained through **getSupportedCameras**. | | callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. | **Example** ```js -cameraManager.createCameraInput(camera, (err, cameraInput) => { +let cameraDevice = cameras[0]; +cameraManager.createCameraInput(cameraDevice, (err, cameraInput) => { if (err) { console.error(`Failed to create the CameraInput instance. ${err.message}`); return; @@ -326,12 +336,10 @@ cameraManager.createCameraInput(camera, (err, cameraInput) => { ### createCameraInput -createCameraInput(camera: CameraDevice): Promise +createCameraInput(cameraDevice: CameraDevice): Promise Creates a **CameraInput** instance with the specified **CameraDevice** object. This API uses a promise to return the result. -This is a system API. - **Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core @@ -340,7 +348,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ---------- | -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| +| cameraDevice | [CameraDevice](#cameradevice) | Yes | Target **CameraDevice** object, which is obtained through **getSupportedCameras**.| **Return value** @@ -351,7 +359,8 @@ This is a system API. **Example** ```js -cameraManager.createCameraInput(camera).then((cameraInput) => { +let cameraDevice = cameras[0]; +cameraManager.createCameraInput(cameraDevice).then((cameraInput) => { console.log('Promise returned with the CameraInput instance'); }) ``` @@ -362,8 +371,6 @@ createCameraInput(position: CameraPosition, type: CameraType, callback: AsyncCal Creates a **CameraInput** instance with the specified camera position and type. This API uses an asynchronous callback to return the result. -This is a system API. - **Required permissions**: ohos.permission.CAMERA **System capability**: SystemCapability.Multimedia.Camera.Core @@ -372,14 +379,17 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | --------------------------------- | -| position | [CameraPosition](#cameraposition) | Yes | Camera position. | -| type | [CameraType](#cameratype) | Yes | Camera type. | +| position | [CameraPosition](#cameraposition) | Yes | Camera position, which is obtained through **getSupportedCameras**. This API obtains a **CameraDevice** object, which contains the camera position information. | +| type | [CameraType](#cameratype) | Yes | Camera type, which is obtained through **getSupportedCameras**. This API obtains a **CameraDevice** object, which contains the camera type information. | | callback | AsyncCallback<[CameraInput](#camerainput)\> | Yes | Callback used to return the **CameraInput** instance. | **Example** ```js -cameraManager.createCameraInput(camera.CameraPosition.CAMERA_POSITION_BACK, camera.CameraType.CAMERA_TYPE_UNSPECIFIED, (err, cameraInput) => { +let cameraDevice = cameras[0]; +let position = cameraDevice.cameraPosition; +let type = cameraDevice.cameraType; +cameraManager.createCameraInput(position, type, (err, cameraInput) => { if (err) { console.error(`Failed to create the CameraInput instance. ${err.message}`); return; @@ -394,8 +404,6 @@ createCameraInput(position: CameraPosition, type:CameraType ): Promise { +let cameraDevice = cameras[0]; +let position = cameraDevice.cameraPosition; +let type = cameraDevice.cameraType; +cameraManager.createCameraInput(position, type).then((cameraInput) => { console.log('Promise returned with the CameraInput instance'); }) ``` @@ -433,14 +444,15 @@ Creates a **PreviewOutput** instance. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------- | -| profile | [Profile](#profile) | Yes | Supported preview profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| profile | [Profile](#profile) | Yes | Supported preview profiles, which are obtained through **getSupportedOutputCapability**.| +| surfaceId| string | Yes | Surface ID, which is obtained from [XComponent](../arkui-ts/ts-basic-components-xcomponent.md) or [ImageReceiver](js-apis-image.md#imagereceiver9).| | callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | Yes | Callback used to return the **PreviewOutput** instance.| **Example** ```js -cameraManager.createPreviewOutput(profile, surfaceId, (err, previewoutput) => { +let profile = cameraoutputcapability.previewProfiles[0]; +cameraManager.createPreviewOutput(profile, surfaceId, (err, previewOutput) => { if (err) { console.error(`Failed to gcreate previewOutput. ${err.message}`); return; @@ -461,8 +473,8 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | -------- | ---------------------------------| ---- | ----------------- | -| profile | [Profile](#profile) | Yes | Supported preview profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)** or **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| profile | [Profile](#profile) | Yes | Supported preview profiles, which are obtained through **getSupportedOutputCapability**.| +| surfaceId| string | Yes | Surface ID, which is obtained from [XComponent](../arkui-ts/ts-basic-components-xcomponent.md) or [ImageReceiver](js-apis-image.md#imagereceiver9).| **Return value** @@ -473,7 +485,8 @@ Creates a **PreviewOutput** instance. This API uses a promise to return the resu **Example** ```js -cameraManager.createPreviewOutput(profile, surfaceId).then((previewoutput) => { +let profile = cameraoutputcapability.previewProfiles[0]; +cameraManager.createPreviewOutput(profile, surfaceId).then((previewOutput) => { console.log('Promise returned with previewOutput created.'); }) ``` @@ -490,14 +503,15 @@ Creates a **PhotoOutput** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ----------------------------------- | -| profile | [Profile](#profile) | Yes | Supported shooting profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| profile | [Profile](#profile) | Yes | Supported shooting profiles, which are obtained through **getSupportedOutputCapability**.| +| surfaceId| string | Yes | Surface ID, which is obtained from [ImageReceiver](js-apis-image.md#imagereceiver9).| | callback | AsyncCallback<[PhotoOutput](#photooutput)\> | Yes | Callback used to return the **PhotoOutput** instance. | **Example** ```js -cameraManager.createPhotoOutput(profile, surfaceId, (err, photooutput) => { +let profile = cameraoutputcapability.photoProfiles[0]; +cameraManager.createPhotoOutput(profile, surfaceId, (err, photoOutput) => { if (err) { console.error(`Failed to create photoOutput. ${err.message}`); return; @@ -518,8 +532,8 @@ Creates a **PhotoOutput** instance. This API uses a promise to return the result | Name | Type | Mandatory| Description | | -------- | ---------------------------------| ---- | ----------- | -| profile | [Profile](#profile) | Yes | Supported shooting profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[ImageReceiver](js-apis-image.md#imagereceiver9)**.| +| profile | [Profile](#profile) | Yes | Supported shooting profiles, which are obtained through **getSupportedOutputCapability**.| +| surfaceId| string | Yes | Surface ID, which is obtained from [ImageReceiver](js-apis-image.md#imagereceiver9).| **Return value** @@ -530,7 +544,8 @@ Creates a **PhotoOutput** instance. This API uses a promise to return the result **Example** ```js -cameraManager.createPhotoOutput(profile, surfaceId).then((photooutput) => { +let profile = cameraoutputcapability.photoProfiles[0]; +cameraManager.createPhotoOutput(profile, surfaceId).then((photoOutput) => { console.log('Promise returned with photoOutput created.'); }) ``` @@ -547,14 +562,15 @@ Creates a **VideoOutput** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------ | -| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| +| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profiles, which are obtained through **getSupportedOutputCapability**.| +| surfaceId| string | Yes | Surface ID, which is obtained from [VideoRecorder](js-apis-media.md#videorecorder9).| | callback | AsyncCallback<[VideoOutput](#videooutput)\> | Yes | Callback used to return the **VideoOutput** instance.| **Example** ```js -cameraManager.createVideoOutput(profile, surfaceId, (err, videooutput) => { +let profile = cameraoutputcapability.videoProfiles[0]; +cameraManager.createVideoOutput(profile, surfaceId, (err, videoOutput) => { if (err) { console.error(`Failed to create videoOutput. ${err.message}`); return; @@ -575,8 +591,8 @@ Creates a **VideoOutput** instance. This API uses a promise to return the result | Name | Type | Mandatory| Description | | -------- | ---------------------------------| ---- | ---------- | -| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profile. | -| surfaceId| string | Yes | Surface ID, which is obtained from **[VideoRecorder](js-apis-media.md#videorecorder9)**.| +| profile | [VideoProfile](#videoprofile) | Yes | Supported video recording profiles, which are obtained through **getSupportedOutputCapability**.| +| surfaceId| string | Yes | Surface ID, which is obtained from [VideoRecorder](js-apis-media.md#videorecorder9).| **Return value** @@ -587,7 +603,8 @@ Creates a **VideoOutput** instance. This API uses a promise to return the result **Example** ```js -cameraManager.createVideoOutput(profile, surfaceId).then((videooutput) => { +let profile = cameraoutputcapability.videoProfiles[0]; +cameraManager.createVideoOutput(profile, surfaceId).then((videoOutput) => { console.log('Promise returned with videoOutput created.'); }) ``` @@ -604,13 +621,14 @@ Creates a **MetadataOutput** instance. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------------- | --- | ---------------------------- | -| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types. | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types, which are obtained through **getSupportedOutputCapability**.| | callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | Yes | Callback used to return the **MetadataOutput** instance. | **Example** ```js -cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataoutput) => { +let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes; +cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataOutput) => { if (err) { console.error(`Failed to create metadataOutput. ${err.message}`); return; @@ -631,7 +649,7 @@ Creates a **MetadataOutput** instance. This API uses a promise to return the res | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------------- | --- | -------------------- | -| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types. | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | Yes | Metadata object types, which are obtained through **getSupportedOutputCapability**. | **Return value** @@ -642,7 +660,8 @@ Creates a **MetadataOutput** instance. This API uses a promise to return the res **Example** ```js -cameraManager.createMetadataOutput().then((metadataoutput) => { +let metadataObjectTypes = cameraoutputcapability.supportedMetadataObjectTypes; +cameraManager.createMetadataOutput(metadataObjectTypes).then((metadataOutput) => { console.log('Promise returned with metadataOutput created.'); }) ``` @@ -664,7 +683,7 @@ Creates a **CaptureSession** instance. This API uses an asynchronous callback to **Example** ```js -cameraManager.createCaptureSession((err, capturesession) => { +cameraManager.createCaptureSession((err, captureSession) => { if (err) { console.error(`Failed to create captureSession. ${err.message}`); return; @@ -690,7 +709,7 @@ Creates a **CaptureSession** instance. This API uses a promise to return the res **Example** ```js -cameraManager.createCaptureSession().then((capturesession) => { +cameraManager.createCaptureSession().then((captureSession) => { console.log('Promise returned with captureSession created.'); }) ``` @@ -729,6 +748,8 @@ on(type: 'cameraMute', callback: AsyncCallback): void Listens for camera mute status changes. This API uses an asynchronous callback to return the result. +This is a system API. + **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** @@ -736,12 +757,12 @@ Listens for camera mute status changes. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | --------------- | ---- | --------- | | type | string | Yes | Event type. The value is fixed at **'cameraMute'**, indicating the camera mute status change event.| -| callback | boolean | Yes | Callback used to return the camera mute status. | +| callback | AsyncCallback\ | Yes | Callback used to return the camera mute status. | **Example** ```js -cameraManager.on('cameraMute', (err, cameraStatusInfo) => { +cameraManager.on('cameraMute', (err, curMuetd) => { if (err) { console.error(`Failed to get cameraMute callback. ${err.message}`); return; @@ -755,10 +776,10 @@ Describes the camera status information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Description | -| ------ | ----------------------------- | ---------- | -| camera | [CameraDevice](#cameradevice) | Camera object.| -| status | [CameraStatus](#camerastatus) | Camera status.| +| Name | Type | Mandatory | Description | +| ------ | ----------------------------- | -------------- | ---------- | +| camera | [CameraDevice](#cameradevice) | Yes | Camera object.| +| status | [CameraStatus](#camerastatus) | Yes | Camera status.| ## CameraPosition @@ -804,27 +825,13 @@ Defines the camera device information. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Read Only| Description | +| Name | Type | Mandatory| Description | | -------------- | --------------------------------- | ---- | ---------- | | cameraId | string | Yes | **CameraDevice** object.| | cameraPosition | [CameraPosition](#cameraposition) | Yes | Camera position. | | cameraType | [CameraType](#cameratype) | Yes | Camera type. | | connectionType | [ConnectionType](#connectiontype) | Yes | Camera connection type.| -**Example** - -```js -async function getCameraInfo("cameraId") { - let cameraManager = await camera.getCameraManager(context); - let cameras = await cameraManager.getSupportedCameras(); - let cameraObj = cameras[0]; - let cameraId = cameraObj.cameraId; - let cameraPosition = cameraObj.cameraPosition; - let cameraType = cameraObj.cameraType; - let connectionType = cameraObj.connectionType; -} -``` - ## Size Enumerates the camera output capability. @@ -853,7 +860,7 @@ Enumerates the camera output formats. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------------- | --------- | ------------ | | CAMERA_FORMAT_RGBA_8888 | 3 | RGB image. | | CAMERA_FORMAT_YUV_420_SP| 1003 | YUV 420 SP image. | @@ -1009,7 +1016,7 @@ cameraInput.release().then(() => { ### on('error') -on(type: 'error', camera:CameraDevice, callback: ErrorCallback): void +on(type: 'error', cameraDevice:CameraDevice, callback: ErrorCallback): void Listens for **CameraInput** errors. This API uses a callback to return the result. @@ -1020,13 +1027,14 @@ Listens for **CameraInput** errors. This API uses a callback to return the resul | Name | Type | Mandatory| Description | | -------- | -------------------------------- | --- | ------------------------------------------- | | type | string | Yes | Event type. The value is fixed at **'error'**, indicating the camera input error event.| -| camera | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| +| cameraDevice | [CameraDevice](#cameradevice) | Yes | **CameraDevice** object.| | callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | Yes | Callback used to return the result. | **Example** ```js -cameraInput.on('error', camera, (cameraInputError) => { +let cameraDevice = cameras[0]; +cameraInput.on('error', cameraDevice, (cameraInputError) => { console.log(`Camera input error code: ${cameraInputError.code}`); }) ``` @@ -1052,9 +1060,9 @@ Defines an error object used for **[CameraInput](#camerainput)**. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | --------------------------------------------- | --------------------- | -| code | [CameraInputErrorCode](#camerainputerrorcode) | **CameraInput** error code.| +| Name| Type | Mandatory | Description | +| ---- | --------------------------------------------- | ------------ |--------------------- | +| code | [CameraInputErrorCode](#camerainputerrorcode) | Yes |**CameraInput** error code.| ## FlashMode @@ -1334,9 +1342,9 @@ captureSession.removeInput(cameraInput).then(() => { ### addOutput -addOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void +addOutput\(previewOutput: CameraOutput, callback: AsyncCallback\): void -Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. +Adds a [CameraOutput](#cameraoutput) instance to this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1344,13 +1352,13 @@ Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. Th | Name | Type | Mandatory| Description | | ------------- | ------------------------------- | ---- | ------------------------ | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.addOutput(cameraOutput, (err) => { +captureSession.addOutput(previewOutput, (err) => { if (err) { console.error(`Failed to add output. ${err.message}`); return; @@ -1361,9 +1369,9 @@ captureSession.addOutput(cameraOutput, (err) => { ### addOutput -addOutput\(cameraOutput: CameraOutput\): Promise +addOutput\(previewOutput: CameraOutput\): Promise -Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. This API uses a promise to return the result. +Adds a [CameraOutput](#cameraoutput) instance to this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1371,7 +1379,7 @@ Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. Th | Name | Type | Mandatory| Description | | ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to add.| +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to add.| **Return value** @@ -1382,16 +1390,16 @@ Adds a **[CameraOutput](#cameraoutput)** instance to this **CaptureSession**. Th **Example** ```js -captureSession.addOutput(cameraOutput).then(() => { +captureSession.addOutput(previewOutput).then(() => { console.log('Promise returned with cameraOutput added.'); }) ``` ### removeOutput -removeOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void +removeOutput\(previewOutput: CameraOutput, callback: AsyncCallback\): void -Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. +Removes a [CameraOutput](#cameraoutput) instance from this **CaptureSession**. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1399,13 +1407,13 @@ Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession* | Name | Type | Mandatory| Description | | ------------- | ------------------------------- | ---- | ------------------------ | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| | callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -captureSession.removeOutput(cameraOutput, (err) => { +captureSession.removeOutput(previewOutput, (err) => { if (err) { console.error(`Failed to remove the CameraOutput instance. ${err.message}`); return; @@ -1416,9 +1424,9 @@ captureSession.removeOutput(cameraOutput, (err) => { ### removeOutput -removeOutput(cameraOutput: CameraOutput): Promise +removeOutput(previewOutput: CameraOutput): Promise -Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession**. This API uses a promise to return the result. +Removes a [CameraOutput](#cameraoutput) instance from this **CaptureSession**. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -1426,7 +1434,7 @@ Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession* | Name | Type | Mandatory| Description | | ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | Yes | **CameraOutput** instance to remove.| +| previewOutput | [PreviewOutput](#previewoutput) | Yes | **PreviewOutput** instance to remove.| **Return value** @@ -1439,7 +1447,7 @@ Removes a **[CameraOutput](#cameraoutput)** instance from this **CaptureSession* **Example** ```js -captureSession.removeOutput(cameraOutput).then(() => { +captureSession.removeOutput(previewOutput).then(() => { console.log('Promise returned to indicate that the CameraOutput instance is removed.'); }) ``` @@ -2106,8 +2114,8 @@ Obtains the exposure compensation values. This API uses a promise to return the **Example** ```js -captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { - console.log(`Promise returned with exposure mode supported : ${isSupported}`); +captureSession.getExposureBiasRange().then((biasRangeArray) => { + console.log('Promise returned with the array of compenstation range: ' + JSON.stringify(biasRangeArray)); }) ``` @@ -2125,13 +2133,14 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure | Name | Type | Mandatory| Description | | -------- | -------------------------------| ---- | ------------------- | -| exposureBias | number | Yes | Compensation value. | +| exposureBias | number | Yes | Compensation value. You can use **getExposureBiasRange** to obtain the supported values.| | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.setExposureBias(-4,(err) => { +let exposureBias = biasRangeArray[0]; +captureSession.setExposureBias(exposureBias,(err) => { if (err) { console.log(`Failed to set the exposure bias ${err.message}`); return ; @@ -2154,7 +2163,7 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure | Name | Type | Mandatory| Description | | -------------- | --------- | ---- | --------- | -| exposureBias | number | Yes | Compensation value. | +| exposureBias | number | Yes | Compensation value. You can use **getExposureBiasRange** to obtain the supported values. | **Return value** @@ -2165,7 +2174,8 @@ Before the setting, you are advised to use **[getExposureBiasRange](#getexposure **Example** ```js -captureSession.setExposureBias(-4).then(() => { +let exposureBias = biasRangeArray[0]; +captureSession.setExposureBias(exposureBias).then(() => { console.log('Promise returned with the successful execution of setExposureBias.'); }) ``` @@ -2595,13 +2605,14 @@ Sets a zoom ratio. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | --------- | -------------------- | ---- | ------------------- | -| zoomRatio | number | Yes | Zoom ratio. | +| zoomRatio | number | Yes | Zoom ratio. You can use **getZoomRatioRange** to obtain the supported values.| | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -captureSession.setZoomRatio(1, (err) => { +let zoomRatio = zoomRatioRange[0]; +captureSession.setZoomRatio(zoomRatio, (err) => { if (err) { console.error(`Failed to set the zoom ratio value ${err.message}`); return; @@ -2622,7 +2633,7 @@ Sets a zoom ratio. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | --------- | ------ | ---- | --------- | -| zoomRatio | number | Yes | Zoom ratio.| +| zoomRatio | number | Yes | Zoom ratio. You can use **getZoomRatioRange** to obtain the supported values.| **Return value** @@ -2633,7 +2644,8 @@ Sets a zoom ratio. This API uses a promise to return the result. **Example** ```js -captureSession.setZoomRatio(1).then(() => { +let zoomRatio = zoomRatioRange[0]; +captureSession.setZoomRatio(zoomRatio).then(() => { console.log('Promise returned with the successful execution of setZoomRatio.'); }) ``` @@ -2902,45 +2914,49 @@ Defines a **CaptureSession** error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------------- | -------------------------- | -| code | [CaptureSessionError](#capturesessionerror) | **CaptureSession** error code.| +| Name| Type | Mandatory | Description | +| ---- | ------------------------------------------- | -------------------------- |-------------------------- | +| code | [CaptureSessionError](#capturesessionerror) | Yes |**CaptureSession** error code.| ## CameraOutput Implements output information used in a **[CaptureSession](#capturesession)**. It is the base class of **output**. -### release +## PreviewOutput -release(callback: AsyncCallback): void +Implements preview output. It inherits **[CameraOutput](#cameraoutput)**. -Releases output resources. This API uses an asynchronous callback to return the result. +### start + +start(callback: AsyncCallback): void + +Starts to output preview streams. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** | Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------- | +| -------- | -------------------- | ---- | -------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -cameraOutput.release((err) => { +previewOutput.start((err) => { if (err) { - console.error(`Failed to release the PreviewOutput instance ${err.message}`); + console.error(`Failed to start the previewOutput. ${err.message}`); return; } - console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); -}); + console.log('Callback returned with previewOutput started.'); +}) ``` -### release +### start -release(): Promise +start(): Promise -Releases output resources. This API uses a promise to return the result. +Starts to output preview streams. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2953,20 +2969,16 @@ Releases output resources. This API uses a promise to return the result. **Example** ```js -cameraOutput.release().then(() => { - console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +previewOutput.start().then(() => { + console.log('Promise returned with previewOutput started.'); }) ``` -## PreviewOutput - -Implements preview output. It inherits **[CameraOutput](#cameraoutput)**. - -### start +### stop -start(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Starts to output preview streams. This API uses an asynchronous callback to return the result. +Stops outputting preview streams. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core @@ -2979,82 +2991,82 @@ Starts to output preview streams. This API uses an asynchronous callback to retu **Example** ```js -previewOutput.start((err) => { +previewOutput.stop((err) => { if (err) { - console.error(`Failed to start the previewOutput. ${err.message}`); + console.error(`Failed to stop the previewOutput. ${err.message}`); return; } - console.log('Callback returned with previewOutput started.'); + console.log('Callback returned with previewOutput stopped.'); }) ``` -### start +### stop -start(): Promise +stop(): Promise -Starts to output preview streams. This API uses a promise to return the result. +Stops outputting preview streams. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** | Type | Description | -| -------------- | ----------------------- | +| -------------- | ------------------------ | | Promise| Promise used to return the result.| **Example** ```js -previewOutput.start().then(() => { - console.log('Promise returned with previewOutput started.'); +previewOutput.stop().then(() => { + console.log('Callback returned with previewOutput stopped.'); }) ``` -### stop +### release -stop(callback: AsyncCallback): void +release(callback: AsyncCallback): void -Stops outputting preview streams. This API uses an asynchronous callback to return the result. +Releases output resources. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** | Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | -------------------- | +| -------- | -------------------- | ---- | ------------------- | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -previewOutput.stop((err) => { +previewOutput.release((err) => { if (err) { - console.error(`Failed to stop the previewOutput. ${err.message}`); + console.error(`Failed to release the PreviewOutput instance ${err.message}`); return; } - console.log('Callback returned with previewOutput stopped.'); -}) + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); ``` -### stop +### release -stop(): Promise +release(): Promise -Stops outputting preview streams. This API uses a promise to return the result. +Releases output resources. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** | Type | Description | -| -------------- | ------------------------ | +| -------------- | ----------------------- | | Promise| Promise used to return the result.| **Example** ```js -previewOutput.stop().then(() => { - console.log('Callback returned with previewOutput stopped.'); +previewOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); }) ``` @@ -3143,9 +3155,9 @@ Defines the preview output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------------------- | ---------------------- | -| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | **PreviewOutput** error code.| +| Name| Type | Mandatory | Description | +| ---- | ------------------------------------------------- | ---------------- |---------------------- | +| code | [PreviewOutputErrorCode](#previewoutputerrorcode) | Yes |**PreviewOutput** error code.| ## ImageRotation @@ -3191,16 +3203,16 @@ Defines the settings for photo capture. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name | Type | Mandatory | Default Value | Description | -| -------- | ------------------------------- | ---- | ----------------- | -----------------| -| quality | [QualityLevel](#qualitylevel) | No | QUALITY_LEVEL_HIGH| Photo quality. | -| rotation | [ImageRotation](#imagerotation) | No | ROTATION_0 | Rotation angle of the photo. | -| location | [Location](#location) | No | (0,0,0) | Geolocation information of the photo. | -| mirror | boolean | No | false |Whether mirroring is enabled. By default, mirroring is disabled.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------- | ---- | -----------------| +| quality | [QualityLevel](#qualitylevel) | No | Photo quality. | +| rotation | [ImageRotation](#imagerotation) | No | Rotation angle of the photo. | +| location | [Location](#location) | No | Geolocation information of the photo. | +| mirror | boolean | No |Whether mirroring is enabled. By default, mirroring is disabled.| ## PhotoOutput -Implements output information used in a **CaptureSession**. +Implements output information used in a shooting session. This class inherits from [CameraOutput](#cameraoutput). ### capture @@ -3246,9 +3258,16 @@ Captures a photo with the specified shooting parameters. This API uses an asynch **Example** ```js -let settings:PhotoCaptureSetting = { - quality = 1, - rotation = 0 +let captureLocation = { + latitude: 0, + longitude: 0, + altitude: 0, +} +let settings = { + quality: camera.QualityLevel.QUALITY_LEVEL_LOW, + rotation: camera.ImageRotation.ROTATION_0, + location: captureLocation, + mirror: false } photoOutput.capture(settings, (err) => { if (err) { @@ -3314,6 +3333,54 @@ photoOutput.isMirrorSupported((err, isSupported) => { }) ``` +### release + +release(callback: AsyncCallback): void + +Releases output resources. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +photoOutput.release((err) => { + if (err) { + console.error(`Failed to release the PreviewOutput instance ${err.message}`); + return; + } + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); +``` + +### release + +release(): Promise + +Releases output resources. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| -------------- | ----------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +photoOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +}) +``` + ### isMirrorSupported isMirrorSupported(): Promise @@ -3471,13 +3538,13 @@ Defines a photo output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputErrorCode](#photooutputerrorcode) | **PhotoOutput** error code.| +| Name| Type | Mandatory |Description | +| ---- | ------------------------------------- | --------- | ----------------------- | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Yes | **PhotoOutput** error code.| ## VideoOutput -Implements output information used in a video recording session. +Implements output information used in a video recording session. This class inherits from [CameraOutput](#cameraoutput). ### start @@ -3576,6 +3643,54 @@ videoOutput.stop().then(() => { }) ``` +### release + +release(callback: AsyncCallback): void + +Releases output resources. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Example** + +```js +videoOutput.release((err) => { + if (err) { + console.error(`Failed to release the PreviewOutput instance ${err.message}`); + return; + } + console.log('Callback invoked to indicate that the PreviewOutput instance is released successfully.'); +}); +``` + +### release + +release(): Promise + +Releases output resources. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +**Return value** + +| Type | Description | +| -------------- | ----------------------- | +| Promise| Promise used to return the result.| + +**Example** + +```js +videoOutput.release().then(() => { + console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); +}) +``` + ### on('frameStart') on(type: 'frameStart', callback: AsyncCallback): void @@ -3662,348 +3777,354 @@ Defines a video output error. **System capability**: SystemCapability.Multimedia.Camera.Core -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [PhotoOutputErrorCode](#photooutputerrorcode) | **VideoOutput** error code.| - -## MetadataObjectType - -Enumerates metadata streams. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ------------------------- | ---- | ----------------- | -| FACE_DETECTION | 0 | Metadata object type.| - -## Rect - -Defines a rectangle. +| Name| Type | Mandatory | Description | +| ---- | ------------------------------------- | ----------------- | ----------------------- | +| code | [PhotoOutputErrorCode](#photooutputerrorcode) | Yes | **VideoOutput** error code.| -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Type | Description | -| -------- | ------ | -------------------- | -| topLeftX | number | X-axis coordinate of the upper left corner of the rectangle. | -| topLeftY | number | Y-axis coordinate of the upper left corner of the rectangle. | -| width | number | Width of the rectangle. | -| height | number | Height of the rectangle. | - -## MetadataObject +## MetadataOutput -Implements camera metadata, which is the data source of **[CameraInput](#camerainput)**. +Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**. -### getType +### start -getType(callback: AsyncCallback): void +start(callback: AsyncCallback): void -Obtains the metadata object type. This API uses an asynchronous callback to return the result. +Starts to output metadata. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------------- | --- | -------------------- | -| callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -metadataObject.getType((err, metadataObjectType) => { +metadataOutput.start((err) => { if (err) { - console.error(`Failed to get type. ${err.message}`); + console.error(`Failed to start metadataOutput. ${err.message}`); return; } - console.log('Callback returned with an array of metadataObjectType.'); + console.log('Callback returned with metadataOutput started.'); }) ``` -### getType +### start -getType(): Promise +start(): Promise -Obtains the metadata object type. This API uses a promise to return the result. +Starts to output metadata. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| --------------------------------------------------- | --------------------------- | -| Promise<[MetadataObjectType](#metadataobjecttype)\> | Promise used to return the result.| +| Type | Description | +| ---------------------- | ------------------------ | +| Promise | Promise used to return the result.| **Example** ```js -metadataObject.getType().then((metadataObjectType) => { - console.log('Callback returned with an array of metadataObjectType.'); +metadataOutput.start().then(() => { + console.log('Callback returned with metadataOutput started.'); }) ``` -### getTimestamp +### stop -getTimestamp(callback: AsyncCallback): void +stop(callback: AsyncCallback): void -Obtains the metadata timestamp. This API uses an asynchronous callback to return the result. +Stops outputting metadata. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -metadataObject.getTimestamp((err,timestamp) => { +metadataOutput.stop((err) => { if (err) { - console.error(`Failed to get timestamp. ${err.message}`); + console.error(`Failed to stop the metadataOutput. ${err.message}`); return; } - console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); + console.log('Callback returned with metadataOutput stopped.'); }) ``` -### getTimestamp +### stop -getTimestamp(): Promise +stop(): Promise -Obtains the metadata timestamp. This API uses a promise to return the result. +Stops outputting metadata. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ---------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| ---------------------- | --------------------------- | +| Promise | Promise used to return the result.| **Example** ```js -metadataObject.getTimestamp().then((timestamp) => { - console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); +metadataOutput.stop().then(() => { + console.log('Callback returned with metadataOutput stopped.'); }) ``` -### getBoundingBox +### on('metadataObjectsAvailable') -getBoundingBox(callback: AsyncCallback): void +on(type: 'metadataObjectsAvailable', callback: AsyncCallback\>): void -Obtains the bounding box of metadata. This API uses an asynchronous callback to return the result. +Listens for metadata objects. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------------ | -| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**, that is, the metadata object.| +| callback | Callback\> | Yes | Callback used to return the error information. | **Example** ```js -metadataObject.getBoundingBox((err, rect) => { - if (err) { - console.error(`Failed to get boundingBox. ${err.message}`); - return; - } - console.log('Callback returned with boundingBox getted.'); +metadataOutput.on('metadataObjectsAvailable', (metadataObjectArr) => { + console.log(`metadata output metadataObjectsAvailable`); }) ``` -### getBoundingBox +### on('error') -getBoundingBox(): Promise +on(type: 'error', callback: ErrorCallback): void -Obtains the bounding box of metadata. This API uses a promise to return the result. +Listens for metadata errors. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Return value** +**Parameters** -| Type | Description | -| ---------------------- | --------------------------- | -| Promise<[Rect](#rect)\> | Promise used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | --------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **'error'**, that is, the metadata error.| +| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | Yes | Callback used to return the error information. | **Example** ```js -metadataObject.getBoundingBox().then((rect) => { - console.log('Callback returned with boundingBox getted.'); +metadataOutput.on('error', (metadataOutputError) => { + console.log(`Metadata output error code: ${metadataOutputError.code}`); }) ``` -## MetadataFaceObject +## MetadataOutputErrorCode -Implements the face object of metadata. It inherits [MetadataObject](#metadataobject). +Enumerates the codes used for metadata output errors. -## MetadataOutput +**System capability**: SystemCapability.Multimedia.Camera.Core -Implements metadata streams. It inherits **[CameraOutput](#cameraoutput)**. +| Name | Value | Description | +| ------------------------------- | ---- | -------- | +| ERROR_UNKNOWN | -1 | Unknown error.| +| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| -### start +## MetadataOutputError -start(callback: AsyncCallback): void +Defines a metadata output error. -Starts to output metadata. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name| Type | Mandatory | Description | +| ---- | ------------------------------------- | ----------------- | ----------------------- | +| code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | Yes | **MetadataOutput** error code.| + +## MetadataObjectType + +Enumerates metadata streams. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Value | Description | +| ------------------------- | ---- | ----------------- | +| FACE_DETECTION | 0 | Metadata object type.| + +## Rect + +Defines a rectangle. + +**System capability**: SystemCapability.Multimedia.Camera.Core + +| Name | Type | Mandatory | Description | +| -------- | ------ | --------------- | -------------------- | +| topLeftX | number | Yes | X-axis coordinate of the upper left corner of the rectangle. | +| topLeftY | number | Yes | Y-axis coordinate of the upper left corner of the rectangle. | +| width | number | Yes | Width of the rectangle. | +| height | number | Yes |Height of the rectangle. | + +## MetadataObject + +Implements camera metadata, which is the data source of [CameraInput](#camerainput). The metadata is obtained through metadataOutput.on('metadataObjectsAvailable'). + +### getType + +getType(callback: AsyncCallback): void + +Obtains the metadata object type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | --- | -------------------- | +| callback | AsyncCallback<[MetadataObjectType](#metadataobjecttype)\> | Yes | Callback used to return the result.| **Example** ```js -metadataOutput.start((err) => { +let metadataObject = metadataObjectArr[0]; +metadataObject.getType((err, metadataObjectType) => { if (err) { - console.error(`Failed to start metadataOutput. ${err.message}`); + console.error(`Failed to get type. ${err.message}`); return; } - console.log('Callback returned with metadataOutput started.'); + console.log('Callback returned with an array of metadataObjectType.'); }) ``` -### start +### getType -start(): Promise +getType(): Promise -Starts to output metadata. This API uses a promise to return the result. +Obtains the metadata object type. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ---------------------- | ------------------------ | -| Promise | Promise used to return the result.| +| Type | Description | +| --------------------------------------------------- | --------------------------- | +| Promise<[MetadataObjectType](#metadataobjecttype)\> | Promise used to return the result.| **Example** ```js -metadataOutput.start().then(() => { - console.log('Callback returned with metadataOutput started.'); +let metadataObject = metadataObjectArr[0]; +metadataObject.getType().then((metadataObjectType) => { + console.log('Callback returned with an array of metadataObjectType.'); }) ``` -### stop +### getTimestamp -stop(callback: AsyncCallback): void +getTimestamp(callback: AsyncCallback): void -Stops outputting metadata. This API uses an asynchronous callback to return the result. +Obtains the metadata timestamp. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -metadataOutput.stop((err) => { +let metadataObject = metadataObjectArr[0]; +metadataObject.getTimestamp((err,timestamp) => { if (err) { - console.error(`Failed to stop the metadataOutput. ${err.message}`); + console.error(`Failed to get timestamp. ${err.message}`); return; } - console.log('Callback returned with metadataOutput stopped.'); + console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); }) ``` -### stop +### getTimestamp -stop(): Promise +getTimestamp(): Promise -Stops outputting metadata. This API uses a promise to return the result. +Obtains the metadata timestamp. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Return value** -| Type | Description | -| ---------------------- | --------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| ---------------- | --------------------------- | +| Promise | Promise used to return the result.| **Example** ```js -metadataOutput.stop().then(() => { - console.log('Callback returned with metadataOutput stopped.'); +let metadataObject = metadataObjectArr[0]; +metadataObject.getTimestamp().then((timestamp) => { + console.log('Callback returned with timestamp getted timestamp : ${timestamp}'); }) ``` -### on('metadataObjectsAvailable') +### getBoundingBox -on(type: 'metadataObjectsAvailable', callback: AsyncCallback\>): void +getBoundingBox(callback: AsyncCallback): void -Listens for metadata objects. This API uses an asynchronous callback to return the result. +Obtains the bounding box of metadata. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | ------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **'metadataObjectsAvailable'**, that is, the metadata object.| -| callback | Callback\> | Yes | Callback used to return the error information. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<[Rect](#rect)\> | Yes | Callback used to return the result.| **Example** ```js -metadataOutput.on('metadataObjectsAvailable', (metadataObject) => { - console.log(`metadata output error code: ${metadataObject.code}`); +let metadataObject = metadataObjectArr[0]; +metadataObject.getBoundingBox((err, rect) => { + if (err) { + console.error(`Failed to get boundingBox. ${err.message}`); + return; + } + console.log('Callback returned with boundingBox getted.'); }) ``` -### on('error') +### getBoundingBox -on(type: 'error', callback: ErrorCallback): void +getBoundingBox(): Promise -Listens for metadata errors. This API uses an asynchronous callback to return the result. +Obtains the bounding box of metadata. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Camera.Core -**Parameters** +**Return value** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------ | ---- | --------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **'error'**, that is, the metadata error.| -| callback | Callback<[MetadataOutputError](#metadataoutputerror)\> | Yes | Callback used to return the error information. | +| Type | Description | +| ---------------------- | --------------------------- | +| Promise<[Rect](#rect)\> | Promise used to return the result.| **Example** ```js -metadataOutput.on('error', (metadataOutputError) => { - console.log(`Metadata output error code: ${metadataOutputError.code}`); +let metadataObject = metadataObjectArr[0]; +metadataObject.getBoundingBox().then((rect) => { + console.log('Callback returned with boundingBox getted.'); }) ``` -## MetadataOutputErrorCode - -Enumerates the codes used for metadata output errors. - -**System capability**: SystemCapability.Multimedia.Camera.Core - -| Name | Value | Description | -| ------------------------------- | ---- | -------- | -| ERROR_UNKNOWN | -1 | Unknown error.| -| ERROR_INSUFFICIENT_RESOURCES | 0 | Insufficient resources.| - -## MetadataOutputError - -Defines a metadata output error. - -**System capability**: SystemCapability.Multimedia.Camera.Core +## MetadataFaceObject -| Name| Type | Description | -| ---- | ------------------------------------- | ----------------------- | -| code | [MetadataOutputErrorCode](#metadataoutputerrorcode) | **MetadataOutput** error code.| +Implements the face object of metadata. It inherits [MetadataObject](#metadataobject). diff --git a/en/application-dev/reference/apis/js-apis-cardEmulation.md b/en/application-dev/reference/apis/js-apis-cardEmulation.md index b4f3906b02b1dea7dabd558173010a37e65c2c19..329a2e6126de45fe401a748bd580a372cd1dc18e 100644 --- a/en/application-dev/reference/apis/js-apis-cardEmulation.md +++ b/en/application-dev/reference/apis/js-apis-cardEmulation.md @@ -1,11 +1,11 @@ -# Standard NFC Card Emulation +# @ohos.nfc.cardEmulation 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**
+> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ``` @@ -18,7 +18,7 @@ Enumerates the NFC card emulation types. **System capability**: SystemCapability.Communication.NFC.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | HCE | 0 | HCE.| | UICC | 1 | Subscriber identity module (SIM) card emulation.| @@ -30,8 +30,6 @@ 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** @@ -42,9 +40,9 @@ Checks whether a certain type of card emulation is supported. **Return value** - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the card emulation type is supported; returns **false** otherwise.| ## HceService8+ diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md new file mode 100644 index 0000000000000000000000000000000000000000..dc506245c6feef1b2c22b70613ce3359404162dc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-cert.md @@ -0,0 +1,2109 @@ +# @ohos.security.cert (Certificate) + +The **certificate** module provides APIs for performing certificate operations. For details about the APIs for implementing the basic algorithm capabilities based on the cryptographic (crypto) framework, see [Crypto Framework](js-apis-cryptoFramework.md). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. + +## Modules to Import + +```javascript +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" +``` + +## CertResult + + Enumerates the error codes. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value | Description | +| --------------------------------------| -------- | -----------------------------| +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | This operation is not supported. | +| ERR_OUT_OF_MEMORY | 19020001 | Memory error. | +| ERR_RUNTIME_ERROR | 19020002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 19030001 | Crypto operation error. | +| ERR_CERT_SIGNATURE_FAILURE | 19030002 | The certificate signature verification failed. | +| ERR_CERT_NOT_YET_VALID | 19030003 | The certificate has not taken effect. | +| ERR_CERT_HAS_EXPIRED | 19030004 | The certificate has expired. | +| ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY | 19030005 | Failed to obtain the certificate issuer. | +| ERR_KEYUSAGE_NO_CERTSIGN | 19030006 | The key cannot be used for signing a certificate. | +| ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE | 19030007 | The key cannot be used for digital signature. | + +## DataBlob +Defines a binary data array. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data. | + +## DataArray + +Defines a list of data arrays. + **System capability**: SystemCapability.Security.Cert +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | ---- | ----------------| +| data | Uint8Array | Yes | Yes | Data list. | + +## EncodingFormat + + Enumerates the certificate encoding formats. + + **System capability**: SystemCapability.Security.Cert + +| Name | Value| Description | +| ---------- | ------ | --------- | +| FORMAT_DER | 0 | Distinguished Encoding Rules (DER) format.| +| FORMAT_PEM | 1 | Privacy-Enhanced Mail (PEM) format.| + + +## EncodingBlob + +Defines a certificate binary array in encoding format. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data.| +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## CertChainData + +Defines the certificate chain data, which is passed in as input parameters during certificate chain verification. + +### Attributes + +**System capability**: SystemCapability.Security.Cert + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------------------------- | ---- | ---- | ------------------------------------------------------------ | +| data | Uint8Array | Yes | Yes | Certificate data, in the *length* (2 bytes) + *data* format. For example, **08ABCDEFGH07ABCDEFG**. The first two bytes indicate the length of the first certificate is eight bytes, and the following eight bytes indicate the certificate data. Then, the next two bytes indicate the length of another certificate is seven bytes, and the seven bytes followed indicate the certificate data.| +| count | number | Yes | Yes | Number of certificates contained in the input data. | +| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. | + + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Cert** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cer** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + } +}); +``` + +## cryptoCert.createX509Cert + +createX509Cert(inStream : EncodingBlob) : Promise\ + +Creates an **X509Cert** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data.| + +**Return value** + +| Type | Description | +| ------- | ---------------- | +| Promise\ | **X509Cer** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Cert + +Provides APIs for X.509 certificate operations. + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the certificate signature. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the certificate signature. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance. + let pubKey = null; + x509Cert.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 certificate data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized X.509 certificate data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + x509Cert.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 certificate data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | ---------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized X.509 certificate data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob).then(x509Cert => { + console.log("createX509Cert success"); + x509Cert.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getPublicKey + +getPublicKey() : cryptoFramework.PubKey + +Obtains the public key of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| cryptoFramework.PubKey | X.509 certificate public key obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let pubKey = null; + try { + pubKey = x509Cert.getPublicKey(); + } catch (error) { + console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### checkValidityWithDate + +checkValidityWithDate(date: string) : void + +Checks the validity period of this X.509 certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------- | +| date | string | Yes | Date of the certificate to check. | + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let date = "150527000001Z"; + + // Verify the certificate validity period. + try { + x509Cert.checkValidityWithDate(date); + } catch (error) { + console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getVersion + +getVersion() : number + +Obtains the X.509 certificate version. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------- | +| number | X.509 certificate version obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let version = x509Cert.getVersion(); + } +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the X.509 certificate serial number. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | X.509 certificate serial number obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let serialNumber = x509Cert.getSerialNumber(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the X.509 certificate issuer. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- | +| [DataBlob](#datablob) | X.509 certificate issuer obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerName = x509Cert.getIssuerName(); + } +}); +``` + +### getSubjectName + +getSubjectName() : DataBlob + +Obtains the subject of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Subject name obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectName = x509Cert.getSubjectName(); + } +}); +``` + +### getNotBeforeTime + +getNotBeforeTime() : string + +Obtains the start time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Start time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notBefore = x509Cert.getNotBeforeTime(); + } +}); +``` + +### getNotAfterTime + +getNotAfterTime() : string + +Obtains the expiration time of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------- | +| string | Expiration time of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let notAfter = x509Cert.getNotAfterTime(); + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Signature data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let signature = x509Cert.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | X.509 certificate signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgName = x509Cert.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the object identifier (OID) of the X.509 certificate signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------- | +| string | OID obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgOid = x509Cert.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the signing algorithm parameters of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------ | +| [DataBlob](#datablob) | X.509 certificate signing algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let sigAlgParams = x509Cert.getSignatureAlgParams(); + } +}); +``` + +### getKeyUsage + +getKeyUsage() : DataBlob + +Obtains the key usage of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | -------------------- | +| [DataBlob](#datablob) | Key usage of the X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let keyUsage = x509Cert.getKeyUsage(); + } +}); +``` + +### getExtKeyUsage + +getExtKeyUsage() : DataArray + +Obtains the usage of the extended key of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | Usage of the extended key obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let extKeyUsage = x509Cert.getExtKeyUsage(); + } +}); +``` + +### getBasicConstraints + +getBasicConstraints() : number + +Obtains the basic constraints for obtaining this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| number | Basic constraints obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let basicConstraints = x509Cert.getBasicConstraints(); + } +}); +``` + +### getSubjectAltNames + +getSubjectAltNames() : DataArray + +Obtains the Subject Alternative Names (SANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------ | +| [DataArray](#dataarray) | SANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let subjectAltNames = x509Cert.getSubjectAltNames(); + } +}); +``` + +### getIssuerAltNames + +getIssuerAltNames() : DataArray + +Obtains the Issuer Alternative Names (IANs) of this X.509 certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------- | -------------------------- | +| [DataArray](#dataarray) | IANs obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Certificate binary data, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) { + if (error != null) { + console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Cert success"); + let issuerAltNames = x509Cert.getIssuerAltNames(); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void + +Creates an **X509Crl** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------------------ | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + } +}); +``` + +## cryptoCert.createX509Crl + +createX509Crl(inStream : EncodingBlob) : Promise\ + +Creates an **X509Crl** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | -------------------------- | +| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized CRL data.| + +**Return value** + +| Type | Description | +| ----------------- | -------------------- | +| Promise\ | Promise used to return the **X509Crl** instance created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +## X509Crl + +Provides APIs for X.509 certificate CRL operations. + +### isRevoked + +isRevoked(cert : X509Cert) : boolean + +Checks whether an X.509 certificate is revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| cert | X509Cert | Yes | X.509 certificate to check.| + +**Return value** + +| Type | Description | +| --------- | --------------------------------------------- | +| boolean | Promise used to return the result. The value **true** indicates the certificate is revoked; the value **false** indicates the opposite.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let revokedFlag = x509Crl.isRevoked(x509Cert); + } catch (error) { + console.log("isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getType + +getType() : string + +Obtains the CRL type. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| string | CRL type obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let type = x509Crl.getType(); + } +}); +``` + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------ | +| callback | AsyncCallback\ | Yes | Callback invoked to return the serialized X.509 CRL data obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } + }); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized X.509 CRL data. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ---------------------- | -------------------------------- | +| Promise\ | Promise used to return the serialized X.509 CRL data obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getEncoded().then(result => { + console.log("getEncoded success"); + }, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void + +Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey, function (error, data) { + if (error != null) { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("verify success"); + } + }); + } +}); +``` + +### verify + +verify(key : cryptoFramework.PubKey) : Promise\ + +Verifies the signature of the X.509 CRL. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.| + +**Return value** + +| Type| Description | +| ---- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; +import cryptoFramework from "@ohos.security.cryptoFramework" + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + // Generate the public key by AsyKeyGenerator. + let pubKey = null; + x509Crl.verify(pubKey).then(result => { + console.log("verify success"); + }, error => { + console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getVersion + +getVersion() : number + +Obtains the version of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| number | Version of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let version = x509Crl.getVersion(); + } +}); +``` + +### getIssuerName + +getIssuerName() : DataBlob + +Obtains the issuer of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Issuer of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let issuerName = x509Crl.getIssuerName(); + } +}); +``` + +### getLastUpdate + +getLastUpdate() : string + +Obtains the date when the X.509 CRL was last updated. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Last update date of the X.509 CRL.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let lastUpdate = x509Crl.getLastUpdate(); + } +}); +``` + +### getNextUpdate + +getNextUpdate() : string + +Obtains the date when the CRL will be updated the next time. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Next update date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let nextUpdate = x509Crl.getNextUpdate(); + } +}); +``` + +### getRevokedCert + +getRevokedCert(serialNumber : number) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified serial number of the certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | -------------- | +| serialNumber | number | Yes | Serial number of the certificate.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Set the serial number of the corresponding certificate. + let serialNumber = 1000; + try { + let entry = x509Crl.getRevokedCert(serialNumber); + } catch (error) { + console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCertWithCert + +getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry + +Obtains the revoked X.509 certificate based on the specified certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------- | ---- | ------------ | +| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.| + +**Return value** + +| Type | Description | +| ------------ | -------------------- | +| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + // Create an X509Cert instance. + let x509Cert = null; + try { + let entry = x509Crl.getRevokedCertWithCert(x509Cert); + } catch (error) { + console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getRevokedCerts + +getRevokedCerts(callback : AsyncCallback>) : void + +Obtains all the revoked X.509 certificates. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts(function (error, array) { + if (error != null) { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getRevokedCerts success"); + } + }); + } +}); +``` + +### getRevokedCerts + +getRevokedCerts() : Promise> + +Obtains all the revoked X.509 certificates. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ----------------------------- | ---------------------- | +| Promise> | Promise used to return a list of revoked X.509 certificates.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob).then(x509Crl => { + console.log("createX509Crl success"); + x509Crl.getRevokedCerts().then(array => { + console.log("getRevokedCerts success"); + }, error => { + console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message); + }); +}, error => { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getTbsInfo + +getTbsInfo() : DataBlob + +Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| [DataBlob](#datablob) | Promise used to return the **tbsCertList** information obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + try { + let tbsInfo = x509Crl.getTbsInfo(); + } catch (error) { + console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message); + } + } +}); +``` + +### getSignature + +getSignature() : DataBlob + +Obtains the signature data of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------ | +| [DataBlob](#datablob) | Signature data of the X.509 CRL obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let signature = x509Crl.getSignature(); + } +}); +``` + +### getSignatureAlgName + +getSignatureAlgName() : string + +Obtains the signing algorithm of the X.509 CRL. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | -------------------------------- | +| string | Signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgName = x509Crl.getSignatureAlgName(); + } +}); +``` + +### getSignatureAlgOid + +getSignatureAlgOid() : string + +Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO). + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | --------------------------------------------- | +| string | OID of the X.509 CRL signing algorithm obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgOid = x509Crl.getSignatureAlgOid(); + } +}); +``` + +### getSignatureAlgParams + +getSignatureAlgParams() : DataBlob + +Obtains the parameters of the X.509 CRL signing algorithm. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------- | +| [DataBlob](#datablob) | Algorithm parameters obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Binary data of the CRL, which must be set based on the service. +let encodingData = null; +let encodingBlob = { + data: encodingData, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) { + if (error != null) { + console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("createX509Crl success"); + let sigAlgParams = x509Crl.getSignatureAlgParams(); + } +}); +``` + +## cryptoCert.createCertChainValidator + +createCertChainValidator(algorithm :string) : CertChainValidator + +Creates a **CertChainValidator** object. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------------------ | +| algorithm | string | Yes | Certificate chain validator algorithm. Currently, only **PKIX** is supported.| + +**Return value** + +| Type | Description | +| ------------------ | -------------------- | +| CertChainValidator | **CertChainValidator** object created.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +``` + +## CertChainValidator + +Provides APIs for certificate chain validator operations. + + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------- | +| algorithm | string | Yes | No | Algorithm used by the X509 certificate chain validator.| + + +### validate + +validate(certChain : CertChainData, callback : AsyncCallback\) : void + +Validates the X.509 certificate chain. This API uses an asynchronous callback to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the X.509 certificate chain is valid. If **error** is not **null**, the X.509 certificate chain is not valid.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData, function (error, data) { + if (error != null) { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("validate success"); + } +}); +``` + +### validate + +validate(certChain : CertChainData) : Promise\ + +Validates the X.509 certificate chain. This API uses a promise to return the result. +The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications). + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------- | ---- | -------------------------- | +| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data.| + +**Return value** + +| Type | Description | +| -------------- | ----------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +// Certificate chain binary data, which must be set based on the service. +let encodingData = null; +// Number of certificates in the certificate chain. It must be set based on the service. +let certCount = 2; +let certChainData = { + data: encodingData, + count: certCount, + // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER. + encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM +}; +validator.validate(certChainData).then(result => { + console.log("validate success"); +}, error => { + console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### algorithm + +algorithm : string + +Obtains the algorithm of the X.509 certificate chain validator. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------------ | +| string | Algorithm of the X.509 certificate chain validator obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +let validator = cryptoCert.createCertChainValidator("PKIX"); +let algorithm = validator.algorithm; +``` + +## X509CrlEntry + +Provides APIs for operating the revoked certificates. + +### getEncoded + +getEncoded(callback : AsyncCallback\) : void + +Obtains the serialized data of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------- | ---- | ------------------------------------ | +| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized data of the revoked certificate obtained.| + + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded(function (error, data) { + if (error != null) { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); + } else { + console.log("getEncoded success"); + } +}); +``` + +### getEncoded + +getEncoded() : Promise\ + +Obtains the serialized data of this revoked certificate. This API uses a promise to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------------------------- | -------------------------- | +| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized data of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +x509CrlEntry.getEncoded().then(result => { + console.log("getEncoded success"); +}, error => { + console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message); +}); +``` + +### getSerialNumber + +getSerialNumber() : number + +Obtains the serial number of this revoked certificate. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ---------------------- | +| number | Serial number of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +let serialNumber = x509CrlEntry.getSerialNumber(); +``` + +### getCertIssuer + +getCertIssuer() : DataBlob + +Obtains the issuer of this revoked certificate. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| --------------------- | ---------------------- - | +| [DataBlob](#datablob) | Promise used to return the issuer of the revoked certificate obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let issuer = x509CrlEntry.getCertIssuer(); +} catch (error) { + console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` + +### getRevocationDate + +getRevocationDate() : string + +Obtains the date when the certificate was revoked. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Security.Cert + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| string | Promise used to return the certificate revocation date obtained.| + +**Example** + +```js +import cryptoCert from '@ohos.security.cert'; + +// Obtain X509CrlEntry by using getRevokedCert() of X509Crl. +let x509CrlEntry = null; +try { + let date = x509CrlEntry.getRevocationDate(); +} catch (error) { + console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-colorSpaceManager.md b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md index 044fab3c6456d47e9a342b78770f10dc8f58c87d..706838181628f3e95cf2a35660d78e2f9389d73c 100644 --- a/en/application-dev/reference/apis/js-apis-colorSpaceManager.md +++ b/en/application-dev/reference/apis/js-apis-colorSpaceManager.md @@ -1,4 +1,4 @@ -# Color Space Management +# @ohos.graphics.colorSpaceManager (Color Space Management) The **colorSpaceManager** module provides APIs for creating and managing color space objects and obtaining basic color space attributes. diff --git a/en/application-dev/reference/apis/js-apis-commonEvent.md b/en/application-dev/reference/apis/js-apis-commonEvent.md index 5aaacbe7d104cf965d398240ff8e19468644713b..12fc260b45b0364ae5a4fc1218f45f6f2ed9df44 100644 --- a/en/application-dev/reference/apis/js-apis-commonEvent.md +++ b/en/application-dev/reference/apis/js-apis-commonEvent.md @@ -1,10 +1,10 @@ -# CommonEvent +# @ohos.commonEvent The **CommonEvent** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. > **NOTE** -> -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [@ohos.commonEventManager](js-apis-commonEventManager.md). +> - 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 @@ -14,7 +14,7 @@ import CommonEvent from '@ohos.commonEvent'; ## Support -Provides the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. +The table below lists the event types supported by the **CommonEvent** module. The name and value indicate the macro and name of a common event, respectively. **System capability**: SystemCapability.Notification.CommonEvent @@ -167,8 +167,8 @@ 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 | - | 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_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 been updated. | | 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. | @@ -192,7 +192,7 @@ Publishes a common event. This API uses an asynchronous callback to return the r ```js // Callback for common event publication -function PublishCallBack(err) { +function publishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -201,7 +201,7 @@ function PublishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", PublishCallBack); +CommonEvent.publish("event", publishCallBack); ``` @@ -234,7 +234,7 @@ let options = { } // Callback for common event publication -function PublishCallBack(err) { +function publishCallBack(err) { if (err.code) { console.error("publish failed " + JSON.stringify(err)); } else { @@ -243,7 +243,7 @@ function PublishCallBack(err) { } // Publish a common event. -CommonEvent.publish("event", options, PublishCallBack); +CommonEvent.publish("event", options, publishCallBack); ``` @@ -270,7 +270,7 @@ Publishes a common event to a specific user. This API uses an asynchronous callb ```js // Callback for common event publication -function PublishAsUserCallBack(err) { +function publishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -282,7 +282,7 @@ function PublishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, PublishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, publishAsUserCallBack); ``` @@ -317,7 +317,7 @@ let options = { } // Callback for common event publication -function PublishAsUserCallBack(err) { +function publishAsUserCallBack(err) { if (err.code) { console.error("publishAsUser failed " + JSON.stringify(err)); } else { @@ -329,7 +329,7 @@ function PublishAsUserCallBack(err) { let userId = 100; // Publish a common event. -CommonEvent.publishAsUser("event", userId, options, PublishAsUserCallBack); +CommonEvent.publishAsUser("event", userId, options, publishAsUserCallBack); ``` @@ -361,7 +361,7 @@ let subscribeInfo = { }; // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { @@ -371,7 +371,7 @@ function CreateSubscriberCallBack(err, commonEventSubscriber) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); ``` @@ -442,7 +442,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function SubscribeCallBack(err, data) { +function subscribeCallBack(err, data) { if (err.code) { console.error("subscribe failed " + JSON.stringify(err)); } else { @@ -451,19 +451,19 @@ function SubscribeCallBack(err, data) { } // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.error("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, SubscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCallBack); } } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); ``` @@ -494,7 +494,7 @@ let subscribeInfo = { }; // Callback for common event subscription. -function SubscribeCallBack(err, data) { +function subscribeCallBack(err, data) { if (err.code) { console.info("subscribe failed " + JSON.stringify(err)); } else { @@ -503,19 +503,19 @@ function SubscribeCallBack(err, data) { } // Callback for subscriber creation. -function CreateSubscriberCallBack(err, commonEventSubscriber) { +function createSubscriberCallBack(err, commonEventSubscriber) { if (err.code) { console.info("createSubscriber failed " + JSON.stringify(err)); } else { console.info("createSubscriber"); subscriber = commonEventSubscriber; // Subscribe to a common event. - CommonEvent.subscribe(subscriber, SubscribeCallBack); + CommonEvent.subscribe(subscriber, subscribeCallBack); } } // Callback for common event unsubscription. -function UnsubscribeCallBack(err) { +function unsubscribeCallBack(err) { if (err.code) { console.info("unsubscribe failed " + JSON.stringify(err)); } else { @@ -524,10 +524,10 @@ function UnsubscribeCallBack(err) { } // Create a subscriber. -CommonEvent.createSubscriber(subscribeInfo, CreateSubscriberCallBack); +CommonEvent.createSubscriber(subscribeInfo, createSubscriberCallBack); // Unsubscribe from the common event. -CommonEvent.unsubscribe(subscriber, UnsubscribeCallBack); +CommonEvent.unsubscribe(subscriber, unsubscribeCallBack); ``` ## CommonEventSubscriber @@ -1233,39 +1233,45 @@ subscriber.finishCommonEvent().then(() => { ## CommonEventData +Describes the common event data body. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| ---------- | ---- | ---- | -------------------- | ------------------------------------------------------- | -| event | Yes | No | string | Name of the common event that is being received. | -| bundleName | Yes | No | string | Bundle name. | -| code | Yes | No | number | Result code of the common event, which is used to transfer data of the int type. | -| data | Yes | No | string | Custom result data of the common event, which is used to transfer data of the string type.| -| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | +| Name | Type | Readable| Writable| Description | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | Yes | No | Name of the common event that is being received. | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | ## CommonEventPublishData +Describes the data body published by a common event, including the common event content and attributes. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| --------------------- | ---- | ---- | -------------------- | ---------------------------- | -| bundleName | Yes | No | string | Bundle name. | -| code | Yes | No | number | Result code of the common event. | -| data | Yes | No | string | Custom result data of the common event.| -| subscriberPermissions | Yes | No | Array\ | Permissions required for subscribers to receive the common event. | -| isOrdered | Yes | No | boolean | Whether the common event is an ordered one. | -| isSticky | Yes | No | boolean | Whether the common event is a sticky one. | -| parameters | Yes | No | {[key: string]: any} | Additional information about the common event. | +| Name | Type | Readable| Writable| Description | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event. | +| data | string | Yes | No | Custom result data of the common event.| +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | +| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | ## CommonEventSubscribeInfo +Provides the subscriber information. + **System capability**: SystemCapability.Notification.CommonEvent -| Name | Readable| Writable| Type | Description | -| ------------------- | ---- | ---- | -------------- | ------------------------------------------------------------ | -| events | Yes | No | Array\ | Name of the common event to publish. | -| publisherPermission | Yes | No | string | Permissions required for publishers to publish the common event. | -| publisherDeviceId | Yes | No | string | Device ID. The value must be the ID of an existing device on the same network. | -| userId | Yes | No | number | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| -| priority | Yes | No | number | Subscriber priority. The value ranges from -100 to 1000. | +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | Yes | No | Name of the common event to publish. | +| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-commonEventManager.md b/en/application-dev/reference/apis/js-apis-commonEventManager.md new file mode 100644 index 0000000000000000000000000000000000000000..502603da539a71e465fcfbffb8e69ba696d4e6ea --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-commonEventManager.md @@ -0,0 +1,1353 @@ +# @ohos.commonEventManager + +The **CommonEventManager** module provides common event capabilities, including the capabilities to publish, subscribe to, and unsubscribe from common events, as well obtaining and setting the common event result code and result data. + +> **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 + +```ts +import CommonEventManager from '@ohos.commonEventManager'; +``` + +## Support + +The table below lists the event types supported by the **CommonEventManager** module. The name and value indicate the macro and name of a common event, respectively. + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Value | Subscriber Permission | Description | +| ------------ | ------------------ | ---------------------- | -------------------- | +| COMMON_EVENT_BOOT_COMPLETED | usual.event.BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded. | +| COMMON_EVENT_LOCKED_BOOT_COMPLETED | usual.event.LOCKED_BOOT_COMPLETED | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the user has finished booting and the system has been loaded but the screen is still locked. | +| COMMON_EVENT_SHUTDOWN | usual.event.SHUTDOWN | - | Indicates the common event that the device is being shut down and the final shutdown will proceed. | +| COMMON_EVENT_BATTERY_CHANGED | usual.event.BATTERY_CHANGED | - | Indicates the common event that the charging state, level, and other information about the battery have changed. | +| COMMON_EVENT_BATTERY_LOW | usual.event.BATTERY_LOW | - | Indicates the common event that the battery level is low. | +| COMMON_EVENT_BATTERY_OKAY | usual.event.BATTERY_OKAY | - | Indicates the common event that the battery exits the low state. | +| COMMON_EVENT_POWER_CONNECTED | usual.event.POWER_CONNECTED | - | Indicates the common event that the device is connected to an external power supply. | +| COMMON_EVENT_POWER_DISCONNECTED | usual.event.POWER_DISCONNECTED | - | Indicates the common event that the device is disconnected from the external power supply. | +| COMMON_EVENT_SCREEN_OFF | usual.event.SCREEN_OFF | - | Indicates the common event that the device screen is off and the device is sleeping. | +| COMMON_EVENT_SCREEN_ON | usual.event.SCREEN_ON | - | Indicates the common event that the device screen is on and the device is in interactive state. | +| COMMON_EVENT_THERMAL_LEVEL_CHANGED | usual.event.THERMAL_LEVEL_CHANGED | - | Indicates the common event that the device's thermal level has changed. | +| COMMON_EVENT_USER_PRESENT | usual.event.USER_PRESENT | - | Indicates the common event that the user unlocks the device. | +| COMMON_EVENT_TIME_TICK | usual.event.TIME_TICK | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIME_CHANGED | usual.event.TIME_CHANGED | - | Indicates the common event that the system time is set. | +| COMMON_EVENT_DATE_CHANGED | usual.event.DATE_CHANGED | - | Indicates the common event that the system time has changed. | +| COMMON_EVENT_TIMEZONE_CHANGED | usual.event.TIMEZONE_CHANGED | - | Indicates the common event that the system time zone has changed. | +| COMMON_EVENT_CLOSE_SYSTEM_DIALOGS | usual.event.CLOSE_SYSTEM_DIALOGS | - | Indicates the common event that a user closes a temporary system dialog box. | +| COMMON_EVENT_PACKAGE_ADDED | usual.event.PACKAGE_ADDED | - | Indicates the common event that a new application package has been installed on the device. | +| COMMON_EVENT_PACKAGE_REPLACED | usual.event.PACKAGE_REPLACED | - | Indicates the common event that a later version of an installed application package has replaced the previous one on the device. | +| COMMON_EVENT_MY_PACKAGE_REPLACED | usual.event.MY_PACKAGE_REPLACED | - | Indicates the common event that a later version of your application package has replaced the previous one. +| COMMON_EVENT_PACKAGE_REMOVED | usual.event.PACKAGE_REMOVED | - | Indicates the common event that an installed application has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_BUNDLE_REMOVED | usual.event.BUNDLE_REMOVED | - | Indicates the common event that an installed bundle has been uninstalled from the device with the application data retained. | +| COMMON_EVENT_PACKAGE_FULLY_REMOVED | usual.event.PACKAGE_FULLY_REMOVED | - | Indicates the common event that an installed application, including both the application data and code, has been completely uninstalled from the device. | +| COMMON_EVENT_PACKAGE_CHANGED | usual.event.PACKAGE_CHANGED | - | Indicates the common event that an application package has been changed (for example, a component in the package has been enabled or disabled). | +| COMMON_EVENT_PACKAGE_RESTARTED | usual.event.PACKAGE_RESTARTED | - | Indicates the common event that the user has restarted the application package and killed all its processes. | +| COMMON_EVENT_PACKAGE_DATA_CLEARED | usual.event.PACKAGE_DATA_CLEARED | - | Indicates the common event that the user has cleared the application package data. | +| COMMON_EVENT_PACKAGE_CACHE_CLEARED9+ | usual.event.PACKAGE_CACHE_CLEARED | - | Indicates the common event that the user has cleared the application package data. | +| COMMON_EVENT_PACKAGES_SUSPENDED | usual.event.PACKAGES_SUSPENDED | - | Indicates the common event that application packages have been suspended. | +| COMMON_EVENT_PACKAGES_UNSUSPENDED | usual.event.PACKAGES_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | +| COMMON_EVENT_MY_PACKAGE_SUSPENDED | usual.event.MY_PACKAGE_SUSPENDED | - | Indicates the common event that an application package has been suspended. | +| COMMON_EVENT_MY_PACKAGE_UNSUSPENDED | usual.event.MY_PACKAGE_UNSUSPENDED | - | Indicates the common event that application package has not been suspended. | +| COMMON_EVENT_UID_REMOVED | usual.event.UID_REMOVED | - | Indicates the common event that a user ID has been removed from the system. | +| COMMON_EVENT_PACKAGE_FIRST_LAUNCH | usual.event.PACKAGE_FIRST_LAUNCH | - | Indicates the common event that an installed application is started for the first time. | +| COMMON_EVENT_PACKAGE_NEEDS_VERIFICATION | usual.event.PACKAGE_NEEDS_VERIFICATION | - | Indicates the common event that an application requires system verification. | +| COMMON_EVENT_PACKAGE_VERIFIED | usual.event.PACKAGE_VERIFIED | - | Indicates the common event that an application has been verified by the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_AVAILABLE | usual.event.EXTERNAL_APPLICATIONS_AVAILABLE | - | Indicates the common event that applications installed on the external storage become available for the system. | +| COMMON_EVENT_EXTERNAL_APPLICATIONS_UNAVAILABLE | usual.event.EXTERNAL_APPLICATIONS_UNAVAILABLE | - | Indicates the common event that applications installed on the external storage become unavailable for the system. | +| COMMON_EVENT_CONFIGURATION_CHANGED | usual.event.CONFIGURATION_CHANGED | - | Indicates the common event that the device state (for example, orientation and locale) has changed. | +| COMMON_EVENT_LOCALE_CHANGED | usual.event.LOCALE_CHANGED | - | Indicates the common event that the device locale has changed. | +| COMMON_EVENT_MANAGE_PACKAGE_STORAGE | usual.event.MANAGE_PACKAGE_STORAGE | - | Indicates the common event that the device storage is insufficient. | +| COMMON_EVENT_DRIVE_MODE | common.event.DRIVE_MODE | - | Indicates the common event that the system is in driving mode. | +| COMMON_EVENT_HOME_MODE | common.event.HOME_MODE | - | Indicates the common event that the system is in home mode. | +| COMMON_EVENT_OFFICE_MODE | common.event.OFFICE_MODE | - | Indicates the common event that the system is in office mode. | +| COMMON_EVENT_USER_STARTED | usual.event.USER_STARTED | - | Indicates the common event that the user has been started. | +| COMMON_EVENT_USER_BACKGROUND | usual.event.USER_BACKGROUND | - | Indicates the common event that the user has been brought to the background. | +| COMMON_EVENT_USER_FOREGROUND | usual.event.USER_FOREGROUND | - | Indicates the common event that the user has been brought to the foreground. | +| COMMON_EVENT_USER_SWITCHED | usual.event.USER_SWITCHED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that user switching is happening. | +| COMMON_EVENT_USER_STARTING | usual.event.USER_STARTING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be started. | +| COMMON_EVENT_USER_UNLOCKED | usual.event.USER_UNLOCKED | - | Indicates the common event that the credential-encrypted storage has been unlocked for the current user when the device is unlocked after being restarted. | +| COMMON_EVENT_USER_STOPPING | usual.event.USER_STOPPING | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the user is going to be stopped. | +| COMMON_EVENT_USER_STOPPED | usual.event.USER_STOPPED | - | Indicates the common event that the user has been stopped. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGIN | usual.event.DISTRIBUTED_ACCOUNT_LOGIN | - | Indicates the action of successful login using a distributed account. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOUT | usual.event.DISTRIBUTED_ACCOUNT_LOGOUT | - | Indicates the action of successful logout of a distributed account. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_TOKEN_INVALID | usual.event.DISTRIBUTED_ACCOUNT_TOKEN_INVALID | - | Indicates the action when the token of a distributed account is invalid. | +| COMMON_EVENT_DISTRIBUTED_ACCOUNT_LOGOFF | usual.event.DISTRIBUTED_ACCOUNT_LOGOFF | - | Indicates the action of deregistering a distributed account. | +| COMMON_EVENT_WIFI_POWER_STATE | usual.event.wifi.POWER_STATE | - | Indicates the common event about the Wi-Fi network state, such as enabled and disabled. | +| COMMON_EVENT_WIFI_SCAN_FINISHED | usual.event.wifi.SCAN_FINISHED | ohos.permission.LOCATION | Indicates the common event that the Wi-Fi access point has been scanned and proven to be available. | +| COMMON_EVENT_WIFI_RSSI_VALUE | usual.event.wifi.RSSI_VALUE | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi signal strength (RSSI) has changed. | +| COMMON_EVENT_WIFI_CONN_STATE | usual.event.wifi.CONN_STATE | - | Indicates the common event that the Wi-Fi connection state has changed. | +| COMMON_EVENT_WIFI_HOTSPOT_STATE | usual.event.wifi.HOTSPOT_STATE | - | Indicates the common event about the Wi-Fi hotspot state, such as enabled or disabled. | +| COMMON_EVENT_WIFI_AP_STA_JOIN | usual.event.wifi.WIFI_HS_STA_JOIN | ohos.permission.GET_WIFI_INFO | Indicates the common event that a client has joined the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_AP_STA_LEAVE | usual.event.wifi.WIFI_HS_STA_LEAVE | ohos.permission.GET_WIFI_INFO |Indicates the common event that a client has disconnected from the Wi-Fi hotspot of the current device. | +| COMMON_EVENT_WIFI_MPLINK_STATE_CHANGE | usual.event.wifi.mplink.STATE_CHANGE | ohos.permission.MPLINK_CHANGE_STATE | Indicates the common event that the state of MPLINK (an enhanced Wi-Fi feature) has changed. | +| COMMON_EVENT_WIFI_P2P_CONN_STATE | usual.event.wifi.p2p.CONN_STATE_CHANGE | ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION | Indicates the common event that the Wi-Fi P2P connection state has changed. | +| COMMON_EVENT_WIFI_P2P_STATE_CHANGED | usual.event.wifi.p2p.STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P state, such as enabled and disabled. | +| COMMON_EVENT_WIFI_P2P_PEERS_STATE_CHANGED | usual.event.wifi.p2p.DEVICES_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of Wi-Fi P2P peer devices. | +| COMMON_EVENT_WIFI_P2P_PEERS_DISCOVERY_STATE_CHANGED | usual.event.wifi.p2p.PEER_DISCOVERY_STATE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the Wi-Fi P2P discovery status change. | +| COMMON_EVENT_WIFI_P2P_CURRENT_DEVICE_STATE_CHANGED | usual.event.wifi.p2p.CURRENT_DEVICE_CHANGE | ohos.permission.GET_WIFI_INFO | Indicates the common event about the status change of the Wi-Fi P2P local device. | +| COMMON_EVENT_WIFI_P2P_GROUP_STATE_CHANGED | usual.event.wifi.p2p.GROUP_STATE_CHANGED | ohos.permission.GET_WIFI_INFO | Indicates the common event that the Wi-Fi P2P group information has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth handsfree communication. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.handsfree.ag.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected to the Bluetooth handsfree is active. | +| COMMON_EVENT_BLUETOOTH_HANDSFREE_AG_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfree.ag.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the connection state of Bluetooth A2DP. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CURRENT_DEVICE_UPDATE | usual.event.bluetooth.a2dpsource.CURRENT_DEVICE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the device connected using Bluetooth A2DP is active. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsource.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_AVRCP_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsource.AVRCP_CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the AVRCP connection state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSOURCE_CODEC_VALUE_UPDATE | usual.event.bluetooth.a2dpsource.CODEC_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio codec state of Bluetooth A2DP has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_DISCOVERED | usual.event.bluetooth.remotedevice.DISCOVERED | ohos.permission.LOCATION and ohos.permission.USE_BLUETOOTH | Indicates the common event that a remote Bluetooth device is discovered. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CLASS_VALUE_UPDATE | usual.event.bluetooth.remotedevice.CLASS_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth class of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_CONNECTED | usual.event.bluetooth.remotedevice.ACL_CONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been established with a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_ACL_DISCONNECTED | usual.event.bluetooth.remotedevice.ACL_DISCONNECTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that a low-ACL connection has been disconnected from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_NAME_UPDATE | usual.event.bluetooth.remotedevice.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the friendly name of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIR_STATE | usual.event.bluetooth.remotedevice.PAIR_STATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of a remote Bluetooth device has changed. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_BATTERY_VALUE_UPDATE | usual.event.bluetooth.remotedevice.BATTERY_VALUE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the battery level of a remote Bluetooth device is retrieved for the first time or is changed since the last retrieval. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_SDP_RESULT | usual.event.bluetooth.remotedevice.SDP_RESULT | - | Indicates the common event about the SDP state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_UUID_VALUE | usual.event.bluetooth.remotedevice.UUID_VALUE | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the UUID connection state of a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_REQ | usual.event.bluetooth.remotedevice.PAIRING_REQ | ohos.permission.DISCOVER_BLUETOOTH | Indicates the common event about the pairing request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_PAIRING_CANCEL | usual.event.bluetooth.remotedevice.PAIRING_CANCEL | - | Indicates the common event that Bluetooth pairing is canceled. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REQ | usual.event.bluetooth.remotedevice.CONNECT_REQ | - | Indicates the common event about the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_REPLY | usual.event.bluetooth.remotedevice.CONNECT_REPLY | - | Indicates the common event about the response to the connection request from a remote Bluetooth device. | +| COMMON_EVENT_BLUETOOTH_REMOTEDEVICE_CONNECT_CANCEL | usual.event.bluetooth.remotedevice.CONNECT_CANCEL | - | Indicates the common event that the connection to a remote Bluetooth device has been canceled. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_CONNECT_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.CONNECT_STATE_UPDATE | - | Indicates the common event that the connection state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AUDIO_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AUDIO_STATE_UPDATE | - | Indicates the common event that the audio state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_COMMON_EVENT | usual.event.bluetooth.handsfreeunit.AG_COMMON_EVENT | - | Indicates the common event that the audio gateway state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HANDSFREEUNIT_AG_CALL_STATE_UPDATE | usual.event.bluetooth.handsfreeunit.AG_CALL_STATE_UPDATE | - | Indicates the common event that the calling state of a Bluetooth handsfree has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_STATE_UPDATE | usual.event.bluetooth.host.STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the state of a Bluetooth adapter has been changed, for example, Bluetooth has been enabled or disabled. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISCOVERABLE | usual.event.bluetooth.host.REQ_DISCOVERABLE | - | Indicates the common event about the request for the user to allow Bluetooth device scanning. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_ENABLE | usual.event.bluetooth.host.REQ_ENABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to enable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_REQ_DISABLE | usual.event.bluetooth.host.REQ_DISABLE | ohos.permission.USE_BLUETOOTH | Indicates the common event about the request for the user to disable Bluetooth. | +| COMMON_EVENT_BLUETOOTH_HOST_SCAN_MODE_UPDATE | usual.event.bluetooth.host.SCAN_MODE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning mode of a device has changed. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_STARTED | usual.event.bluetooth.host.DISCOVERY_STARTED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning has been started on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_DISCOVERY_FINISHED | usual.event.bluetooth.host.DISCOVERY_FINISHED | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth scanning is finished on the device. | +| COMMON_EVENT_BLUETOOTH_HOST_NAME_UPDATE | usual.event.bluetooth.host.NAME_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the Bluetooth adapter name of the device has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_CONNECT_STATE_UPDATE | usual.event.bluetooth.a2dpsink.CONNECT_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the connection state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_PLAYING_STATE_UPDATE | usual.event.bluetooth.a2dpsink.PLAYING_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the playing state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_BLUETOOTH_A2DPSINK_AUDIO_STATE_UPDATE | usual.event.bluetooth.a2dpsink.AUDIO_STATE_UPDATE | ohos.permission.USE_BLUETOOTH | Indicates the common event that the audio state of Bluetooth A2DP Sink has changed. | +| COMMON_EVENT_NFC_ACTION_ADAPTER_STATE_CHANGED | usual.event.nfc.action.ADAPTER_STATE_CHANGED | - | Indicates the common event that the state of the device's NFC adapter has changed. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_ON_DETECTED | usual.event.nfc.action.RF_FIELD_ON_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the action of a common event that the NFC RF field is detected to be in the enabled state. | +| COMMON_EVENT_NFC_ACTION_RF_FIELD_OFF_DETECTED | usual.event.nfc.action.RF_FIELD_OFF_DETECTED | ohos.permission.MANAGE_SECURE_SETTINGS | Indicates the common event that the NFC RF field is detected to be in the disabled state. | +| COMMON_EVENT_DISCHARGING | usual.event.DISCHARGING | - | Indicates the common event that the system stops charging the battery. | +| COMMON_EVENT_CHARGING | usual.event.CHARGING | - | Indicates the common event that the system starts charging the battery. | +| COMMON_EVENT_DEVICE_IDLE_MODE_CHANGED | usual.event.DEVICE_IDLE_MODE_CHANGED | - | Indicates the common event that the system idle mode has changed. | +| COMMON_EVENT_POWER_SAVE_MODE_CHANGED | usual.event.POWER_SAVE_MODE_CHANGED | - | Indicates the common event that the power saving mode of the system has changed. | +| COMMON_EVENT_USER_ADDED | usual.event.USER_ADDED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been added to the system. | +| COMMON_EVENT_USER_REMOVED | usual.event.USER_REMOVED | ohos.permission.MANAGE_LOCAL_ACCOUNTS | Indicates the common event that a user has been removed from the system. | +| COMMON_EVENT_ABILITY_ADDED | usual.event.ABILITY_ADDED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been added. | +| COMMON_EVENT_ABILITY_REMOVED | usual.event.ABILITY_REMOVED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been removed. | +| COMMON_EVENT_ABILITY_UPDATED | usual.event.ABILITY_UPDATED | ohos.permission.LISTEN_BUNDLE_CHANGE | Indicates the common event that an ability has been updated. | +| COMMON_EVENT_LOCATION_MODE_STATE_CHANGED | usual.event.location.MODE_STATE_CHANGED | - | Indicates the common event that the location mode of the system has changed. | +| COMMON_EVENT_IVI_SLEEP | common.event.IVI_SLEEP | - | Indicates the common event that the in-vehicle infotainment (IVI) system of a vehicle is sleeping. | +| COMMON_EVENT_IVI_PAUSE | common.event.IVI_PAUSE | - | Indicates the common event that the IVI system of a vehicle has entered sleep mode and the playing application is instructed to stop playback. | +| COMMON_EVENT_IVI_STANDBY | common.event.IVI_STANDBY | - | Indicates the common event that a third-party application is instructed to pause the current work. | +| COMMON_EVENT_IVI_LASTMODE_SAVE | common.event.IVI_LASTMODE_SAVE | - | Indicates the common event that a third-party application is instructed to save its last mode. | +| COMMON_EVENT_IVI_VOLTAGE_ABNORMAL | common.event.IVI_VOLTAGE_ABNORMAL | - | Indicates the common event that the voltage of the vehicle's power system is abnormal. | +| COMMON_EVENT_IVI_HIGH_TEMPERATURE | common.event.IVI_HIGH_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is high. | +| COMMON_EVENT_IVI_EXTREME_TEMPERATURE | common.event.IVI_EXTREME_TEMPERATURE | - | Indicates the common event that the temperature of the IVI system is extremely high. | +| COMMON_EVENT_IVI_TEMPERATURE_ABNORMAL | common.event.IVI_TEMPERATURE_ABNORMAL | - | Indicates the common event that the IVI system has an extreme temperature. | +| COMMON_EVENT_IVI_VOLTAGE_RECOVERY | common.event.IVI_VOLTAGE_RECOVERY | - | Indicates the common event that the voltage of the vehicle's power system is restored to normal. | +| COMMON_EVENT_IVI_TEMPERATURE_RECOVERY | common.event.IVI_TEMPERATURE_RECOVERY | - | Indicates the common event that the temperature of the IVI system is restored to normal. | +| COMMON_EVENT_IVI_ACTIVE | common.event.IVI_ACTIVE | - | Indicates the common event that the battery service is active. | +|COMMON_EVENT_USB_STATE9+ | usual.event.hardware.usb.action.USB_STATE | - | Indicates a common event indicating that the USB device status changes. | +|COMMON_EVENT_USB_PORT_CHANGED9+ | usual.event.hardware.usb.action.USB_PORT_CHANGED | - | Indicates the public event that the USB port status of the user device changes. | +| COMMON_EVENT_USB_DEVICE_ATTACHED | usual.event.hardware.usb.action.USB_DEVICE_ATTACHED | - | Indicates the common event that a USB device has been attached when the user device functions as a USB host. | +| COMMON_EVENT_USB_DEVICE_DETACHED | usual.event.hardware.usb.action.USB_DEVICE_DETACHED | - | Indicates the common event that a USB device has been detached when the user device functions as a USB host. | +| COMMON_EVENT_USB_ACCESSORY_ATTACHED | usual.event.hardware.usb.action.USB_ACCESSORY_ATTACHED | - | Indicates the common event that a USB accessory was attached. | +| COMMON_EVENT_USB_ACCESSORY_DETACHED | usual.event.hardware.usb.action.USB_ACCESSORY_DETACHED | - | Indicates the common event that a USB accessory was detached. | +| COMMON_EVENT_DISK_REMOVED | usual.event.data.DISK_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_DISK_UNMOUNTED | usual.event.data.DISK_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_DISK_MOUNTED | usual.event.data.DISK_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_DISK_BAD_REMOVAL | usual.event.data.DISK_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_DISK_UNMOUNTABLE | usual.event.data.DISK_UNMOUNTABLE | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device becomes unmountable. | +| COMMON_EVENT_DISK_EJECT | usual.event.data.DISK_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VOLUME_REMOVED9+ | usual.event.data.VOLUME_REMOVED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed. | +| COMMON_EVENT_VOLUME_UNMOUNTED9+ | usual.event.data.VOLUME_UNMOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was unmounted. | +| COMMON_EVENT_VOLUME_MOUNTED9+ | usual.event.data.VOLUME_MOUNTED | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was mounted. | +| COMMON_EVENT_VOLUME_BAD_REMOVAL9+ | usual.event.data.VOLUME_BAD_REMOVAL | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was removed without being unmounted. | +| COMMON_EVENT_VOLUME_EJECT9+ | usual.event.data.VOLUME_EJECT | ohos.permission.STORAGE_MANAGER | Indicates the common event that an external storage device was ejected. | +| COMMON_EVENT_VISIBLE_ACCOUNTS_UPDATED | usual.event.data.VISIBLE_ACCOUNTS_UPDATED | ohos.permission.GET_APP_ACCOUNTS | Indicates the common event that the account visibility changed. | +| COMMON_EVENT_ACCOUNT_DELETED | usual.event.data.ACCOUNT_DELETED | ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS | Indicates the common event that the account was deleted. | +| COMMON_EVENT_FOUNDATION_READY | usual.event.data.FOUNDATION_READY | ohos.permission.RECEIVER_STARTUP_COMPLETED | Indicates the common event that the foundation is ready. | +| COMMON_EVENT_AIRPLANE_MODE_CHANGED | usual.event.AIRPLANE_MODE | - | Indicates the common event that the airplane mode of the device has changed. | +| COMMON_EVENT_SPLIT_SCREEN | usual.event.SPLIT_SCREEN | ohos.permission.RECEIVER_SPLIT_SCREEN | Indicates the common event of screen splitting. | +| COMMON_EVENT_SLOT_CHANGE9+ | usual.event.SLOT_CHANGE | ohos.permission.NOTIFICATION_CONTROLLER | Indicates the common event that the notification slot has been updated. | +| 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. | + + +## CommonEventManager.publish + +publish(event: string, callback: AsyncCallback\): void + +Publishes a common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Event Error Codes](../errorcodes/errorcode-CommonEventService.md). + +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + +```ts +// Callback for common event publication +function publishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +// Publish a common event. +try { + CommonEventManager.publish("event", publishCallBack); +} catch(err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + +## CommonEventManager.publish + +publish(event: string, options: CommonEventPublishData, callback: AsyncCallback\): void + +Publishes a common event with given attributes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | syncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + + +**Example** + + +```ts +// Attributes of a common event. +var options = { + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. + isOrdered: true // The common event is an ordered one. +} + +// Callback for common event publication +function publishCallBack(err) { + if (err) { + console.error("publish failed " + JSON.stringify(err)); + } else { + console.info("publish"); + } +} + +// Publish a common event. +try { + CommonEventManager.publish("event", options, publishCallBack); +} catch (err) { + console.error('publish failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, callback: AsyncCallback\): void + +Publishes a common event to a specific user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes | User ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + +```ts +// Callback for common event publication +function publishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +// Specify the user to whom the common event will be published. +var userId = 100; + +// Publish a common event. +try { + CommonEventManager.publishAsUser("event", userId, publishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.publishAsUser + +publishAsUser(event: string, userId: number, options: CommonEventPublishData, callback: AsyncCallback\): void + +Publishes a common event with given attributes to a specific user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| event | string | Yes | Name of the common event to publish. | +| userId | number | Yes| User ID.| +| options | [CommonEventPublishData](#commoneventpublishdata) | Yes | Attributes of the common event to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** +|ID |Error Message | +|-----------|--------------------| +|1500004 |not System services or System app| +|1500007 |message send error| +|1500008 |CEMS error| +|1500009 |system error| + +**Example** + + +```ts +// Attributes of a common event. +var options = { + code: 0, // Result code of the common event. + data: "initial data";// Result data of the common event. +} + +// Callback for common event publication +function publishAsUserCallBack(err) { + if (err) { + console.error("publishAsUser failed " + JSON.stringify(err)); + } else { + console.info("publishAsUser"); + } +} + +// Specify the user to whom the common event will be published. +var userId = 100; + +// Publish a common event. +try { + CommonEventManager.publishAsUser("event", userId, options, publishAsUserCallBack); +} catch (err) { + console.error('publishAsUser failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback\): void + +Creates a subscriber. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ------------------------------------------------------------ | ---- | -------------------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information. | +| callback | AsyncCallback\<[CommonEventSubscriber](#commoneventsubscriber)> | Yes | Callback used to return the result.| + +**Example** + + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.createSubscriber + +createSubscriber(subscribeInfo: CommonEventSubscribeInfo): Promise\ + +Creates a subscriber. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | ----------------------------------------------------- | ---- | -------------- | +| subscribeInfo | [CommonEventSubscribeInfo](#commoneventsubscribeinfo) | Yes | Subscriber information.| + +**Return value** +| Type | Description | +| --------------------------------------------------------- | ---------------- | +| Promise\<[CommonEventSubscriber](#commoneventsubscriber)> | Promise used to return the subscriber object.| + +**Example** + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo).then((commonEventSubscriber) => { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; +}).catch((err) => { + console.error("createSubscriber failed " + JSON.stringify(err)); +}); +} catch(err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} + +``` + + + +## CommonEventManager.subscribe + +subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback\): void + +Subscribes to common events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------------------------------------- | ---- | -------------------------------- | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\<[CommonEventData](#commoneventdata)> | Yes | Callback used to return the result.| + +**Example** + +```ts +// Subscriber information. +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. + +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; + +// Callback for common event subscription. +function SubscribeCallBack(err, data) { + if (err.code) { + console.error("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe "); + } +} + +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if(!err) { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + // Subscribe to a common event. + try { + CommonEventManager.subscribe(subscriber, SubscribeCallBack); + } catch (err) { + console.error("createSubscriber failed " + JSON.stringify(err)); + } + } else { + console.error("createSubscriber failed " + JSON.stringify(err)); + } +} + +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.error('createSubscriber failed, catch error' + JSON.stringify(err)); +} +``` + + + +## CommonEventManager.unsubscribe + +unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback\): void + +Unsubscribes from common events. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ----------------------------------------------- | ---- | ------------------------ | +| subscriber | [CommonEventSubscriber](#commoneventsubscriber) | Yes | Subscriber object. | +| callback | AsyncCallback\ | No | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Used to save the created subscriber object for subsequent subscription and unsubscription. +// Subscriber information. +var subscribeInfo = { + events: ["event"] +}; +// Callback for common event subscription. +function subscribeCallBack(err, data) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe"); + } +} +// Callback for subscriber creation. +function createSubscriberCallBack(err, commonEventSubscriber) { + if (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); + } else { + console.info("createSubscriber"); + subscriber = commonEventSubscriber; + // Subscribe to a common event. + try { + CommonEventManager.subscribe(subscriber, subscribeCallBack); + } catch(err) { + console.info("subscribe failed " + JSON.stringify(err)); + } + } +} +// Callback for common event unsubscription. +function unsubscribeCallBack(err) { + if (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe"); + } +} +// Create a subscriber. +try { + CommonEventManager.createSubscriber(subscribeInfo, createSubscriberCallBack); +} catch (err) { + console.info("createSubscriber failed " + JSON.stringify(err)); +} + +// Unsubscribe from the common event. +try { + CommonEventManager.unsubscribe(subscriber, unsubscribeCallBack); +} catch (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); +} +``` + +## CommonEventSubscriber + +### getCode + +getCode(callback: AsyncCallback\): void + +Obtains the result code of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code obtaining of an ordered common event. +function getCodeCallback(err, Code) { + if (err.code) { + console.error("getCode failed " + JSON.stringify(err)); + } else { + console.info("getCode " + JSON.stringify(Code)); + } +} +subscriber.getCode(getCodeCallback); +``` + +### getCode + +getCode(): Promise\ + +Obtains the result code of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getCode().then((Code) => { + console.info("getCode " + JSON.stringify(Code)); +}).catch((err) => { + console.error("getCode failed " + JSON.stringify(err)); +}); +``` + +### setCode + +setCode(code: number, callback: AsyncCallback\): void + +Sets the result code for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Result code of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code setting of an ordered common event. +function setCodeCallback(err) { + if (err.code) { + console.error("setCode failed " + JSON.stringify(err)); + } else { + console.info("setCode"); + } +} +subscriber.setCode(1, setCodeCallback); +``` + +### setCode + +setCode(code: number): Promise\ + +Sets the result code for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| code | number | Yes | Result code of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setCode(1).then(() => { + console.info("setCode"); +}).catch((err) => { + console.error("setCode failed " + JSON.stringify(err)); +}); +``` + +### getData + +getData(callback: AsyncCallback\): void + +Obtains the result data of this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result data.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result data obtaining of an ordered common event. +function getDataCallback(err, Data) { + if (err.code) { + console.error("getData failed " + JSON.stringify(err)); + } else { + console.info("getData " + JSON.stringify(Data)); + } +} +subscriber.getData(getDataCallback); +``` + +### getData + +getData(): Promise\ + +Obtains the result data of this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | ------------------ | +| Promise\ | Promise used to return the result data.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getData().then((Data) => { + console.info("getData " + JSON.stringify(Data)); +}).catch((err) => { + console.error("getData failed " + JSON.stringify(err)); +}); +``` + +### setData + +setData(data: string, callback: AsyncCallback\): void + +Sets the result data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| data | string | Yes | Result data of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result data setting of an ordered common event +function setDataCallback(err) { + if (err.code) { + console.error("setData failed " + JSON.stringify(err)); + } else { + console.info("setData"); + } +} +subscriber.setData("publish_data_changed", setDataCallback); +``` + +### setData + +setData(data: string): Promise\ + +Sets the result data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setData("publish_data_changed").then(() => { + console.info("setData"); +}).catch((err) => { + console.error("setData failed " + JSON.stringify(err)); +}); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string, callback:AsyncCallback\): void + +Sets the result code and result data for this common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------- | +| code | number | Yes | Result code of the common event. | +| data | string | Yes | Result data of the common event. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for result code and result data setting of an ordered common event. +function setCodeDataCallback(err) { + if (err.code) { + console.error("setCodeAndData failed " + JSON.stringify(err)); + } else { + console.info("setCodeDataCallback"); + } +} +subscriber.setCodeAndData(1, "publish_data_changed", setCodeDataCallback); +``` + +### setCodeAndData + +setCodeAndData(code: number, data: string): Promise\ + +Sets the result code and result data for this common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| code | number | Yes | Result code of the common event.| +| data | string | Yes | Result data of the common event.| + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.setCodeAndData(1, "publish_data_changed").then(() => { + console.info("setCodeAndData"); +}).catch((err) => { + console.info("setCodeAndData failed " + JSON.stringify(err)); +}); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is an ordered one. This API uses an asynchronous callback to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is an ordered one. +function isOrderedCallback(err, isOrdered) { + if (err.code) { + console.error("isOrderedCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isOrdered " + JSON.stringify(isOrdered)); + } +} +subscriber.isOrderedCommonEvent(isOrderedCallback); +``` + +### isOrderedCommonEvent + +isOrderedCommonEvent(): Promise\ + +Checks whether this common event is an ordered one. This API uses a promise to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the common event is an ordered one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.isOrderedCommonEvent().then((isOrdered) => { + console.info("isOrdered " + JSON.stringify(isOrdered)); +}).catch((err) => { + console.error("isOrdered failed " + JSON.stringify(err)); +}); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is a sticky one. This API uses an asynchronous callback to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is a sticky one. +function isStickyCallback(err, isSticky) { + if (err.code) { + console.error("isStickyCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("isSticky " + JSON.stringify(isSticky)); + } +} +subscriber.isStickyCommonEvent(isStickyCallback); +``` + +### isStickyCommonEvent + +isStickyCommonEvent(): Promise\ + +Checks whether this common event is a sticky one. This API uses a promise to return the result. + + + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the common event is a sticky one; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.isStickyCommonEvent().then((isSticky) => { + console.info("isSticky " + JSON.stringify(isSticky)); +}).catch((err) => { + console.error("isSticky failed " + JSON.stringify(err)); +}); +``` + +### abortCommonEvent + +abortCommonEvent(callback: AsyncCallback\): void + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for common event aborting. +function abortCallback(err) { + if (err.code) { + console.error("abortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("abortCommonEvent"); + } +} +subscriber.abortCommonEvent(abortCallback); +``` + +### abortCommonEvent + +abortCommonEvent(): Promise\ + +Aborts this common event. After the abort, the common event is not sent to the next subscriber. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.abortCommonEvent().then(() => { + console.info("abortCommonEvent"); +}).catch((err) => { + console.error("abortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(callback: AsyncCallback\): void + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for clearing the aborted state of the current common event. +function clearAbortCallback(err) { + if (err.code) { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("clearAbortCommonEvent"); + } +} +subscriber.clearAbortCommonEvent(clearAbortCallback); +``` + +### clearAbortCommonEvent + +clearAbortCommonEvent(): Promise\ + +Clears the aborted state of this common event. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.clearAbortCommonEvent().then(() => { + console.info("clearAbortCommonEvent"); +}).catch((err) => { + console.error("clearAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(callback: AsyncCallback\): void + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ---------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for checking whether the current common event is in the aborted state. +function getAbortCallback(err, AbortCommonEvent) { + if (err.code) { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); + } else { + console.info("AbortCommonEvent " + AbortCommonEvent) + } +} +subscriber.getAbortCommonEvent(getAbortCallback); +``` + +### getAbortCommonEvent + +getAbortCommonEvent(): Promise\ + +Checks whether this common event is in the aborted state. This API takes effect only for ordered common events. It uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ----------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the ordered common event is in the aborted state; and **false** means the opposite.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getAbortCommonEvent().then((AbortCommonEvent) => { + console.info("AbortCommonEvent " + JSON.stringify(AbortCommonEvent)); +}).catch((err) => { + console.error("getAbortCommonEvent failed " + JSON.stringify(err)); +}); +``` + +### getSubscribeInfo + +getSubscribeInfo(callback: AsyncCallback\): void + +Obtains the subscriber information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ---------------------- | +| callback | AsyncCallback\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Yes | Callback used to return the subscriber information.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for subscriber information obtaining. +function getSubscribeInfoCallback(err, SubscribeInfo) { + if (err.code) { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); + } else { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); + } +} +subscriber.getSubscribeInfo(getSubscribeInfoCallback); +``` + +### getSubscribeInfo + +getSubscribeInfo(): Promise\ + +Obtains the subscriber information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ---------------------- | +| Promise\<[CommonEventSubscribeInfo](#commoneventsubscribeinfo)> | Promise used to return the subscriber information.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.getSubscribeInfo().then((SubscribeInfo) => { + console.info("SubscribeInfo " + JSON.stringify(SubscribeInfo)); +}).catch((err) => { + console.error("getSubscribeInfo failed " + JSON.stringify(err)); +}); +``` + +### finishCommonEvent9+ + +finishCommonEvent(callback: AsyncCallback\): void + +Finishes this ordered common event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback returned after the ordered common event is finished.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +// Callback for ordered common event finishing. +function finishCommonEventCallback(err) { + if (err.code) { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +} else { + console.info("FinishCommonEvent"); +} +} +subscriber.finishCommonEvent(finishCommonEventCallback); +``` + +### finishCommonEvent9+ + +finishCommonEvent(): Promise\ + +Finishes this ordered common event. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.CommonEvent + +**Return value** + +| Type | Description | +| ---------------- | -------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```ts +var subscriber; // Subscriber object successfully created. + +subscriber.finishCommonEvent().then(() => { + console.info("FinishCommonEvent"); +}).catch((err) => { + console.error("finishCommonEvent failed " + JSON.stringify(err)); +}); +``` + +## CommonEventData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ---------- |-------------------- | ---- | ---- | ------------------------------------------------------- | +| event | string | Yes | No | Name of the common event that is being received. | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event, which is used to transfer data of the int type. | +| data | string | Yes | No | Custom result data of the common event, which is used to transfer data of the string type.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | + + +## CommonEventPublishData + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| --------------------- | -------------------- | ---- | ---- | ---------------------------- | +| bundleName | string | Yes | No | Bundle name. | +| code | number | Yes | No | Result code of the common event. | +| data | string | Yes | No | Custom result data of the common event.| +| subscriberPermissions | Array\ | Yes | No | Permissions required for subscribers to receive the common event. | +| isOrdered | boolean | Yes | No | Whether the common event is an ordered one. | +| isSticky | boolean | Yes | No | Whether the common event is a sticky one. Only system applications and system services are allowed to send sticky events.| +| parameters | {[key: string]: any} | Yes | No | Additional information about the common event. | + +## CommonEventSubscribeInfo + +**System capability**: SystemCapability.Notification.CommonEvent + +| Name | Type | Readable| Writable| Description | +| ------------------- | -------------- | ---- | ---- | ------------------------------------------------------------ | +| events | Array\ | Yes | No | Name of the common event to publish. | +| publisherPermission | string | Yes | No | Permissions required for publishers to publish the common event. | +| publisherDeviceId | string | Yes | No | Device ID. The value must be the ID of an existing device on the same network. | +| userId | number | Yes | No | User ID. The default value is the ID of the current user. If this parameter is specified, the value must be an existing user ID in the system.| +| priority | number | Yes | No | Subscriber priority. The value ranges from -100 to +1000. | diff --git a/en/application-dev/reference/apis/js-apis-configPolicy.md b/en/application-dev/reference/apis/js-apis-configPolicy.md index 4e541cbfe0022219d9ebf57b0502e82984c84384..af8d2ba8f5fa0aa614d55205d176ce49132f9068 100644 --- a/en/application-dev/reference/apis/js-apis-configPolicy.md +++ b/en/application-dev/reference/apis/js-apis-configPolicy.md @@ -1,4 +1,4 @@ -# Configuration Policy +# @ohos.configPolicy (Configuration Policy) The **configPolicy** module provides APIs for obtaining the custom configuration directory and file path based on the predefined custom configuration level. @@ -24,6 +24,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | --------------------- | | relPath | string | Yes | Name of the configuration file. | @@ -50,11 +51,13 @@ Obtains the path of a configuration file with the specified name and highest pri **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----- | | relPath | string | Yes | Name of the configuration file.| **Return value** + | Type | Description | | --------------------- | ------------ | | Promise<string> | Promise used to return the path of the configuration file.| @@ -79,6 +82,7 @@ For example, if the **config.xml** file is stored in **/system/etc/config.xml** **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------- | | relPath | string | Yes | Name of the configuration file. | @@ -105,11 +109,13 @@ Obtains a list of configuration files with the specified name, sorted in ascendi **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | ------- | ------ | ---- | ----- | | relPath | string | Yes | Name of the configuration file.| **Return value** + | Type | Description | | ---------------------------------- | ---- | | Promise<Array<string>> | Promise used to return the file list.| @@ -133,6 +139,7 @@ Obtains the list of configuration level directories. This API uses an asynchrono **System capability**: SystemCapability.Customization.ConfigPolicy **Parameters** + | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------- | | callback | AsyncCallback<Array<string>> | Yes | Callback used to return the configuration level directory list.| @@ -158,6 +165,7 @@ Obtains the list of configuration level directories. This API uses a promise to **System capability**: SystemCapability.Customization.ConfigPolicy **Return value** + | Type | Description | | ---------------------------------- | -------- | | Promise<Array<string>> | Promise used to return the configuration level directory list.| diff --git a/en/application-dev/reference/apis/js-apis-connectedTag.md b/en/application-dev/reference/apis/js-apis-connectedTag.md index 57cf8eadb5a07bcd3038c67d4d582ab4359d2ea2..1bfb1231c3c4584fe4d608891bdf2be54458e425 100644 --- a/en/application-dev/reference/apis/js-apis-connectedTag.md +++ b/en/application-dev/reference/apis/js-apis-connectedTag.md @@ -1,18 +1,17 @@ -# Active Tag +# @ohos.connectedTag -The **connectedTag** module provides methods for using active tags. You can use the APIs provided by this module to initialize the active tag chip and read and write active tags. +The **connectedTag** module provides APIs for using active tags. You can use the APIs to initialize the active tag chip and read and write active tags. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import -``` +```js import connectedTag from '@ohos.connectedTag'; ``` - ## connectedTag.init init(): boolean @@ -23,11 +22,11 @@ Initializes the active tag chip. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the initialization is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.uninit @@ -39,125 +38,136 @@ Uninitializes the active tag resources. **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +**Return value** +| **Type**| **Description**| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## connectedTag.readNdefTag readNdefTag(): Promise<string> -Reads the content of this active tag. This method uses a promise to return the result. +Reads the content of this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<string> | Promise used to return the content of the active tag.| +**Return value** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; +| **Type**| **Description**| +| -------- | -------- | +| Promise<string> | Promise used to return the content of the active tag.| - connectedTag.readNdefTag().then(result => { - console.log("promise recv ndef response: " + result); - }); - ``` +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag().then((data) => { + console.log("connectedTag readNdefTag Promise data = " + data); +}).catch((err)=> { + console.log("connectedTag readNdefTag Promise err: " + err); +}); +``` ## connectedTag.readNdefTag readNdefTag(callback: AsyncCallback<string>): void -Reads the content of this active tag. This method uses an asynchronous callback to return the result. +Reads the content of this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| +**Parameters** -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.readNdefTag(result => { - console.log("callback recv ndef response: " + result); - }); - ``` +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +connectedTag.readNdefTag((err, data)=> { + if (err) { + console.log("connectedTag readNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag readNdefTag AsyncCallback data: " + data); + } +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string): Promise<void> -Writes data to this active tag. This method uses a promise to return the result. +Writes data to this active tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - -- Return value - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result. This method returns no value.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - writeNdefTag.write("010203") - .then((value) => { - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }).catch((err) => { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| + +**Return value** + +| **Type**| **Description**| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData).then(() => { + console.log("connectedTag writeNdefTag Promise success."); +}).catch((err)=> { + console.log("connectedTag writeNdefTag Promise err: " + err); +}); +``` ## connectedTag.writeNdefTag writeNdefTag(data: string, callback: AsyncCallback<void>): void -Writes data to this active tag. This method uses an asynchronous callback to return the result. +Writes data to this active tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | data | string | Yes| Data to write. The maximum length is 1024 bytes.| - | callback | AsyncCallback<string> | Yes| Callback invoked to return the active tag content obtained.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - connectedTag.writeNdefTag("010203", (err, value) => { - if (err) { - // Failed to write data to the tag. - console.error(`failed to write event because ${err.code}`); - return; - } - - // Data is written to the tag. - console.log(`success to write event: ${value}`); - }); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | string | Yes| Data to write. The maximum length is 1024 bytes.| +| callback | AsyncCallback<void> | Yes| Callback invoked to return the active tag content obtained.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +var rawData = "010203"; // change it tobe correct. +connectedTag.writeNdefTag(rawData, (err)=> { + if (err) { + console.log("connectedTag writeNdefTag AsyncCallback err: " + err); + } else { + console.log("connectedTag writeNdefTag AsyncCallback success."); + } +}); +``` ## connectedTag.on('notify') @@ -169,18 +179,12 @@ Registers the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | Yes| Callback invoked to return the field strength state.| - -- Enumerates the field strength states. - | **Value**| **Description**| - | -------- | -------- | - | 0 | Field off.| - | 1 | Field on.| +**Parameters** +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | Yes| Callback used to return the [NfcRfType](#nfcrftype).| ## connectedTag.off('notify') @@ -192,36 +196,54 @@ Unregisters the NFC field strength state events. **System capability**: SystemCapability.Communication.ConnectedTag -- Parameters - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value is **notify**.| - | callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| - -- Example - ``` - import connectedTag from '@ohos.connectedTag'; - - var NFC_RF_NOTIFY = "notify"; - - var recvNfcRfNotifyFunc = result => { - console.info("nfc rf receive state: " + result); - } - - // Register event notification. - connectedTag.on(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - - // Unregister event notification. - connectedTag.off(NFC_RF_NOTIFY, recvNfcRfNotifyFunc); - ``` +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **notify**.| +| callback | Callback<number> | No| Callback used to return the field strength state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + +```js +import connectedTag from '@ohos.connectedTag'; + +// Register the event. +connectedTag.on("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag on Callback err: " + err); + } else { + console.log("connectedTag on Callback rfState: " + rfState); + } +}); + +var initStatus = connectedTag.init(); +console.log("connectedTag init status: " + initStatus); + +// Add nfc connecected tag business oprations here... +// connectedTag.writeNdefTag(rawData) +// connectedTag.readNdefTag() + +var uninitStatus = connectedTag.uninit(); +console.log("connectedTag uninit status: " + uninitStatus); + +// Unregister the event. +connectedTag.off("notify", (err, rfState)=> { + if (err) { + console.log("connectedTag off Callback err: " + err); + } else { + console.log("connectedTag off Callback rfState: " + rfState); + } +}); +``` ## NfcRfType -Enumerates the NFC states. +Enumerates the NFC field strength states. **System capability**: SystemCapability.Communication.ConnectedTag -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | -| NFC_RF_LEAVE | 0 | Field on.| +| NFC_RF_LEAVE | 0 | Field off.| | NFC_RF_ENTER | 1 | Field on.| diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md index a166781108683f6b6fb53673da4deacd99882b26..2778a143c65125eca650324e67a220ab60f64ead 100644 --- a/en/application-dev/reference/apis/js-apis-contact.md +++ b/en/application-dev/reference/apis/js-apis-contact.md @@ -1,4 +1,4 @@ -# Contacts +# @ohos.contact (Contacts) >**NOTE** > diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md index cfbfb83e3359a4b7d41cf6ab039d0c1f0552c9eb..89ddd643d07a9882e289b27ff9fd0cc6679fd187 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @@ -1,6 +1,6 @@ # ContinuationExtraParams -The **ContinuationExtraParams** module provides the extra parameters required by the device selection module in the continuation management entry. +The **ContinuationExtraParams** module provides the filter parameters required by the device selection module in the continuation management entry. These filter parameters can be used as an input parameter of [startContinuationDeviceManager](js-apis-continuation-continuationManager.md#continuationmanagerstartcontinuationdevicemanager9). > **NOTE** > @@ -15,7 +15,7 @@ Describes the extra parameters required by the device selection module in the co | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | deviceType | Array\ | Yes| Yes| Device type.| -| targetBundle | string | Yes| Yes| Target bundle name.| +| targetBundle | string | Yes| Yes| Name of the target bundle.| | description | string | Yes| Yes| Device filtering description.| | filter | any | Yes| Yes| Device filtering parameter.| | continuationMode | [ContinuationMode](js-apis-continuation-continuationManager.md#continuationmode) | Yes| Yes| Continuation mode.| diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md index 079c89cb0b3abf962e8d26ec2e4577e636d0dd44..05f490c454f7e7133bfc5977d1bdc2d180462a7c 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -1,8 +1,8 @@ -# continuationManager +# @ohos.continuation.continuationManager (continuationManager) The **continuationManager** module provides the continuation management entry. You can use the APIs of this module to connect to and cancel the continuation management service, subscribe to and unsubscribe from device connection events, start the device selection module, and update the device connection state. -Currently, this module provides incomplete functions, and its APIs are mainly used to start the device selection module. **The continuation capability is not available for application development.** +Currently, this module provides incomplete functions, and its APIs are mainly used to start the device selection module. The continuation capability is not available for application development. > **NOTE** > @@ -38,7 +38,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360207 | The maximum number of registrations exceeded. | +| 29360207 | The number of registrations has reached the upper limit. | **Example** @@ -79,7 +79,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360207 | The maximum number of registrations exceeded. | +| 29360207 | The number of registrations has reached the upper limit. | | 29360216 | Invalid continuation mode. | **Example** @@ -129,7 +129,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object | | 7 | The object is null. | -| 29360207 | The maximum number of registrations exceeded. | +| 29360207 | The number of registrations has reached the upper limit. | | 29360216 | Invalid continuation mode. | **Example** @@ -171,8 +171,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | +| 16600001 | The system ability works abnormally. | | 16600003 | The number of token registration times has reached the upper limit. | **Example** @@ -216,8 +215,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | +| 16600001 | The system ability works abnormally. | | 16600003 | The number of token registration times has reached the upper limit. | **Example** @@ -269,8 +267,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | +| 16600001 | The system ability works abnormally. | | 16600003 | The number of token registration times has reached the upper limit. | **Example** @@ -320,8 +317,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object | | 7 | The object is null | 7 | -| 29360208 | The token has not registered. | -| 29360209 | Callback has been registered. | +| 29360208 | The token is not registered. | +| 29360209 | The callback has been registered. | | 29360214 | The type of callback is not supported. | **Example** @@ -359,8 +356,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360209 | Callback has been registered. | +| 29360208 | The token is not registered. | +| 29360209 | The callback has been registered. | | 29360214 | The type of callback is not supported. | **Example** @@ -396,8 +393,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | | 29360214 | The type of callback is not supported. | **Example** @@ -435,8 +432,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | | 29360214 | The type of callback is not supported. | **Example** @@ -471,9 +468,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | | 16600004 | The specified callback has been registered. | **Example** @@ -518,9 +514,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | | 16600004 | The specified callback has been registered. | **Example** @@ -565,9 +560,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | | 16600004 | The specified callback has been registered. | **Example** @@ -604,9 +598,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | | 16600004 | The specified callback has been registered. | **Example** @@ -645,9 +638,9 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | | 29360216 | Invalid continuation mode. | **Example** @@ -689,9 +682,9 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object | | 7 | The object is null | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | | 29360216 | Invalid continuation mode. | **Example** @@ -741,9 +734,9 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object | | 7 | The object is null | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | | 29360216 | Invalid continuation mode. | **Example** @@ -785,9 +778,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **Example** @@ -830,9 +822,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **Example** @@ -883,9 +874,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **Example** @@ -934,10 +924,10 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | -| 29360215 | Invalid connect state. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | +| 29360215 | Invalid connection state. | **Example** @@ -985,10 +975,10 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | -| 29360210 | Callback has not registered. | -| 29360211 | Failed to connect ability. | -| 29360215 | Invalid connect state. | +| 29360208 | The token is not registered. | +| 29360210 | The callback is not registered. | +| 29360211 | Failed to connect to the ability. | +| 29360215 | Invalid connection state. | **Example** @@ -1029,9 +1019,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **Example** @@ -1081,9 +1070,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **Example** @@ -1129,7 +1117,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | +| 29360208 | The token is not registered. | **Example** @@ -1174,7 +1162,7 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ------- | -------------------------------------------- | | 3 | Failed to flatten the object. | | 7 | The object is null. | -| 29360208 | The token has not registered. | +| 29360208 | The token is not registered. | **Example** @@ -1212,9 +1200,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **Example** @@ -1261,9 +1248,8 @@ For details about the error codes, see [Distributed Scheduler Error Codes](../er | ID| Error Message| | ------- | -------------------------------------------- | -| 401 | The parameter check failed. | -| 16600001 | The system ability work abnormally. | -| 16600002 | The specified token or callback has not registered. | +| 16600001 | The system ability works abnormally. | +| 16600002 | The specified token or callback is not registered. | **Example** @@ -1289,14 +1275,12 @@ Enumerates the device connection states. **System capability**: SystemCapability.Ability.DistributedAbilityManager -**Parameters** - - | Name| Type| Value| Description| - | -------- | -------- | -------- | -------- | - | IDLE | number | 0 | The device is in the initial state.| - | CONNECTING | number | 1 | The device is being connected.| - | CONNECTED | number | 2 | The device is connected.| - | DISCONNECTING | number | 3 | The device is being disconnected.| +| Name| Value| Description| +| -------- | -------- | -------- | +| IDLE | 0 | The device is in the initial state.| +| CONNECTING | 1 | The device is being connected.| +| CONNECTED | 2 | The device is connected.| +| DISCONNECTING | 3 | The device is being disconnected.| ## ContinuationMode @@ -1304,9 +1288,7 @@ Enumerates the continuation modes provided by the device selection module. **System capability**: SystemCapability.Ability.DistributedAbilityManager -**Parameters** - - | Name| Type| Value| Description| - | -------- | -------- | -------- | -------- | - | COLLABORATION_SINGLE | number | 0 | Single-choice mode.| - | COLLABORATION_MULTIPLE | number | 1 | Multi-choice mode.| +| Name| Value| Description| +| -------- | -------- | -------- | +| COLLABORATION_SINGLE | 0 | Single-choice mode.| +| COLLABORATION_MULTIPLE | 1 | Multi-choice mode.| diff --git a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md index bdebb727ff7b5c6b41868f37bf5ecdb0ea333d10..d02b0dd61bffff14504bf77ca225c25ce953539e 100644 --- a/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md +++ b/en/application-dev/reference/apis/js-apis-continuation-continuationResult.md @@ -1,12 +1,11 @@ # ContinuationResult > **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. ## ContinuationResult -Describes the device information returned by the continuation management entry. +Describes the device information returned by the continuation management entry after [on](js-apis-continuation-continuationManager.md#continuationmanagerstartcontinuationdevicemanager9) is called. **System capability**: SystemCapability.Ability.DistributedAbilityManager diff --git a/en/application-dev/reference/apis/js-apis-convertxml.md b/en/application-dev/reference/apis/js-apis-convertxml.md index ab33a232ca03c9b8ee139f497cd6ea0f572debc7..70d35b6cb168e6f10b847a42bdefa8fd53eb3d40 100644 --- a/en/application-dev/reference/apis/js-apis-convertxml.md +++ b/en/application-dev/reference/apis/js-apis-convertxml.md @@ -1,4 +1,4 @@ -# XML-to-JavaScript Conversion +# @ohos.convertxml (XML-to-JavaScript Conversion) The **convertxml** module provides APIs for converting XML text into JavaScript objects. @@ -36,6 +36,14 @@ Converts an XML text into a JavaScript object. | ------ | ---------------------------- | | Object | JavaScript object.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200002 | Invalid xml string. | + **Example** ```js @@ -46,13 +54,13 @@ let xml = ' Work' + ' Play' + ''; -let conv = new convertxml.convertToJSObject(); +let conv = new convertxml.ConvertXML() let options = {trim : false, declarationKey:"_declaration", instructionKey : "_instruction", attributesKey : "_attributes", textKey : "_text", cdataKey:"_cdata", doctypeKey : "_doctype", commentKey : "_comment", parentKey : "_parent", typeKey : "_type", nameKey : "_name", elementsKey : "_elements"} -let result = JSON.stringify(conv.convert(xml, options)); +let result = JSON.stringify(conv.convertToJSObject(xml, options)); console.log(result); // Output (non-compact) // {"_declaration":{"_attributes":{"version":"1.0","encoding":"utf-8"}},"_elements":[{"_type":"element","_name":"note","_attributes":{"importance":"high","logged":"true"},"_elements":[{"_type":"element","_name":"title","_elements":[{"_type":"text","_text":"Happy"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Work"}]},{"_type":"element","_name":"todo","_elements":[{"_type":"text","_text":"Play"}]}]}]} @@ -60,14 +68,14 @@ console.log(result); ### convert(deprecated) -> **NOTE** -> -> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [convertToJSObject9+](#converttojsobject9) instead. - convert(xml: string, options?: ConvertOptions) : Object Converts an XML text into a JavaScript object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [convertToJSObject9+](#converttojsobject9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-cooperate.md b/en/application-dev/reference/apis/js-apis-cooperate.md index 0d46d9bda98672572ac415da0a5d92444d88a082..d63729a9dcf6a08133dd28f7cdabc6e63f0a4b6e 100644 --- a/en/application-dev/reference/apis/js-apis-cooperate.md +++ b/en/application-dev/reference/apis/js-apis-cooperate.md @@ -1,10 +1,12 @@ -# Screen Hopping +# @ohos.multimodalInput.inputDeviceCooperate (Screen Hopping) -The Screen Hopping module enables two or more networked devices to share the keyboard and mouse for collaborative operations. +The **inputDeviceCooperate** module enables two or more networked devices to share the keyboard and mouse for collaborative operations. -> **Description** +> **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 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 @@ -18,7 +20,7 @@ enable(enable: boolean, callback: AsyncCallback<void>): void Specifies whether to enable screen hopping. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -52,7 +54,7 @@ enable(enable: boolean): Promise<void> Specifies whether to enable screen hopping. This API uses a promise to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -90,7 +92,7 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCal Starts screen hopping. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -112,6 +114,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode **Example** ```js +let sinkDeviceDescriptor = "descriptor"; +let srcInputDeviceId = 0; try { inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId, (error) => { if (error) { @@ -131,7 +135,7 @@ start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\ Starts screen hopping. This API uses a promise to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -160,6 +164,8 @@ For details about the error codes, see [Screen Hopping Error Codes](../errorcode **Example** ```js +let sinkDeviceDescriptor = "descriptor"; +let srcInputDeviceId = 0; try { inputDeviceCooperate.start(sinkDeviceDescriptor, srcInputDeviceId).then(() => { console.log(`Start Keyboard mouse crossing success.`); @@ -177,7 +183,7 @@ stop(callback: AsyncCallback\): void Stops screen hopping. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -209,9 +215,9 @@ stop(): Promise\ Stops screen hopping. This API uses a promise to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator -**Parameters** +**Return value** | Name | Description | | -------- | ---------------------------- | @@ -237,7 +243,7 @@ getState(deviceDescriptor: string, callback: AsyncCallback<{ state: boolean }>): Checks whether screen hopping is enabled. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -249,6 +255,7 @@ Checks whether screen hopping is enabled. This API uses an asynchronous callback **Example** ```js +let deviceDescriptor = "descriptor"; try { inputDeviceCooperate.getState(deviceDescriptor, (error, data) => { if (error) { @@ -268,7 +275,7 @@ getState(deviceDescriptor: string): Promise<{ state: boolean }> Checks whether screen hopping is enabled. This API uses a promise to return the result. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -306,7 +313,7 @@ on(type: 'cooperation', callback: AsyncCallback<{ deviceDescriptor: string, even Enables listening for screen hopping events. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** @@ -324,7 +331,7 @@ try { inputDeviceCooperate.on('cooperation', (data) => { console.log(`Keyboard mouse crossing event: ${JSON.stringify(data)}`); }); -} catch (err) { +} catch (error) { console.log(`Register failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -335,14 +342,14 @@ off(type: 'cooperation', callback?: AsyncCallback\): void Disables listening for screen hopping events. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator **Parameters** | Name | Type | Mandatory | Description | | -------- | ---------------------------- | ---- | ---------------------------- | | type | string | Yes | Event type. The value is **cooperation**. | -| callback | AsyncCallback | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.| +| callback | AsyncCallback\ | No | Callback to be unregistered. If this parameter is not specified, all callbacks registered by the current application will be unregistered.| @@ -350,25 +357,25 @@ Disables listening for screen hopping events. ```js // Unregister a single callback. -callback: function(event) { +function callback(event) { console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); return false; -}, +} try { - inputDeviceCooperate.on('cooperation', this.callback); - inputDeviceCooperate.off("cooperation", this.callback); + inputDeviceCooperate.on('cooperation', callback); + inputDeviceCooperate.off("cooperation", callback); } catch (error) { console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ```js // Unregister all callbacks. -callback: function(event) { +function callback(event) { console.log(`Keyboard mouse crossing event: ${JSON.stringify(event)}`); return false; -}, +} try { - inputDeviceCooperate.on('cooperation', this.callback); + inputDeviceCooperate.on('cooperation', callback); inputDeviceCooperate.off("cooperation"); } catch (error) { console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); @@ -379,7 +386,7 @@ try { Enumerates screen hopping event. -**System capability**: SystemCapability.MultimodalInput.Input.InputDeviceCooperate +**System capability**: SystemCapability.MultimodalInput.Input.Cooperator | Name | Value | Description | | -------- | --------- | ----------------- | diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md index 30d79a672420f70d0ab3067857e8726ab8a7ba32..4b6210a18736d99c786a2a305dc5ed534445b488 100644 --- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md +++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md @@ -1,9 +1,9 @@ -# Crypto Framework +# @ohos.security.cryptoFramework (Crypto Framework) -The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for crytographic operations. +The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations. > **NOTE** -> +> > The initial APIs of this module are supported since API version 9. ## Modules to Import @@ -18,20 +18,23 @@ import cryptoFramework from "@ohos.security.cryptoFramework" **System capability**: SystemCapability.Security.CryptoFramework -| Name | Default Value | Description | -| --------------------------------------| -------- | -------------------------| -| INVALID_PARAMS | 401 | Invalid parameters. | -| NOT_SUPPORT | 801 | This operation is not supported. | -| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | -| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | -| ERR_CRYPTO_OPERATION | 17630001 | Crypto operation error. | +| Name | Value | Description | +| ------------------------------------- | -------- | ---------------------------- | +| INVALID_PARAMS | 401 | Invalid parameters. | +| NOT_SUPPORT | 801 | Unsupported operation. | +| ERR_OUT_OF_MEMORY | 17620001 | Memory error. | +| ERR_RUNTIME_ERROR | 17620002 | Runtime error. | +| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. | ## DataBlob + Defines a binary data array. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------| -| data | Uint8Array | Yes | Yes | Data. | + +| Name| Type | Readable| Writable| Description | +| ---- | ---------- | ---- | ---- | ------ | +| data | Uint8Array | Yes | Yes | Data.| + ## cryptoFramework.createMac @@ -53,6 +56,12 @@ Creates a **Mac** instance for message authentication code (MAC) operations. | ---- | --------------------------------------- | | Mac | [Mac](#mac) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -60,6 +69,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var mac; try { + // Set algName based on the algorithm supported. mac = cryptoFramework.createMac("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -70,7 +80,7 @@ try { Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework @@ -88,10 +98,16 @@ Initializes the MAC computation using a symmetric key. This API uses an asynchro **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| key | SymKey | Yes | Shared symmetric key. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------ | +| key | SymKey | Yes | Shared symmetric key.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -118,8 +134,6 @@ symKeyGenerator.convertKey(KeyBlob, (err, symKey) => { }); ``` - - ### init init(key : SymKey) : Promise\; @@ -136,10 +150,16 @@ Initializes the MAC computation using a symmetric key. This API uses a promise t **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -149,9 +169,7 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); - } console.error("Mac algName is: " + mac.algName); @@ -175,10 +193,18 @@ Updates the MAC computation data. This API uses an asynchronous callback to retu **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -190,7 +216,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -220,16 +245,26 @@ Updates the MAC computation data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + +**Example** + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" @@ -237,14 +272,11 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message}); console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; - var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob); promiseConvertKey.then(symKey => { @@ -260,8 +292,6 @@ promiseConvertKey.then(symKey => { ``` - - ### doFinal doFinal(callback : AsyncCallback\) : void; @@ -270,10 +300,19 @@ Finalizes the MAC computation. This API uses an asynchronous callback to return **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------- | +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -284,7 +323,6 @@ var mac; try { mac = cryptoFramework.createMac("SHA256"); } catch (error) { - AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message}); console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); } var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -323,10 +361,17 @@ Finalizes the MAC computation. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -339,7 +384,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -375,6 +419,12 @@ Obtains the MAC length, in bytes. | ------ | ------------------------- | | number | MAC length obtained.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -387,7 +437,6 @@ try { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); } console.error("Mac algName is: " + mac.algName); -AlertDialog.show({message: "Mac algName is: " + mac.algName}); var KeyBlob; var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128"); @@ -405,7 +454,7 @@ promiseConvertKey.then(symKey => { }).then(macOutput => { console.error("[Promise]: HMAC result: " + macOutput.data); let macLen = mac.getMacLength(); - AlertDialog.show({message: "MAC len: " + macLen}); + console.error("MAC len: " + macLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -431,6 +480,12 @@ Creates an **Md** instance for message digest operations. | ---- | ------------------------------------- | | Md | [Md](#md) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -438,6 +493,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework" var md; try { + // Set algName based on the algorithm supported. md = cryptoFramework.createMd("SHA256"); } catch (error) { console.error("[Promise]: error code: " + error.code + ", message is: " + error.message); @@ -448,27 +504,34 @@ try { Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd). -### **Attributes** +### Attributes **System capability**: SystemCapability.Security.CryptoFramework | Name | Type | Readable| Writable| Description | | ------- | ------ | ---- | ---- | -------------------- | -| algName | string | Yes | No | Digest algorithm to use.| +| algName | string | Yes | No | Digest algorithm.| ### update update(input : DataBlob, callback : AsyncCallback\) : void; -Updates the message digest data with the message passed in. This API uses an asynchronous callback to return the result. +Updates the message digest data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------ | -| input | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| input | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -495,20 +558,26 @@ md.update(blob, (err,) => { update(input : DataBlob) : Promise\; -Updates the message digest data with the message passed in. This API uses a promise to return the result. +Updates the message digest data. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| input | DataBlob | Yes | Message to pass in.| +| input | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -539,10 +608,17 @@ Generates a message digest. This API uses an asynchronous callback to return the **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -581,10 +657,17 @@ Generates a message digest. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -622,7 +705,13 @@ Obtains the message digest length, in bytes. | Type | Description | | ------ | ------------------------ | -| number | Message digest length obtained. | +| number | Message digest length obtained.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17630001 | crypto operation error | **Example** @@ -645,7 +734,7 @@ promiseMdUpdate.then(() => { }).then(mdOutput => { console.error("[Promise]: MD result: " + mdOutput.data); let mdLen = md.getMdLength(); - AlertDialog.show({message: "MD len: " + mdLen}); + console.error("MD len: " + mdLen); }).catch(error => { console.error("[Promise]: error: " + error.message); }); @@ -665,6 +754,12 @@ Creates a **Random** instance for generating random numbers and setting seeds. | ------ | --------------------------------------------- | | Random | [Random](#random) instance created.| +**Error codes** + +| ID| Error Message | +| -------- | ------------ | +| 17620001 | memory error | + **Example** ```javascript @@ -679,7 +774,7 @@ try { ## Random -Provides APIs for computing random numbers. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). +Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom). ### generateRandom @@ -689,10 +784,19 @@ Generates a random number of the given length. This API uses an asynchronous cal **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------- | -| len | number | Yes | Length of the random number to generate.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------- | +| len | number | Yes | Length of the random number to generate.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | **Example** @@ -722,16 +826,25 @@ Generates a random number of the given length. This API uses a promise to return **System capability**: SystemCapability.Security.CryptoFramework +**Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------- | | len | number | Yes | Length of the random number to generate.| **Return value** -| Type | Description | -| ------------------- | ----------- | +| Type | Description | +| ------------------ | ----------- | | Promise\ | Promise used to return the result.| +**Error codes** + +| ID| Error Message | +| -------- | ---------------------- | +| 17620001 | memory error | +| 17630001 | crypto operation error | + **Example** ```javascript @@ -754,16 +867,21 @@ promiseGenerateRand.then(randData => { ### setSeed -setSeed(seed : DataBlob, callback : AsyncCallback\) : void; +setSeed(seed : DataBlob) : void; Sets a seed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------ | -| seed | DataBlob | Yes | Seed to set. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| seed | DataBlob | Yes | Seed to set.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------- | +| 17620001 | memory error | **Example** @@ -782,94 +900,70 @@ rand.generateRandom(12, (err, randData) => { console.error("[Callback] err: " + err.code); } else { console.error("[Callback]: generate random result: " + randData.data); - rand.setSeed(randData, (err1, data) => { - if (err1) { - console.error("[Callback] err: " + err1.code); - } else { - console.error("[Callback]: setSeed success"); - } - }); + try { + rand.setSeed(randData); + } catch (error) { + console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message); + } } }); ``` -### setSeed - -setSeed(seed : DataBlob) : Promise\; - -Sets a seed. This API uses a promise to return the result. - -**System capability**: SystemCapability.Security.CryptoFramework - -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| seed | DataBlob | Yes | Seed to set.| - -```javascript -import cryptoFramework from "@ohos.security.cryptoFramework" - -var rand; -try { - rand = cryptoFramework.createRandom(); -} catch (error) { - console.error("[Callback]: error code: " + error.code + ", message is: " + error.message); -} - -var promiseGenerateRand = rand.generateRandom(12); -promiseGenerateRand.then(randData => { - console.error("[Promise]: rand result: " + randData.data); - var promiseSetSeed = rand.setSeed(randData); - return promiseSetSeed; -}).then(() => { - console.error("[Promise]: setSeed success"); -}).catch(error => { - console.error("[Promise]: error: " + error.message); -}); -``` - ## ParamsSpec -Defines the parameters for encryption and decryption. For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). You do not need to construct the child class object if the IV is not required. +Defines the parameters used for encryption and decryption.
For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2). **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters.
Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode. | +| Name | Type | Readable| Writable| Description | +| -------- | ------ | ---- | ---- | ----------------------- | +| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC,|CTR,|OFB, |and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.| + +> **NOTE** +> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), while a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you must set **algoName** for the parent class **ParamsSpec** to let the algorithm library know the child class object to pass in in **init()**. ## IvParamsSpec -Defines the parameters for the CBC, CTR, OFB, and CFB modes, which require only an IV for each encryption operation. For the symmetric encryption and decryption that use the CBC, CTR, OFB, or CFB mode, you need to construct **IvParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption.
Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB or CFB mode: 8-byte IV | +| Name| Type | Readable| Writable| Description | +| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, |CTR, |OFB, |or CFB mode: 16-byte IV
- 3DES CBC,|OFB, or |CFB mode: 8-byte IV| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## GcmParamsSpec -Defines the parameters for the GCM mode. For the symmetric encryption and decryption that use the GCM mode, you need to construct **GcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**GcmParamsSpec** applies to the GCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes.| -| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes.| -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 16 bytes.
When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) for decryption.| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | +| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. | +| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. | +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). | + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CcmParamsSpec -Defines the parameters for the CCM mode. For the symmetric encryption and decryption that use the CCM mode, you need to construct **CcmParamsSpec** and pass it to [init()](#init-2). +Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**CcmParamsSpec** applies to the CCM mode. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | -------- | ---- | ---- | -------------------------------| +| Name | Type | Readable| Writable| Description | +| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ | | iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. | | aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. | -| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 12 bytes.
When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) for decryption.| +| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).| + +> **NOTE** +> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec). ## CryptoMode @@ -877,22 +971,22 @@ Enumerates the cryptographic operations. **System capability**: SystemCapability.Security.CryptoFramework -| Name | Value | Description | -| ------------ | -------- | -------------------------------- | -| ENCRYPT_MODE | 0 | Encryption. | -| DECRYPT_MODE | 1 | Decryption. | +| Name | Value | Description | +| ------------ | ---- | ---------------- | +| ENCRYPT_MODE | 0 | Encryption.| +| DECRYPT_MODE | 1 | Decryption.| ## Key -Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. Keys can be generated by a key generator. +Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -905,48 +999,50 @@ Obtains the key in hexadecimal format. This API returns the result synchronously **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## SymKey -Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). +Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator). ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +import cryptoFramework from "@ohos.security.cryptoFramework" function uint8ArrayToShowStr(uint8Array) { return Array.prototype.map .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) .join(''); } -let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. +let key; // The key is generated by a symKeyGenerator. The generation process is omitted here. let encodedKey = key.getEncoded(); -console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. +console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content. key.clearMem(); encodedKey = key.getEncoded(); console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s. @@ -954,15 +1050,15 @@ console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display a ## PubKey -Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Public keys can be generated by an **AsyKeyGenerator**. +Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Public keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| @@ -976,30 +1072,37 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ## PriKey -Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Private keys can be generated by an **AsyKeyGenerator**. +Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Private keys can be generated by an **AsyKeyGenerator**. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------- | -| format | string | Yes | No | Format of the key.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| format | string | Yes | No | Format of the key. | | algName | string | Yes | No | Algorithm name (including the key length).| ### getEncoded @@ -1012,52 +1115,74 @@ Obtains the key in binary format. This API returns the result synchronously. The **Return value** -| Type |Description | -| ------- | ----------- | +| Type | Description | +| --------------------- | ------------------------ | | [DataBlob](#datablob) | Key obtained.| **Example** ```js +function uint8ArrayToShowStr(uint8Array) { + return Array.prototype.map + .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2)) + .join(''); +} + +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. console.info("key format:" + key.format); console.info("key algName:" + key.algName); var encodedKey = key.getEncoded(); -console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data)); +console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data)); ``` ### clearMem clearMem() : void -Clears the keys from the memory. This API returns the result synchronously. +Clears the keys in the memory. This API returns the result synchronously. **System capability**: SystemCapability.Security.CryptoFramework **Example** ```js +let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here. key.clearMem(); ``` +## KeyPair + +Defines an asymmetric key pair, which includes a public key and a private key.
Asymmetric key pairs can be generated by the **AsyKeyGenerator**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------ | +| priKey | [PriKey](#prikey) | Yes | No | Private key. | +| pubKey | [PubKey](#pubkey) | Yes | No | Public key. | + + ## cryptoFramework.createSymKeyGenerator createSymKeyGenerator(algName : string) : SymKeyGenerator -Creates a **SymKeyGenerator** instance based on the specified algorithm. For details about the supported symmetric key parameters, see "String for Generating a Key" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). +Creates a **symKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ----------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------------------------ | +| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String for Generating a Key" in [Key Generation Specifications] (../../security/cryptoFramework-overview.md#key-generation-specifications).| **Return value** -| Type | Description | +| Type | Description | | ----------------------------------- | -------------------------- | -| [SymKeyGenerator](#symkeygenerator) | **SymKeyGenerator** instance created.| +| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.| **Example** @@ -1068,29 +1193,35 @@ let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192'); ## SymKeyGenerator -Provides APIs for using the **symKeyGenerator**. Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). +Provides APIs for using the **symKeyGenerator**.
Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| ------- | ------ | ---- | ---- | ---------------------------- | +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------------ | | algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.| ### generateSymKey generateSymKey(callback : AsyncCallback\) : void -Generates a key randomly. This API uses an asynchronous callback to return the result. +Generates a key randomly. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ------------------- | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | **Example** @@ -1099,11 +1230,11 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); symKeyGenerator.generateSymKey((err, symKey) => { - if (err) { - console.error('Failed to generate symKey'); - return; - } - console.log('Generate symKey success, algName: ' + symKey.algName); + if (err) { + console.error(`Generate symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Generate symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1111,24 +1242,33 @@ symKeyGenerator.generateSymKey((err, symKey) => { generateSymKey() : Promise\ -Generates a key randomly. This API uses a promise to return the result. +Generates a key randomly. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | ------------- | +| 17620001 | memory error. | + **Example** ```js import cryptoFramework from '@ohos.security.cryptoFramework'; let symAlgoName = 'AES128'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); -symKeyGenerator.generateSymKey().then((symKey) => { - console.log('Generate symKey success, algName:' + symKey.algName); +symKeyGenerator.generateSymKey() +.then(symKey => { + console.info(`Generate symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Generate symKey failed, ${error.code}, ${error.message}`); }) ``` @@ -1136,16 +1276,22 @@ symKeyGenerator.generateSymKey().then((symKey) => { convertKey(key : DataBlob, callback : AsyncCallback\) : void -Converts a key. This API uses an asynchronous callback to return the result. +Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------- | ---- | ---------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert. | -| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| key | [DataBlob](#datablob) | Yes | Data to convert. | +| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------- | +| 17620001 | memory error. | **Example** @@ -1164,12 +1310,12 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { - if (err) { - console.error('Failed to convert symKey'); - return; - } - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => { + if (err) { + console.error(`Convert symKey failed, ${err.code}, ${err.message}`); + } else { + console.info(`Convert symKey success, algName: ${symKey.algName}`); + } }) ``` @@ -1177,22 +1323,28 @@ symKeyGenerator.convertKey(keyMaterial, (err, symKey) => { convertKey(key : DataBlob) : Promise\ -Converts a key. This API uses a promise to return the result. +Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| key | [DataBlob](#datablob) | Yes | Key to convert.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| key | [DataBlob](#datablob) | Yes | Data to convert.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| --------------------------- | --------------------------------- | | Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.| +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------- | +| 17620001 | memory error. | + **Example** ```js @@ -1210,14 +1362,18 @@ function genKeyMaterialBlob() { let symAlgoName = '3DES192'; let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName); let keyMaterialBlob = genKeyMaterialBlob(); -symKeyGenerator.convertKey(keyMaterial).then((symKey) => { - console.log('Convert symKey success, algName:' + symKey.algName); +symKeyGenerator.convertKey(keyMaterialBlob) +.then(symKey => { + console.info(`Convert symKey success, algName: ${symKey.algName}`); +}, error => { + console.error(`Convert symKey failed, ${error.code}, ${error.message}`); }) ``` ## cryptoFramework.createAsyKeyGenerator createAsyKeyGenerator(algName : string) : AsyKeyGenerator + Creates an **AsyKeyGenerator** instance based on the specified algorithm. **System capability**: SystemCapability.Security.CryptoFramework @@ -1226,12 +1382,12 @@ Creates an **AsyKeyGenerator** instance based on the specified algorithm. | Name | Type | Mandatory| Description | | ------- | ------ | ---- | -------------------------------- | -| algName | string | Yes | Algorithm used by the **symkeyGenerator**.| +| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.| **Return value** -| Type | Description | -| --------------- | -------------------------- | +| Type | Description | +| --------------- | ---------------------------- | | asyKeyGenerator | **AsyKeyGenerator** instance created.| **Example** @@ -1250,23 +1406,22 @@ Provides APIs for using the **AsKeyGenerator**. Before using any API of the **As **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable| Writable| Description | -| -------------- | -------------- | ---- | ---- | ----------------------------------| -| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**. | - - +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | -------------------------------- | +| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.| ### generateKeyPair generateKeyPair(callback : AsyncCallback\) : void; + Generates a key pair randomly. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------ | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** @@ -1288,14 +1443,15 @@ asyKeyGenerator.generateKeyPair((err, keyPair) => { ### generateKeyPair generateKeyPair() : Promise\ + Generates a key pair randomly. This API uses a promise to return the result. **System capability**: SystemCapability.Security.CryptoFramework **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1315,23 +1471,25 @@ keyGenPromise.then( keyPair => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void -Converts an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------- | ---- | ---------------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ------------------------------ | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. | +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. | | callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.| **Example** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" - +let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here. +let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here. let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { if (err) { @@ -1345,21 +1503,22 @@ asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => { ### convertKey convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ -Converts an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. + +Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| pubKey | DataBlob | No | Public key material to convert. | -| priKey | DataBlob | No | Private key material to convert. | +| Name | Type | Mandatory| Description | +| ------ | -------- | ---- | ---------------- | +| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.| +| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.| **Return value** -| Type | Description | -| --------------------- | ------------------------------- | +| Type | Description | +| ----------------- | --------------------------------- | | Promise\ | Promise used to return the key pair generated.| **Example** @@ -1368,6 +1527,8 @@ Converts an asymmetric key. This API uses a promise to return the result. For de import cryptoFramework from "@ohos.security.cryptoFramework" let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256"); +let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here. +let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here. let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey); keyGenPromise.then( keyPair => { console.info("convertKey success."); @@ -1378,28 +1539,32 @@ keyGenPromise.then( keyPair => { **Key Conversion** -- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 and PKCS #8 formats is returned, respectively. The data can be used for cross-application transfer or persistent storage. +- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage. - The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format. -- In **convertKey()**, **pubKey** and **priKey** are optional. Either **pubKey** or **priKey** can be passed in. As a result, the returned **KeyPair** instance contains only the key converted from the data you passed in. +- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in. ## cryptoFramework.createCipher createCipher(transformation : string) : Cipher -Creates a [Cipher](#cipher) instance based on the specified algorithm. -For details about the supported algorithms, see "Algorithm String" in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). + +Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------------- | ------ | -------- | ------------------------------------------------------------ | -| transformation | string | Yes | Combination of the algorithm name, encryption mode, and padding algorithm of the **Cipher** instance to create. For example, **RSA1024\|PKCS1** or **RSA1024\|PKCS1_OAEP\|SHA256\|SHA256**.| +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------------------------------ | +| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details about, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). | + +> **NOTE** +> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length. +> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same. **Return value** -| Type | Description | -| ------ | ------------------------ | +| Type | Description | +| ----------------- | ------------------------ | | [Cipher](#cipher) | [Cipher](#cipher) instance created.| **Example** @@ -1414,39 +1579,51 @@ try { console.info(`cipher algName: ${cipher.algName}`); } catch (error) { console.error(`createCipher failed, ${error.code}, ${error.message}`); - return; } ``` ## Cipher -Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. For details about the complete encryption and decryption process, see [Encryption and Decryption Operations](../../security/cryptoFramework-guidelines.md#encryption-and-decryption-operations). +Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data). + +A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process. + +- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation. +- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created. ### Attributes **System capability**: SystemCapability.Security.CryptoFramework -| Name | Type | Readable | Writable | Description | -| ------- | ------ | -------- | ----------- | ---------------------------- | -| algName | string | Yes | No | Algorithm to use.| +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm.| ### init init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void -Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. +Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------ | ------- | ------------------------ | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption. | -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1454,13 +1631,14 @@ Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. + cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { if (err) { - console.error('Failed to init cipher'); - return; + console.error(`Failed to init cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Init cipher success`); + // Perform subsequent operations such as update. } - console.log('Init cipher success'); - // Perform subsequent operations such as update. }) ``` @@ -1468,23 +1646,31 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => { init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ -Initializes a [cipher](#cipher) instance. This API uses a promise to return the result. +Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
**init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher). **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| ------ | ---------- | ---- | ---------------------- | -| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | -| key | [Key](#key) | Yes | Key for encryption or decryption.| -| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. | +| Name | Type | Mandatory| Description | +| ------ | ------------------------- | ---- | ------------------------------------------------------------ | +| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. | +| key | [Key](#key) | Yes | Key for encryption or decryption. | +| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.| **Return value** -| Type | Description | -| ------------------- | --------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | -------------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error.| **Example** @@ -1492,9 +1678,12 @@ Initializes a [cipher](#cipher) instance. This API uses a promise to return the import cryptoFramework from '@ohos.security.cryptoFramework'; let symKey; // The process of generating the symmetric key is omitted here. let cipher; // The process of creating a Cipher instance is omitted here. -cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { - console.log('Init cipher success'); +cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null) +.then(() => { + console.info(`Init cipher success`); // Perform subsequent operations such as update. +}, error => { + console.error(`Failed to init cipher, ${error.code}, ${error.message}`); }) ``` @@ -1502,16 +1691,29 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => { update(data : DataBlob, callback : AsyncCallback\) : void -Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1531,11 +1733,14 @@ let cipher; // The process of creating a Cipher instance is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; cipher.update(plainText, (err, output) => { // Example of the encryption process. if (err) { - console.error('Failed to update cipher'); - return; + console.error(`Failed to update cipher`); + } else { + console.info(`Update cipher success`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). } - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. }) ``` @@ -1543,21 +1748,34 @@ cipher.update(plainText, (err, output) => { // Example of the encryption p update(data : DataBlob) : Promise\ -Updates the data to encrypt or decrypt by segment. This API uses a promise to return the result. The number of times that **update()** is called varies depending on the data volume. +Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2). + +> **NOTE** +> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output. That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext. +> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment. +> - RSA asymmetric encryption and decryption do not support **update()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.| +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to returns the **DataBlob** (containing the encrypted or decrypted data).| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1575,9 +1793,15 @@ function stringToUint8Array(str) { let cipher; // The process of creating a Cipher instance is omitted here. // The init() process is omitted here. let plainText = {data : stringToUint8Array('this is test!')}; -cipher.update(data).then((output) => { - console.log('Update cipher success'); - // Perform subsequent operations such as doFinal. +cipher.update(plainText) +.then((output) => { + console.info(`Update cipher success.`); + if (output != null) { + // Concatenate output.data to the ciphertext. + } + // Perform subsequent operations such as doFinal(). +}, error => { + console.info(`Update cipher failed.`); }) ``` @@ -1585,23 +1809,33 @@ cipher.update(data).then((output) => { doFinal(data : DataBlob, callback : AsyncCallback\) : void -Finalizes the data encryption or decryption operation. This API uses an asynchronous callback to return the result. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. -- For symmetric encryption and decryption in other modes, the output can be either of the following: - (1) **Update()** returns part of the encryption and decryption result, and **doFinal()** returns the remaining encryption and decryption result. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. + +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ------------------------------------------ | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.
If data is already passed in by [update()](#update-4), **data** can be **null**. | -| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. | +| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1613,10 +1847,13 @@ let data; // The process of preparing the data to encrypt or decrypt i // The init() and update() processes are omitted here. cipher.doFinal(data, (err, output) => { if (err) { - console.error('Failed to final cipher'); - return; + console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`); + } else { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } } - console.log('Final cipher success'); }) ``` @@ -1624,31 +1861,38 @@ cipher.doFinal(data, (err, output) => { doFinal(data : DataBlob) : Promise\ -Finalizes the data encryption or decryption operation. This API uses a promise to return the result. - -The output of **doFinal** varies depending on the symmetric encryption and decryption mode. - -- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption. + (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use. -- For symmetric encryption and decryption in other modes, the output includes the following: +- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. **authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption. +- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext. - (1) **Update()** returns part of the encryption and decryption results, and **doFinal()** returns the remaining encryption and decryption results. + (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext. - (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value. +> **NOTE** +> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**. +> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name| Type | Mandatory| Description | -| ---- | -------- | ---- | -------------------- | -| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. If data is already passed in by [update()](#update-4), **data** can be **null**. | +| Name| Type | Mandatory| Description | +| ---- | --------------------- | ---- | -------------------- | +| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.| **Return value** -| Type | Description | -| ----------------------- | --------------------------- | -| Promise\<[DataBlob](#datablob)> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------ | +| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.| + +**Error codes** + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 17620001 | memory error. | +| 17620002 | runtime error. | +| 17630001 | crypto operation error. | **Example** @@ -1658,22 +1902,37 @@ import cryptoFramework from '@ohos.security.cryptoFramework'; let cipher; // The process of creating a Cipher instance is omitted here. let data; // The process of preparing the data to encrypt or decrypt is omitted here. // The init() and update() processes are omitted here. -cipher.doFinal(data).then((output) => { - console.log('Final cipher success'); +cipher.doFinal(data) +.then(output => { + console.info(`Finalize cipher success`); + if (output != null) { + // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag). + } +}, error => { + console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`); }) ``` -**Callback example**: +**RSA encryption example (callback)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); rsaGenerator.generateKeyPair(function (err, keyPair) { let pubKey = keyPair.pubKey; cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) { - let input = {data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = {data : stringToUint8Array(plainText) }; cipher.doFinal(input, function (err, data) { AlertDialog.show({ message : "EncryptOutPut is " + data.data} ); }); @@ -1681,11 +1940,19 @@ rsaGenerator.generateKeyPair(function (err, keyPair) { }); ``` -**Promise example**: +**RSA encryption example (promise)** ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +function stringToUint8Array(str) { + let arr = []; + for (let i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + return new Uint8Array(arr); +} + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); let cipher = cryptoFramework.createCipher("RSA1024|PKCS1"); let keyGenPromise = rsaGenerator.generateKeyPair(); @@ -1693,13 +1960,16 @@ keyGenPromise.then(rsaKeyPair => { let pubKey = rsaKeyPair.pubKey; return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode. }).then(() => { - let input = { data : stringToUint8Array(plan) }; + let plainText = "this is cipher text"; + let input = { data : stringToUint8Array(plainText) }; return cipher.doFinal(input); }).then(dataBlob => { console.info("EncryptOutPut is " + dataBlob.data); }); ``` +> **NOTE** +> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data). ## cryptoFramework.createSign @@ -1717,9 +1987,9 @@ Creates a **Sign** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Sign | **Sign** instance created.| +| Type| Description | +| ---- | -------------------------------- | +| Sign | **Sign** instance created.| **Example** @@ -1728,46 +1998,58 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256") ``` ## Sign -Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. +Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization. +The signing mode is determined in **createSign()**, and the key is set by **init()**. +If the data to be signed is short, you can call **sign()** to pass in the data for signing after **init()**. +If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data. +If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to use.| ### init init(priKey : PriKey, callback : AsyncCallback\) : void -Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. +Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init -init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\ +init(priKey : PriKey) : Promise\ -Initializes a **Sign** instance using a private key. This API uses a promise to return the result. +Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**. **System capability**: SystemCapability.Security.CryptoFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | Key |Yes| Private key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------- | +| priKey | PriKey | Yes | Private key used for the initialization.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1780,10 +2062,10 @@ Updates the data to be signed. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1797,12 +2079,12 @@ Updates the data to be signed. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### sign @@ -1815,10 +2097,10 @@ Signs the data. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### sign @@ -1832,53 +2114,92 @@ Signs the data. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -rsaGenerator.generateKeyPair(function (err, keyPair) { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - signer.init(priKey, function (err, data) { - signer.update(input1, function (err, data) { - signer.sign(input2, function (err, data) { - SignMessageBlob = data; - console.info("sign output is " + SignMessageBlob.data); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessageCallback() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + rsaGenerator.generateKeyPair(function (err, keyPair) { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + signer.init(priKey, function (err, data) { + signer.update(input1, function (err, data) { // Add the first segment of the data. + signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2. + SignMessageBlob = data; + AlertDialog.show({message : "res" + SignMessageBlob.data}); + }); }); }); }); -}); +} ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); -let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); -let keyGenPromise = rsaGenerator.generateKeyPair(); -keyGenPromise.then( keyPair => { - globalKeyPair = keyPair; - let priKey = globalKeyPair.priKey; - return signer.init(priKey); -}).then(() => { - return signer.update(input1); -}).then(() => { - return signer.sign(input2); -}).then(dataBlob => { - SignMessageBlob = dataBlob; - console.info("sign output is " + SignMessageBlob.data); -}); +function stringToUint8Array(str) { + var arr = []; + for (var i = 0, j = str.length; i < j; ++i) { + arr.push(str.charCodeAt(i)); + } + var tmpArray = new Uint8Array(arr); + return tmpArray; +} + +let globalKeyPair; +let SignMessageBlob; +let plan1 = "This is Sign test plan1"; // The first segment of the data. +let plan2 = "This is Sign test plan2"; // The second segment of the data. +let input1 = { data : stringToUint8Array(plan1) }; +let input2 = { data : stringToUint8Array(plan2) }; + +function signMessagePromise() { + let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2"); + let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256"); + let keyGenPromise = rsaGenerator.generateKeyPair(); + keyGenPromise.then( keyPair => { + globalKeyPair = keyPair; + let priKey = globalKeyPair.priKey; + return signer.init(priKey); + }).then(() => { + return signer.update(input1); // Add the first segment of the data. + }).then(() => { + return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2. + }).then(dataBlob => { + SignMessageBlob = dataBlob; + console.info("sign output is " + SignMessageBlob.data); + AlertDialog.show({message : "output" + SignMessageBlob.data}); + }); +} ``` ## cryptoFramework.createVerify @@ -1897,9 +2218,9 @@ Creates a **Verify** instance. **Return value** -| Type| Description | -| ---- | ------------------------------ | -| Verify | **Verify** instance created.| +| Type | Description | +| ------ | ---------------------------------- | +| Verify | **Verify** instance created.| **Example** @@ -1908,11 +2229,27 @@ import cryptoFramework from "@ohos.security.cryptoFramework" let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); -let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256") +let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256") ``` + ## Verify Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**. +The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization. +The signature verification mode is determined in **createVerify()**, and key is set by **init()**. +If the data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**. +If the data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data. +If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm to be used for signature verification.| + + ### init @@ -1924,12 +2261,13 @@ Initializes the **Verify** instance using a public key. This API uses an asynchr **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes| Public key used for the initialization.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### init + init(pubKey : PubKey) : Promise\ Initializes the **Verify** instance using a public key. This API uses a promise to return the result. @@ -1938,14 +2276,14 @@ Initializes the **Verify** instance using a public key. This API uses a promise **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| pubKey | Key |Yes|Public key used for the initialization.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------------------------- | +| pubKey | PubKey | Yes | Public key used for the initialization.| **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### update @@ -1958,10 +2296,10 @@ Updates the data for signature verification. This API uses an asynchronous callb **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### update @@ -1975,12 +2313,12 @@ Updates the data for signature verification. This API uses a promise to return t | Name| Type | Mandatory| Description | | ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in. | +| data | DataBlob | Yes | Data to pass in.| **Return value** -| Type | Description | -| ------------- | ----------- | +| Type | Description | +| -------------- | ----------- | | Promise\ | Promise used to return the result.| ### verify @@ -1993,11 +2331,11 @@ Verifies the signature. This API uses an asynchronous callback to return the res **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| data | DataBlob | Yes | Message to pass in. | -| signatureData | DataBlob | Yes | Signature data. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | +| callback | AsyncCallback\ | Yes | Callback invoked to return the result. | ### verify @@ -2009,25 +2347,30 @@ Verifies the signature. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | -------- | ---- | ---------- | -| data | DataBlob | Yes | Message to pass in.| -| signatureData | DataBlob| Yes| Signature data.| +| Name | Type | Mandatory| Description | +| ------------- | -------- | ---- | ---------- | +| data | DataBlob | Yes | Data to pass in.| +| signatureData | DataBlob | Yes | Signature data. | **Return value** -| Type | Description | -| --------------- | ------------ | +| Type | Description | +| ----------------- | ---------------------------- | | Promise\ | Promise used to return the result.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); verifyer.init(globalKeyPair.pubKey, function (err, data) { verifyer.update(input1, function(err, data) { - verifyer.verify(input2, SignMessageBlob, function(err, data) { + verifyer.verify(input2, signMessageBlob, function(err, data) { console.info("verify result is " + data); }) }); @@ -2035,19 +2378,25 @@ verifyer.init(globalKeyPair.pubKey, function (err, data) { ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); let verifyInitPromise = verifyer.init(globalKeyPair.pubKey); +let input1 = null; +let input2 = null; +let signMessageBlob = null; // Signed data, which is omitted here. verifyInitPromise.then(() => { return verifyer.update(input1); }).then(() => { - return verifyer.verify(input2, SignMessageBlob); + return verifyer.verify(input2, signMessageBlob); }).then(res => { console.log("Verify result is " + res); }); ``` + ## cryptoFramework.createKeyAgreement createKeyAgreement(algName : string) : KeyAgreement @@ -2058,15 +2407,15 @@ Creates a **KeyAgreement** instance. **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------------------------------------------------------ | -| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported. | +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------- | +| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.| **Return value** -| Type| Description | -| ---- | ------------------------------ | -| KeyAgreement | **KeyAgreement** instance created.| +| Type | Description | +| ------------ | ---------------------------------------- | +| KeyAgreement | **KeyAgreement** instance created.| **Example** @@ -2079,7 +2428,15 @@ let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); ## KeyAgreement -Provides APIs for key agreement operations. Before using any API of the **keyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. +Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**. + +### Attributes + +**System capability**: SystemCapability.Security.CryptoFramework + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ---------------------------- | +| algName | string | Yes | No | Algorithm used for key agreement.| ### generateSecret @@ -2091,13 +2448,14 @@ Generates a shared secret. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret generated. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret.| ### generateSecret + generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\ Generates a shared secret. This API uses a promise to return the result. @@ -2106,21 +2464,23 @@ Generates a shared secret. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| priKey | PriKey |Yes| Private key used for key agreement.| -| pubKey | PubKey |Yes| Public key used for key agreement.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| priKey | PriKey | Yes | Private key used for key agreement.| +| pubKey | PubKey | Yes | Public key used for key agreement.| **Return value** -| Type | Description | -| --------------- | ------------ | -| Promise\ | Promise used to return the shared secret generated. | +| Type | Description | +| ------------------ | -------- | +| Promise\ | Promise used to return the shared secret.| **Callback example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) { if (err) { @@ -2132,9 +2492,11 @@ keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function ``` **Promise example**: + ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" +let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here. let keyAgreement = cryptoFramework.createKeyAgreement("ECC256"); let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey); keyAgreementPromise.then((secret) => { diff --git a/en/application-dev/reference/apis/js-apis-curve.md b/en/application-dev/reference/apis/js-apis-curve.md new file mode 100644 index 0000000000000000000000000000000000000000..2c90472a98a38d74e7211eb8dcef2061082f18c8 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-curve.md @@ -0,0 +1,337 @@ +# @ohos.curves + +The **Curves** module provides APIs for interpolation calculation to create step, cubic Bezier, and spring curves. + +> **NOTE** +> +> 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 +import Curves from '@ohos.curves' +``` + + +## Curves.initCurve9+ + +initCurve(curve?: Curve): ICurve + + +Implements initialization for the interpolation curve, which is used to create an interpolation curve based on the input parameter. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Default Value | Description | +| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | +| curve | [Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve.Linear | Curve type.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve) | Interpolation curve.| + + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.initCurve(Curve.EaseIn) // Create a default ease-in curve, where the interpolation starts slowly and then picks up speed. +``` + + +## Curves.stepsCurve9+ + +stepsCurve(count: number, end: boolean): ICurve + + +Creates a step curve. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ----| ------------------------------------------------------------ | +| count | number | Yes | Number of steps. The value must be a positive integer. | +| end | boolean | Yes | Whether jumping occurs when the interpolation ends.
- **true**: Jumping occurs when the interpolation ends.
- **false**: Jumping occurs when the interpolation starts.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve) | Interpolation curve.| + + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.stepsCurve(9, true) // Create a step curve. +``` + + +## Curves.cubicBezierCurve9+ + +cubicBezierCurve(x1: number, y1: number, x2: number, y2: number): ICurve + + +Creates a cubic Bezier curve. The curve values must be between 0 and 1. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------------- | +| x1 | number | Yes | X coordinate of the first point on the Bezier curve.| +| y1 | number | Yes | Y coordinate of the first point on the Bezier curve.| +| x2 | number | Yes | X coordinate of the second point on the Bezier curve.| +| y2 | number | Yes | Y coordinate of the second point on the Bezier curve.| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve) | Interpolation curve.| + + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.cubicBezierCurve(0.1, 0.0, 0.1, 1.0) // Create a cubic Bezier curve. +``` + + +## Curves.springCurve9+ + +springCurve(velocity: number, mass: number, stiffness: number, damping: number): ICurve + + +Creates a spring curve. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| +| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| +| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| +| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| + + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve)| Interpolation curve.| + + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.springCurve(100, 1, 228, 30) // Create a spring curve. +``` + + +## Curves.springMotion9+ + +springMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve + +Creates a spring animation curve. If multiple spring animations are applied to the same attribute of an object, each animation replaces their predecessor and inherits the velocity. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| response | number | No | Duration of one complete oscillation, in seconds.
Default value: **0.55**| +| dampingFraction | number | No | Damping coefficient.
**0**: undamped. In this case, the spring oscillates forever.
> 0 and < 1: underdamped. In this case, the spring overshoots the equilibrium position.
**1**: critically damped.
> 1: overdamped. In this case, the spring approaches equilibrium gradually.
Default value: **0.825**| +| overlapDuration | number | No | Duration for animations to overlap, in seconds. When animations overlap, if the **response** values of the two animations are different, they will transit smoothly over this duration.
Default value: **0**| + + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve)| Curve.
Note: The spring animation curve is physics-based. Its duration depends on the **springMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. The time cannot be normalized. Therefore, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.springMotion() // Create a spring animation curve with default settings. +Curves.springMotion(0.5) // Create a spring animation curve with the specified response value. +Curves.springMotion (0.5, 0.6) // Create a spring animation curve with the specified response and dampingFraction values. +Curves.springMotion(0.5, 0.6, 0) // Create a spring animation curve with the specified parameter values. +``` + + +## Curves.responsiveSpringMotion9+ + +responsiveSpringMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve + +Creates a responsive spring animation curve. It is a special case of [springMotion](#curvesspringmotion9), with the only difference in the default values. It can be used together with **springMotion**. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| response | number | No | See **response** in **springMotion**. Default value: **0.15**| +| dampingFraction | number | No | See **dampingFraction** in **springMotion**. Default value: **0.86**| +| overlapDuration | number | No | See **overlapDuration** in **springMotion**. Default value: **0.25**| + +**Return value** + +| Type | Description | +| ---------------------------------- | ---------------- | +| [ICurve](#icurve)| Curve.
**NOTE**
1. To apply custom settings for a spring animation, you are advised to use **springMotion**. When using **responsiveSpringMotion**, you are advised to retain the default settings.
2. The duration of the responsive spring animation depends on the **responsiveSpringMotion** parameters and the previous velocity, rather than the **duration** parameter in **animation** or **animateTo**. In addition, the interpolation cannot be obtained by using the [interpolate](#interpolate) function of the curve.| + +**Example** + +```ts +import Curves from '@ohos.curves' +Curves.responsiveSpringMotion() // Create a responsive spring animation curve with default settings. +``` + + +## ICurve + + +### interpolate + +interpolate(fraction: number): number + + +Implements calculation. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------------------------------------- | +| fraction | number | Yes | Current normalized time. The value ranges from 0 to 1.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| number | Curve interpolation corresponding to the normalized time point.| + +**Example** + +```ts +import Curves from '@ohos.curves' +let curve = Curves.initCurve(Curve.EaseIn) // Create an ease-in curve. +let value: number = curve.interpolate(0.5) // Calculate the interpolation for half of the time. +``` + + +## Curves.init(deprecated) + +init(curve?: Curve): string + + +Implements initialization to create a curve. This API is deprecated since API version 9. You are advised to use [Curves.initCurve](#curvesinitcurve9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Default Value | Description | +| ------ | ------------------------------------------------------------ | ---- | ------------ | ---------- | +| curve |[Curve](../arkui-ts/ts-appendix-enums.md#curve) | No | Curve.Linear | Curve type.| + + +## Curves.steps(deprecated) + +steps(count: number, end: boolean): string + + +Creates a step curve. This API is deprecated since API version 9. You are advised to use [Curves.stepsCurve](#curvesstepscurve9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ----| ------------------------------------------------------------ | +| count | number | Yes | Number of steps. The value must be a positive integer. | +| end | boolean | Yes | Whether jumping occurs when the interpolation ends.
- **true**: Jumping occurs when the interpolation ends.
- **false**: Jumping occurs when the interpolation starts.| + + +## Curves.cubicBezier(deprecated) + +cubicBezier(x1: number, y1: number, x2: number, y2: number): string + + +Creates a cubic Bezier curve. The curve value must range from 0 to 1. This API is deprecated since API version 9. You are advised to use [Curves.cubicBezierCurve](#curvescubicbeziercurve9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------------- | +| x1 | number | Yes | X coordinate of the first point on the Bezier curve.| +| y1 | number | Yes | Y coordinate of the first point on the Bezier curve.| +| x2 | number | Yes | X coordinate of the second point on the Bezier curve.| +| y2 | number | Yes | Y coordinate of the second point on the Bezier curve.| + + +## Curves.spring(deprecated) + +spring(velocity: number, mass: number, stiffness: number, damping: number): string + + +Creates a spring curve. This API is deprecated since API version 9. You are advised to use [Curves.springCurve](#curvesspringcurve9) instead. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------ | ---- | ----- | +| velocity | number | Yes | Initial velocity. It is applied by external factors to the elastic animation. It aims to help ensure the smooth transition from the previous motion state to the elastic animation.| +| mass | number | Yes | Mass, which influences the inertia in the spring system. The greater the mass, the greater the amplitude of the oscillation, and the slower the speed of restoring to the equilibrium position.| +| stiffness | number | Yes | Stiffness. It is the degree to which an object deforms by resisting the force applied. In an elastic system, the greater the stiffness, the stronger the ability to resist deformation, and the faster the speed of restoring to the equilibrium position.| +| damping | number | Yes | Damping. It is a pure number and has no real physical meaning. It is used to describe the oscillation and attenuation of the system after being disturbed. The larger the damping, the smaller the number of oscillations of elastic motion, and the smaller the oscillation amplitude.| + +## Example + +```ts +// xxx.ets +import Curves from '@ohos.curves' + +@Entry +@Component +struct ImageComponent { + @State widthSize: number = 200 + @State heightSize: number = 200 + + build() { + Column() { + Text() + .margin({ top: 100 }) + .width(this.widthSize) + .height(this.heightSize) + .backgroundColor(Color.Red) + .onClick(() => { + let curve = Curves.cubicBezierCurve(0.25, 0.1, 0.25, 1.0); + this.widthSize = curve.interpolate(0.5) * this.widthSize; + this.heightSize = curve.interpolate(0.5) * this.heightSize; + }) + .animation({ duration: 2000, curve: Curves.stepsCurve(9, true) }) + }.width("100%").height("100%") + } +} +``` + +![en-us_image_0000001174104410](figures/en-us_image_0000001174104410.gif) diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index 5fedece20aac3dc30e68020964be1fbca1cefdfa..4cdef60fa628733e5be8cc6df783548b7b5bcd07 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -1,4 +1,4 @@ -# Data Share Result Set +# @ohos.data.dataShareResultSet (DataShare Result Set) The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type. diff --git a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md index 22ae3fc33e27b1dc0b859848fdb8e0ea6c6f2122..009ff71b091c7d91a92d92364450316e3aeecfa2 100644 --- a/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md +++ b/en/application-dev/reference/apis/js-apis-data-ValuesBucket.md @@ -1,4 +1,4 @@ -# Value Bucket +# @ohos.data.ValuesBucket (Value Bucket) The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database. @@ -34,6 +34,6 @@ Defines the types of the key and value in a KV pair. **System capability**: SystemCapability.DistributedDataManager.DataShare.Core -| Key Type | Value Type | -| ------------- | --------------------------------------------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | +| Key Type | Value Type | +| ------------- | --------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | 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 779d30c40263eecd1a8ecf70209a95008aa228dd..f41bea4da45a6f6c0224e126f698d45d274e25dc 100644 --- a/en/application-dev/reference/apis/js-apis-data-ability.md +++ b/en/application-dev/reference/apis/js-apis-data-ability.md @@ -1,4 +1,4 @@ -# DataAbilityPredicates +# @ohos.data.dataAbility (DataAbility Predicates) **DataAbility** provides APIs for creating predicates, which implement different query methods for relational database (RDB) stores. @@ -23,16 +23,16 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of a database table.| - | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of a database table.| +| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. | **Return value** - | Type| Description| - | -------- | -------- | - | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| +| Type| Description| +| -------- | -------- | +| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.| **Example** @@ -56,16 +56,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -83,16 +83,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -110,9 +110,9 @@ Adds a left parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.| **Example** @@ -135,9 +135,9 @@ Adds a right parenthesis to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.| **Example** @@ -160,9 +160,9 @@ Adds the OR condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.| **Example** @@ -182,9 +182,9 @@ Adds the AND condition to this **DataAbilityPredicates**. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.| **Example** @@ -204,16 +204,16 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -231,16 +231,16 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -258,16 +258,16 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -285,15 +285,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -311,15 +311,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -337,16 +337,16 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -364,16 +364,16 @@ Sets a **DataAbilityPredicates** object to match the specified string. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | string | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | string | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -391,17 +391,17 @@ Sets a **DataAbilityPredicates** object to match a field whose data type is **Va **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -419,17 +419,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| - | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.| +| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -447,16 +447,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -474,16 +474,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -501,16 +501,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -528,16 +528,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -555,15 +555,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -581,15 +581,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -607,9 +607,9 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records. **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.| **Example** @@ -627,15 +627,15 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | value | number | Yes| Maximum number of records.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | number | Yes| Maximum number of records.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.| **Example** @@ -653,15 +653,15 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.| **Example** @@ -680,15 +680,15 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fields | Array<string> | Yes| Names of columns to group.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| fields | Array<string> | Yes| Names of columns to group.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.| **Example** @@ -706,15 +706,15 @@ Sets a **DataAbilityPredicates** object to specify the index column. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | indexName | string | Yes| Name of the index column.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| indexName | string | Yes| Name of the index column.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.| **Example** @@ -732,17 +732,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** @@ -760,16 +760,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\ **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | field | string | Yes| Column name in the table.| - | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| field | string | Yes| Column name in the table.| +| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.| **Return value** - | Type| Description| - | -------- | -------- | - | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| +| Type| Description| +| -------- | -------- | +| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md index a5f16c8c04d650608231c4757224c662c23bf387..82a333b14b2ea90e92540ee31142ea884c7f2593 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataShare.md +++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md @@ -1,4 +1,4 @@ -# Data Sharing +# @ohos.data.dataShare (DataShare) The **DataShare** module allows an application to manage its own data and share data with other applications on the same device. @@ -17,6 +17,26 @@ The **DataShare** module allows an application to manage its own data and share import dataShare from '@ohos.data.dataShare' ``` +## URI Naming Rule + +The URIs are in the following format: + +**Scheme://authority/path** +- *Scheme*: scheme name, which has a fixed value of **datashare** for the **DataShare** module. +- *authority*: [userinfo@]host[:port] + - *userinfo*: login information, which can be left unspecified. + - *host*: server address. It is the target device ID for cross-device access and empty for local device access. + - *port*: port number of the server, which can be left unspecified. +- *path*: **DataShare** identifier and the resource path. The **DataShare** identifier is mandatory, and the resource path is optional. + +Example: + +- URI without the resource path:
**datashare:///com.samples.datasharetest.DataShare** + +- URI with the resource path:
**datashare:///com.samples.datasharetest.DataShare/DB00/TBL00** + +**com.samples.datasharetest.DataShare** is the data share identifier, and **DB00/TBL00** is the resource path. + ## dataShare.createDataShareHelper @@ -24,6 +44,11 @@ createDataShareHelper(context: Context, uri: string, callback: AsyncCallback< Creates a **DataShareHelper** instance. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -34,21 +59,33 @@ Creates a **DataShareHelper** instance. This API uses an asynchronous callback t | uri | string | Yes | Uniform Resource Identifier (URI) of the server application to connect. | | callback | AsyncCallback<[DataShareHelper](#datasharehelper)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the **DataShareHelper** instance created. Otherwise, **err** is an error object.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri, (err, data) => { - if (err != undefined) { - console.info("createDataShareHelper failed, error message : " + err); - } else { +try { + dataShare.createDataShareHelper(this.context, uri, (err, data) => { + if (err != undefined) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + return; + } console.info("createDataShareHelper succeed, data : " + data); dataShareHelper = data; - } -}); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## dataShare.createDataShareHelper @@ -57,6 +94,11 @@ createDataShareHelper(context: Context, uri: string): Promise<DataShareHelper Creates a **DataShareHelper** instance. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to access **DataShareExtension**, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target **DataShareExtension** is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.DistributedDataManager.DataShare.Consumer **Parameters** @@ -72,19 +114,31 @@ Creates a **DataShareHelper** instance. This API uses a promise to return the re | -------------------------------------------------- | -------------------------------------- | | Promise<[DataShareHelper](#datasharehelper)> | Promise used to return the **DataShareHelper** instance created.| +**Error codes** + +For details about the error codes, see [DataShare Error Codes](../errorcodes/errorcode-datashare.md). + +| ID| Error Message | +| -------- | ---------------------------------------------------- | +| 15700010 | The dataShareHelper is not initialized successfully. | + **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let dataShareHelper; -dataShare.createDataShareHelper(this.context, uri).then((data) => { - console.info("createDataShareHelper succeed, data : " + data); - dataShareHelper = data; -}).catch((err) => { - console.info("createDataShareHelper failed, error message : " + err); -}) +try { + dataShare.createDataShareHelper(this.context, uri).then((data) => { + console.info("createDataShareHelper succeed, data : " + data); + dataShareHelper = data; + }). catch((err) => { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`createDataShareHelper error: code: ${err.code}, message: ${err.message} `); +}; ``` ## DataShareHelper @@ -101,16 +155,17 @@ Subscribes to changes of the specified data. After an observer is registered, th **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to subscribe to. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the data is changed, the value of **err** is **undefined**. Otherwise, this callback is not invoked or the value of **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If data is changed, the value of **err** is undefined. Otherwise, this callback is not invoked or the value of **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function onCallback() { console.info("**** Observer on callback ****"); } @@ -128,7 +183,7 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | type | string | Yes | Event type to unsubscribe from. The value is **dataChange**, which indicates data change events.| | uri | string | Yes | URI of the data.| @@ -137,7 +192,8 @@ Unsubscribes from the changes of the specified data. This API uses an asynchrono **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + function offCallback() { console.info("**** Observer off callback ****"); } @@ -155,29 +211,34 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the index of the inserted data record. Otherwise, **err** is an error object.
The data index is not returned if the APIs of the database in use, for example, the key-value database (KVDB), do not support the return of indexes.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose", "age": 22, "salary": 200.5, } -dataShareHelper.insert(uri, valueBucket, (err, data) => { - if (err != undefined) { - console.log("insert failed, error message : " + err); - }else{ - console.log("insert succeed, data : " + data); - } -}); +try { + dataShareHelper.insert(uri, valueBucket, (err, data) => { + if (err != undefined) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("insert succeed, data : " + data); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### insert @@ -193,7 +254,7 @@ Inserts a single data record into the database. This API uses a promise to retur | Name | Type | Mandatory| Description | | ----- | --------------------------------------------------------- | ---- | -------------------------------------------------- | | uri | string | Yes | URI of the data to insert. | -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | Data to insert. If this parameter is empty, a blank row will be inserted.| **Return value** @@ -204,18 +265,23 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); const valueBucket = { "name": "rose1", "age": 221, "salary": 20.5, } -dataShareHelper.insert(uri, valueBucket).then((data) => { - console.log("insert succeed, data : " + data); -}).catch((err) => { - console.log("insert failed, error message : " + err); -}); +try { + dataShareHelper.insert(uri, valueBucket).then((data) => { + console.log("insert succeed, data : " + data); + }). catch((err) => { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`insert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -231,25 +297,29 @@ Deletes one or more data records from the database. This API uses an asynchronou | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of deleted data records. Otherwise, **err** is an error object.
The number of deleted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da, (err, data) => { - if (err != undefined) { - console.log("delete failed, error message : " + err); - }else{ - console.log("delete succeed, data : " + data); - } -}); +try { + dataShareHelper.delete(uri, da, (err, data) => { + if (err != undefined) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + return; + } + console.info("delete succeed, data : " + data); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### delete @@ -265,7 +335,7 @@ Deletes one or more data records from the database. This API uses a promise to r | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **delete()** vary depending on the database in use. For example, the KVDB supports only **inKeys**.| **Return value** @@ -276,17 +346,21 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.delete(uri, da).then((data) => { - console.log("delete succeed, data : " + data); -}).catch((err) => { - console.log("delete failed, error message : " + err); -}); +try { + dataShareHelper.delete(uri, da).then((data) => { + console.log("delete succeed, data : " + data); + }). catch((err) => { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`delete error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -302,27 +376,31 @@ Queries data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | | callback | AsyncCallback<[DataShareResultSet](js-apis-data-DataShareResultSet.md#datashareresultset)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the result set obtained. Otherwise, **err** is an error object.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns, (err, data) => { - if (err != undefined) { - console.log("query failed, error message : " + err); - }else{ +try { + dataShareHelper.query(uri, da, columns, (err, data) => { + if (err != undefined) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("query succeed, rowCount : " + data.rowCount); - } -}); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### query @@ -338,7 +416,7 @@ Queries data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **query()** vary depending on the database used. For example, the KVDB supports only **inKeys** and **prefixKey**.| | columns | Array<string> | Yes | Columns to query. If this parameter is empty, all columns will be queried. | **Return value** @@ -350,18 +428,22 @@ Queries data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let columns = ["*"]; let da = new dataSharePredicates.DataSharePredicates(); da.equalTo("name", "ZhangSan"); -dataShareHelper.query(uri, da, columns).then((data) => { - console.log("query succeed, rowCount : " + data.rowCount); -}).catch((err) => { - console.log("query failed, error message : " + err); -}); +try { + dataShareHelper.query(uri, da, columns).then((data) => { + console.log("query succeed, rowCount : " + data.rowCount); + }). catch((err) => { + console.error(`query error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`query error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -377,15 +459,15 @@ Updates data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of updated data records. Otherwise, **err** is an error object.
The number of updated data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -396,13 +478,17 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va, (err, data) => { - if (err != undefined) { - console.log("update failed, error message : " + err); - }else{ +try { + dataShareHelper.update(uri, da, va, (err, data) => { + if (err != undefined) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("update succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### update @@ -418,8 +504,8 @@ Updates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to update. | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| -| value | [ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket) | Yes | New data. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | Filter criteria.
The predicate methods supported by **update()** vary depending on the database in use. For example, only the relational database (RDB) supports predicates.| +| value | [ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket) | Yes | New data. | **Return value** @@ -430,8 +516,8 @@ Updates data in the database. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' -import dataSharePredicates from '@ohos.data.dataSharePredicates' +import UIAbility from '@ohos.app.ability.UIAbility'; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; let uri = ("datashare:///com.samples.datasharetest.DataShare"); let da = new dataSharePredicates.DataSharePredicates(); @@ -442,11 +528,15 @@ const va = { "salary": 20.5, } -dataShareHelper.update(uri, da, va).then((data) => { - console.log("update succeed, data : " + data); -}).catch((err) => { - console.log("update failed, error message : " + err); -}); +try { + dataShareHelper.update(uri, da, va).then((data) => { + console.log("update succeed, data : " + data); + }). catch((err) => { + console.error(`update error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`update error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -462,24 +552,29 @@ Batch inserts data into the database. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | uri | string | Yes | URI of the data to insert. | -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | | callback | AsyncCallback<number> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the number of data records inserted. Otherwise, **err** is an error object.
The number of inserted data records is not returned if the APIs of the database in use (for example, KVDB) do not support this return.| **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs, (err, data) => { - if (err != undefined) { - console.log("batchInsert failed, error message : " + err); - }else{ +try { + dataShareHelper.batchInsert(uri, vbs, (err, data) => { + if (err != undefined) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + return; + } console.log("batchInsert succeed, data : " + data); - } -}); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### batchInsert @@ -495,7 +590,7 @@ Batch inserts data into the database. This API uses a promise to return the resu | Name | Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------ | | uri | string | Yes | URI of the data to insert.| -| values | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to insert. | +| values | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to insert. | **Return value** @@ -506,16 +601,21 @@ Batch inserts data into the database. This API uses a promise to return the resu **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); let vbs = new Array({"name": "roe11", "age": 21, "salary": 20.5,}, {"name": "roe12", "age": 21, "salary": 20.5,}, {"name": "roe13", "age": 21, "salary": 20.5,}) -dataShareHelper.batchInsert(uri, vbs).then((data) => { - console.log("batchInsert succeed, data : " + data); -}).catch((err) => { - console.log("batchInsert failed, error message : " + err); -}); +try { + dataShareHelper.batchInsert(uri, vbs).then((data) => { + console.log("batchInsert succeed, data : " + data); + }). catch((err) => { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); + }); +} catch (err) { + console.error(`batchInsert error: code: ${err.code}, message: ${err.message} `); +}; ``` ### normalizeUri @@ -536,7 +636,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri, (err, data) => { if (err != undefined) { @@ -570,7 +671,8 @@ Normalizes a **DataShare** URI. The **DataShare** URI can be used only by the lo **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.normalizeUri(uri).then((data) => { console.log("normalizeUri = " + data); @@ -597,7 +699,8 @@ Denormalizes a URI. This API uses an asynchronous callback to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri, (err, data) => { if (err != undefined) { @@ -631,7 +734,8 @@ Denormalizes a URI. This API uses a promise to return the result. **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.denormalizeUri(uri).then((data) => { console.log("denormalizeUri = " + data); @@ -650,7 +754,7 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | uri | string | Yes | URI of the data.| | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the observer is notified of the data changes, **err** is **undefined**. Otherwise, **err** is an error object.| @@ -658,7 +762,8 @@ Notifies the registered observer of data changes. This API uses an asynchronous **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri, () => { console.log("***** notifyChange *****"); @@ -688,7 +793,8 @@ Notifies the registered observer of data changes. This API uses a promise to ret **Example** ```ts -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; + let uri = ("datashare:///com.samples.datasharetest.DataShare"); dataShareHelper.notifyChange(uri); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 4d2df994d96b7b0986782774e9d531a12750cac7..78d896c54a2f1c1674825ddaff66088634129596 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -1,4 +1,4 @@ -# Data Share Predicates +# @ohos.data.dataSharePredicates (DataShare Predicates) You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. @@ -35,7 +35,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -65,7 +65,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -439,8 +439,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -470,8 +470,8 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ------------------------ | | field | string | Yes | Column name in the database table. | -| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.| -| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.| +| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.| +| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.| **Return value** @@ -501,7 +501,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -531,7 +531,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | --------------------------------------------------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -561,7 +561,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -591,7 +591,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | --------- | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.| +| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.| **Return value** @@ -790,7 +790,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes| Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** @@ -820,7 +820,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | --------------------------------------- | | field | string | Yes | Column name in the database table. | -| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.| +| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md index 6f24aa3255f0340e0ad8ef248ae25d62092e0774..dc8bf8258b987e9e4ad2799516ee6aafeb487896 100644 --- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md +++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md @@ -1,4 +1,4 @@ -# Distributed Data Object +# @ohos.data.distributedDataObject (Distributed Data Object) The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices. @@ -23,9 +23,9 @@ Creates a distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | source | object | Yes| Attribute of the distributed data object to create.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| source | object | Yes| Attribute of the distributed data object to create.| **Return value** | Type| Description| @@ -49,9 +49,9 @@ Creates a random session ID. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Return value** - | Type| Description| - | -------- | -------- | - | string | Session ID created.| +| Type| Description| +| -------- | -------- | +| string | Session ID created.| **Example** ```js @@ -97,15 +97,15 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. | **Example** @@ -128,10 +128,10 @@ Subscribes to the changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** ```js @@ -157,10 +157,10 @@ Unsubscribes from the changes of this distributed data object. **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| - | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.| +| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.| **Example** @@ -182,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.| **Example** ```js @@ -207,10 +207,10 @@ Unsubscribes from the status change (online or offline) of this distributed data **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| - | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.| +| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.| **Example** @@ -243,10 +243,10 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| - | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.| +| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** ```js @@ -279,15 +279,15 @@ The saved data will be released in the following cases: **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| +| Type| Description| +| -------- | -------- | +| Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.| **Example** @@ -317,9 +317,9 @@ If the object is stored on another device, the data on the local device will be **System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** @@ -345,9 +345,9 @@ If the object is stored on another device, the data on the local device will be **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| +| Type| Description| +| -------- | -------- | +| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index cad744cb266c3c5712de9d441fe0a56a1fc4ccbc..5ba79b73ed0370258a87975c1a4ee576816964b4 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,4 +1,4 @@ -# Preferences +# @ohos.data.preferences (Preferences) The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. @@ -38,7 +38,7 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| | callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| @@ -103,7 +103,7 @@ Obtains a **Preferences** instance. This API uses a promise to return the result | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| **Return value** @@ -177,7 +177,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| @@ -252,7 +252,7 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** @@ -328,7 +328,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| @@ -394,7 +394,7 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi | Name | Type | Mandatory| Description | | ------- | ------------------------------------- | ---- | ----------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** @@ -497,7 +497,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md index 87c75a024fb144c72c0942e44b114a7d250a8008..bcebd097f34c1337e5826e866302af9626696a32 100644 --- a/en/application-dev/reference/apis/js-apis-data-rdb.md +++ b/en/application-dev/reference/apis/js-apis-data-rdb.md @@ -1,4 +1,4 @@ -# Relational Database +# @ohos.data.rdb (RDB) The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. @@ -8,15 +8,17 @@ This module provides the following RDB-related functions: - [RdbStore](#rdbstore): provides APIs for managing an RDB store. > **NOTE**
-> +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore](js-apis-data-relationalStore.md). + ## Modules to Import ```js import data_rdb from '@ohos.data.rdb'; ``` - ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number, callback: AsyncCallback<RdbStore>): void @@ -27,12 +29,12 @@ Obtains an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| -| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes| Callback invoked to return the RDB store obtained.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | +| callback | AsyncCallback<[RdbStore](#rdbstore)> | Yes | Callback invoked to return the RDB store obtained. | **Example** @@ -41,7 +43,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db"} @@ -58,9 +60,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -76,6 +79,7 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, function (err, rdbStore) { console.log("Got RdbStore successfully.") }) ``` + ## data_rdb.getRdbStore getRdbStore(context: Context, config: StoreConfig, version: number): Promise<RdbStore> @@ -86,16 +90,16 @@ Obtains an RDB store. This API uses a promise to return the result. You can set **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes|Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| config | [StoreConfig](#storeconfig) | Yes| Configuration of the RDB store.| -| version | number | Yes| RDB store version.| +| Name | Type | Mandatory| Description | +| ------- | --------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| config | [StoreConfig](#storeconfig) | Yes | Configuration of the RDB store. | +| version | number | Yes | RDB store version.
Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------------------------ | ------------------------------- | | Promise<[RdbStore](#rdbstore)> | Promise used to return the RDB store obtained.| **Example** @@ -105,7 +109,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call getRdbStore. const STORE_CONFIG = { name: "RdbTest.db" } @@ -121,9 +125,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -149,11 +154,11 @@ Deletes an RDB store. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | **Example** @@ -162,7 +167,7 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. data_rdb.deleteRdbStore(context, "RdbTest.db", function (err) { @@ -178,9 +183,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -206,16 +212,16 @@ Deletes an RDB store. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| context | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| -| name | string | Yes| Name of the RDB store to delete.| +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| +| name | string | Yes | Name of the RDB store to delete. | **Return value** -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** @@ -224,11 +230,11 @@ FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() // Call deleteRdbStore. let promise = data_rdb.deleteRdbStore(context, "RdbTest.db") -promise.then(()=>{ +promise.then(() => { console.log("Deleted RdbStore successfully.") }).catch((err) => { console.info("Failed to delete RdbStore, err: " + err) @@ -239,9 +245,10 @@ Stage model: ```ts // Obtain the context. -import Ability from '@ohos.application.Ability' -var context -class MainAbility extends Ability{ +import UIAbility from '@ohos.app.ability.UIAbility'; + +let context; +class EntryAbility extends UIAbility { onWindowStageCreate(windowStage){ context = this.context } @@ -256,16 +263,70 @@ promise.then(()=>{ }) ``` +## ValueType + +Defines the data types allowed. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Type | Description | +| ------- | -------------------- | +| number | Number. | +| string | String. | +| boolean | Boolean.| + + +## ValuesBucket + +Defines the types of the key and value in a KV pair. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Key Type| Value Type | +| ------ | ----------------------------------------------------------- | +| string | [ValueType](#valuetype)\| Uint8Array \| null | + +## SyncMode8+ + +Defines the database synchronization mode. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| -------------- | ---- | ---------------------------------- | +| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| +| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device. | + +## SubscribeType8+ + +Defines the subscription type. + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name | Value | Description | +| --------------------- | ---- | ------------------ | +| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| + +## StoreConfig + +Defines the RDB store configuration. + +**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Database file name.| + ## RdbPredicates Defines predicates for an RDB store. This class determines whether the conditional expression for the RDB store is true or false. - ### constructor constructor(name: string) - A constructor used to create an **RdbPredicates** object. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -286,8 +347,7 @@ let predicates = new data_rdb.RdbPredicates("EMPLOYEE") inDevices(devices: Array<string>): RdbPredicates - -Sets an **RdbPredicates** to specify the remote devices on the network to connect during distributed database synchronization. +Sets an **RdbPredicates** to specify the remote devices to connect on the network during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -314,7 +374,6 @@ predicates.inDevices(['12345678abcde']) inAllDevices(): RdbPredicates - Sets an **RdbPredicates** to specify all remote devices on the network to connect during distributed database synchronization. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -336,7 +395,6 @@ predicates.inAllDevices() equalTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -366,7 +424,6 @@ predicates.equalTo("NAME", "lisi") notEqualTo(field: string, value: ValueType): RdbPredicates - Sets an **RdbPredicates** to match the field with data type **ValueType** and value not equal to the specified value. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -396,7 +453,6 @@ predicates.notEqualTo("NAME", "lisi") beginWrap(): RdbPredicates - Adds a left parenthesis to the **RdbPredicates**. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -1098,7 +1154,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) Provides methods to manage an RDB store. -Before using the following APIs, use [executeSql](#executesql) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). +Before using the following APIs, use [executeSql](#executesql8) to initialize the database table structure and related data. For details, see [RDB Development](../../database/database-relational-guidelines.md). ### insert @@ -1172,7 +1228,7 @@ promise.then((rowId) => { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>, callback: AsyncCallback<number>):void @@ -1210,7 +1266,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { if (status) { console.log("Failed to batch insert data, status = " + status); @@ -1220,7 +1276,7 @@ rdbStore.batchInsert("EMPLOYEE", valueBuckets, function(status, insertNum) { }) ``` -### batchInsert9+ +### batchInsert batchInsert(table: string, values: Array<ValuesBucket>):Promise<number> @@ -1263,7 +1319,7 @@ const valueBucket3 = { "CODES": new Uint8Array([11, 12, 13, 14, 15]) } -var valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); +let valueBuckets = new Array(valueBucket1, valueBucket2, valueBucket3); let promise = rdbStore.batchInsert("EMPLOYEE", valueBuckets); promise.then((insertNum) => { console.log("Batch inserted data successfully. The number of values that were inserted = " + insertNum); @@ -1299,12 +1355,12 @@ const valueBucket = { } let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") -rdbStore.update(valueBucket, predicates, function (err, ret) { +rdbStore.update(valueBucket, predicates, function (err, rows) { if (err) { console.info("Failed to update data, err: " + err) return } - console.log("Updated row count: " + ret) + console.log("Updated row count: " + rows) }) ``` @@ -1341,91 +1397,8 @@ const valueBucket = { let predicates = new data_rdb.RdbPredicates("EMPLOYEE") predicates.equalTo("NAME", "Lisa") let promise = rdbStore.update(valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) -}).catch((err) => { - console.info("Failed to update data, err: " + err) -}) -``` - -### update9+ -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates)| Yes| Update conditions specified by the **DataSharePredicates** object.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.update("EMPLOYEE", valueBucket, predicates, function (err, ret) { - if (err) { - console.info("Failed to update data, err: " + err) - return - } - console.log("Updated row count: " + ret) -}) -``` - -### update9+ - -update(table: string, values: ValuesBucket, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Updates data in the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| values | [ValuesBucket](#valuesbucket) | Yes| Rows of data to update in the RDB store. The key-value pair is associated with the column name in the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Update conditions specified by the **DataSharePredicates** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -const valueBucket = { - "NAME": "Rose", - "AGE": 22, - "SALARY": 200.5, - "CODES": new Uint8Array([1, 2, 3, 4, 5]), -} -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.update("EMPLOYEE", valueBucket, predicates) -promise.then(async (ret) => { - console.log("Updated row count: " + ret) +promise.then(async (rows) => { + console.log("Updated row count: " + rows) }).catch((err) => { console.info("Failed to update data, err: " + err) }) @@ -1493,76 +1466,6 @@ promise.then((rows) => { }) ``` -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<number>):void - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -rdbStore.delete("EMPLOYEE", predicates, function (err, rows) { - if (err) { - console.info("Failed to delete data, err: " + err) - return - } - console.log("Deleted rows: " + rows) -}) -``` - -### delete9+ - -delete(table: string, predicates: dataSharePredicates.DataSharePredicates):Promise<number> - -Deletes data from the RDB store based on the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Conditions specified by the **DataSharePredicates** object for deleting data.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the number of rows updated.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Lisa") -let promise = rdbStore.delete("EMPLOYEE", predicates) -promise.then((rows) => { - console.log("Deleted rows: " + rows) -}).catch((err) => { - console.info("Failed to delete data, err: " + err) -}) -``` - ### query query(predicates: RdbPredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void @@ -1629,151 +1532,6 @@ Queries data from the RDB store based on specified conditions. This API uses a p }) ``` -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns: Array<string>, callback: AsyncCallback<ResultSet>):void - -Queries data from the RDB store based on specified conditions. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], function (err, resultSet) { - if (err) { - console.info("Failed to query data, err: " + err) - return - } - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) -}) -``` - -### query9+ - -query(table: string, predicates: dataSharePredicates.DataSharePredicates, columns?: Array<string>):Promise<ResultSet> - -Queries data from the RDB store based on specified conditions. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| table | string | Yes| Name of the target table.| -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes| Query conditions specified by the **DataSharePredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<[ResultSet](js-apis-data-resultset.md)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates' -let predicates = new dataSharePredicates.DataSharePredicates() -predicates.equalTo("NAME", "Rose") -let promise = rdbStore.query("EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.log("ResultSet column names: " + resultSet.columnNames) - console.log("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to query data, err: " + err) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string> , callback: AsyncCallback<ResultSet>): void - -Queries data from the RDB store of a remote device based on specified conditions. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | Yes| Columns to query. If this parameter is not specified, the query applies to all columns.| -| callback | AsyncCallback<[ResultSet](js-apis-data-resultset.md#resultset)> | Yes| Callback invoked to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"], - function(err, resultSet){ - if (err) { - console.info("Failed to remoteQuery, err: " + err) - return - } - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}) -``` - -### remoteQuery9+ - -remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> - -Queries data from the RDB store of a remote device based on specified conditions. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| device | string | Yes| Network ID of the remote device.| -| table | string | Yes| Name of the target table.| -| predicates | [RdbPredicates](#rdbpredicates) | Yes| Query conditions specified by the **RdbPredicates** object.| -| columns | Array<string> | No| Columns to query. If this parameter is not specified, the query applies to all columns.| - -**Return value** - -| Type | Description | -| ------------------------------------------------------------ | -------------------------------------------------------- | -| Promise<[ResultSet](js-apis-data-resultset.md#resultset)> | Promise used to return the result. If the operation is successful, a **ResultSet** object will be returned.| - -**Example** - -```js -let predicates = new data_rdb.RdbPredicates('EMPLOYEE') -predicates.greaterThan("id", 0) -let promise = rdbStore.remoteQuery("deviceId", "EMPLOYEE", predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) -promise.then((resultSet) => { - console.info("ResultSet column names: " + resultSet.columnNames) - console.info("ResultSet column count: " + resultSet.columnCount) -}).catch((err) => { - console.info("Failed to remoteQuery , err: " + err) -}) -``` - ### querySql8+ querySql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<ResultSet>):void @@ -1836,7 +1594,7 @@ promise.then((resultSet) => { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs: Array<ValueType>, callback: AsyncCallback<void>):void @@ -1865,7 +1623,7 @@ rdbStore.executeSql(SQL_CREATE_TABLE, null, function(err) { }) ``` -### executeSql +### executeSql8+ executeSql(sql: string, bindArgs?: Array<ValueType>):Promise<void> @@ -1884,7 +1642,7 @@ Executes an SQL statement that contains specified arguments but returns no value | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -1910,7 +1668,7 @@ Starts the transaction before executing an SQL statement. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1937,7 +1695,7 @@ Commits the executed SQL statements. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { rdbStore.beginTransaction() @@ -1964,7 +1722,7 @@ Rolls back the SQL statements that have been executed. ```js import featureAbility from '@ohos.ability.featureAbility' -var context = featureAbility.getContext() +let context = featureAbility.getContext() const STORE_CONFIG = { name: "RdbTest.db"} data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { try { @@ -1984,122 +1742,6 @@ data_rdb.getRdbStore(context, STORE_CONFIG, 1, async function (err, rdbStore) { }) ``` -### backup9+ - -backup(destName:string, callback: AsyncCallback<void>):void - -Backs up an RDB store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.backup("dbBackup.db", function(err) { - if (err) { - console.info('Failed to back up data, err: ' + err) - return - } - console.info('Backed up data successfully.') -}) -``` - -### backup9+ - -backup(destName:string): Promise<void> - -Backs up an RDB store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| destName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseBackup = rdbStore.backup("dbBackup.db") -promiseBackup.then(()=>{ - console.info('Backed up data successfully.') -}).catch((err)=>{ - console.info('Failed to back up data, err: ' + err) -}) -``` - -### restore9+ - -restore(srcName:string, callback: AsyncCallback<void>):void - -Restores an RDB store from a backup file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result.| - -**Example** - -```js -rdbStore.restore("dbBackup.db", function(err) { - if (err) { - console.info('Failed to restore data, err: ' + err) - return - } - console.info('Restored data successfully.') -}) -``` - -### restore9+ - -restore(srcName:string): Promise<void> - -Restores an RDB store from a backup file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| srcName | string | Yes| Name of the RDB store backup file.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| - -**Example** - -```js -let promiseRestore = rdbStore.restore("dbBackup.db") -promiseRestore.then(()=>{ - console.info('Restored data successfully.') -}).catch((err)=>{ - console.info('Failed to restore data, err: ' + err) -}) -``` - ### setDistributedTables8+ setDistributedTables(tables: Array<string>, callback: AsyncCallback<void>): void @@ -2149,7 +1791,7 @@ Sets distributed tables. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** @@ -2306,8 +1948,6 @@ on(event: 'dataChange', type: SubscribeType, observer: Callback<Array<stri Registers an observer for this RDB store. When the data in the RDB store changes, a callback is invoked to return the data changes. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2315,7 +1955,7 @@ Registers an observer for this RDB store. When the data in the RDB store changes | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| The value is'dataChange', which indicates a data change event.| -| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to register.| | observer | Callback<Array<string>> | Yes| Observer that listens for the data changes in the RDB store.| **Example** @@ -2339,8 +1979,6 @@ off(event:'dataChange', type: SubscribeType, observer: Callback<Array<stri Unregisters the observer of the specified type from the RDB store. This API uses a callback to return the result. -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** @@ -2348,7 +1986,7 @@ Unregisters the observer of the specified type from the RDB store. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | string | Yes| The value is'dataChange', which indicates a data change event.| -| type | [SubscribeType](#subscribetype8) | Yes| Type defined in **SubscribeType**.| +| type | [SubscribeType](#subscribetype8) | Yes| Subscription type to unregister.| | observer | Callback<Array<string>> | Yes| Data change observer registered.| **Example** @@ -2365,60 +2003,3 @@ try { console.log('Failed to unregister observer') } ``` - -## StoreConfig - -Defines the RDB store configuration. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Database file name.| -| encrypt9+ | boolean | No| Whether to encrypt the RDB store.
The value **true** means to encrypt the RDB store, and the value **false** means the opposite.| - -## ValueType - -Defines the data types allowed. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Type| Description| -| -------- | -------- | -| number | Number.| -| string | String.| -| boolean | Boolean.| - - -## ValuesBucket - -Defines the types of the key and value in a KV pair. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Key Type| Value Type| -| -------- | -------- | -| string | [ValueType](#valuetype)\| Uint8Array \| null | - -## SyncMode8+ - -Defines the database synchronization mode. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |----- | -| SYNC_MODE_PUSH | 0 | Data is pushed from a local device to a remote device.| -| SYNC_MODE_PULL | 1 | Data is pulled from a remote device to a local device.| - -## SubscribeType8+ - -Defines the subscription type. - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Default Value| Description| -| -------- | ----- |---- | -| SUBSCRIBE_TYPE_REMOTE | 0 | Subscribe to remote data changes.| diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md index 798ac7bba0926f47e1bc16eb6b672403bc082fa7..8cdecd1134a270075b3d4dd86a7e4e7a07fc7390 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -1,549 +1,17 @@ -# Result Set +# resultSet A result set is a set of results returned after the relational database (RDB) query APIs are called. You can use the **resultset** APIs to obtain required data. -> **NOTE** +> **NOTE**
> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore#ResultSet](js-apis-data-relationalStore.md#resultset). -## ResultSetV99+ - -Provides methods to access the result set, which is obtained by querying the RDB store. - -### Usage - -You need to obtain the **resultSetV9** instance by using [RdbStoreV9.query()](js-apis-data-rdb.md#query). - -```js -import dataRdb from '@ohos.data.rdb'; -let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -predicatesV9.equalTo("AGE", 18); -let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promise.then((resultSetV9) => { - console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount); -}); -``` - -### Attributes9+ - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -| Name | Type | Mandatory| Description | -| ------------ | ------------------- | ---- | -------------------------------- | -| columnNames | Array<string> | Yes | Names of all columns in the result set. | -| columnCount | number | Yes | Number of columns in the result set. | -| rowCount | number | Yes | Number of rows in the result set. | -| rowIndex | number | Yes | Index of the current row in the result set. | -| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. | -| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. | -| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.| -| isStarted | boolean | Yes | Whether the cursor has been moved. | -| isClosed | boolean | Yes | Whether the result set is closed. | - -### getColumnIndex9+ - -getColumnIndex(columnName: string): number - -Obtains the column index based on the column name. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ---------- | ------ | ---- | -------------------------- | -| columnName | string | Yes | Column name specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| number | Index of the column obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -resultSetV9.goToFirstRow(); -const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID")); -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### getColumnName9+ - -getColumnName(columnIndex: number): string - -Obtains the column name based on the column index. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | -------------------------- | -| columnIndex | number | Yes | Column index specified.| - -**Return value** - -| Type | Description | -| ------ | ------------------ | -| string | Column name obtained.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const id = resultSetV9.getColumnName(0); -const name = resultSetV9.getColumnName(1); -const age = resultSetV9.getColumnName(2); - ``` - -### goTo9+ - -goTo(offset:number): boolean - -Moves the cursor to the row based on the specified offset. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------------------- | -| offset | number | Yes | Offset relative to the current position.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoto.then((resultSetV9) => { - resultSetV9.goTo(1); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToRow9+ - -goToRow(position: number): boolean - -Moves the cursor to the specified row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------ | -| position | number | Yes | Position to which the cursor is to be moved.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygotorow.then((resultSetV9) => { - resultSetV9.goToRow(5); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToFirstRow9+ - -goToFirstRow(): boolean - - -Moves the cursor to the first row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoFirst.then((resultSetV9) => { - resultSetV9.goToFirstRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToLastRow9+ - -goToLastRow(): boolean - -Moves the cursor to the last row of the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoLast.then((resultSetV9) => { - resultSetV9.goToLastRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToNextRow9+ - -goToNextRow(): boolean - -Moves the cursor to the next row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoNext.then((resultSetV9) => { - resultSetV9.goToNextRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### goToPreviousRow9+ - -goToPreviousRow(): boolean - -Moves the cursor to the previous row in the result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -**Example** - - ```js -let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promisequerygoPrev.then((resultSetV9) => { - resultSetV9.goToPreviousRow(); - resultSetV9.close(); -}).catch((err) => { - console.log('query failed'); -}); - ``` - -### getBlob9+ - -getBlob(columnIndex: number): Uint8Array - -Obtains the value in the specified column in the current row as a byte array. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ---------- | -------------------------------- | -| Uint8Array | Value in the specified column as a byte array.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES")); - ``` - -### getString9+ - -getString(columnIndex: number): string - -Obtains the value in the specified column in the current row as a string. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| string | Value in the specified column as a string.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME")); - ``` - -### getLong9+ - -getLong(columnIndex: number): number - -Obtains the value in the specified column in the current row as a Long. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | -------------------------- | -| number | Value in the specified column as a Long.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE")); - ``` - -### getDouble9+ - -getDouble(columnIndex: number): number - -Obtains the value in the specified column in the current row as a double. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------ | ---------------------------- | -| number | Value in the specified column as a double.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY")); - ``` - -### isColumnNull9+ - -isColumnNull(columnIndex: number): boolean - -Checks whether the value in the specified column of the current row is null. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| ----------- | ------ | ---- | ----------------------- | -| columnIndex | number | Yes | Index of the specified column, starting from 0.| - -**Return value** - -| Type | Description | -| ------- | --------------------------------------------------------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800013 | The column value is null or the column type is incompatible. | - -**Example** - - ```js -const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES")); - ``` - -### close9+ - -close(): void - -Closes this result set. - -**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core - -**Example** - - ```js -let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE"); -let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]); -promiseClose.then((resultSetV9) => { - resultSetV9.close(); -}).catch((err) => { - console.log('Failed to close the resultset'); -}); - ``` - -**Error codes** - -For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md). - -| ID| **Error Message** | -| ------------ | ------------------------------------------------------------ | -| 14800012 | The result set is empty or the specified location is invalid. | - -## ResultSet(deprecated) +## ResultSet Provides methods to access the result set, which is obtained by querying the RDB store. -> **NOTE** -> -> This object is supported since API version 7 and deprecated since API version 9. You are advised to use [ResultSetV9](#resultsetv99). - ### Usage You need to obtain a **resultSet** object by using [RdbStore.query()](js-apis-data-rdb.md#query). @@ -559,11 +27,7 @@ promise.then((resultSet) => { }); ``` -### Attributes(deprecated) - -> **NOTE** -> -> This parameter is supported since API version 7 and is deprecated since API version 9. You are advised to use [Attributes](#attributes9). +### Attributes **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -579,29 +43,25 @@ promise.then((resultSet) => { | isStarted | boolean | Yes| Whether the cursor has been moved.| | isClosed | boolean | Yes| Whether the result set is closed.| -### getColumnIndex(deprecated) +### getColumnIndex getColumnIndex(columnName: string): number Obtains the column index based on the column name. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnIndex](#getcolumnindex9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnName | string | Yes| Column name specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnName | string | Yes| Column name specified.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Index of the column obtained.| + | Type| Description| + | -------- | -------- | + | number | Index of the column obtained.| **Example** @@ -613,29 +73,25 @@ Obtains the column index based on the column name. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### getColumnName(deprecated) +### getColumnName getColumnName(columnIndex: number): string Obtains the column name based on the column index. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnName](#getcolumnname9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Column index specified.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Column index specified.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Column name obtained.| + | Type| Description| + | -------- | -------- | + | string | Column name obtained.| **Example** @@ -645,29 +101,25 @@ Obtains the column name based on the column index. const age = resultSet.getColumnName(2); ``` -### goTo(deprecated) +### goTo goTo(offset:number): boolean Moves the cursor to the row based on the specified offset. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goTo](#goto9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| offset | number | Yes| Offset relative to the current position.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | offset | number | Yes| Offset relative to the current position.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -682,29 +134,25 @@ Moves the cursor to the row based on the specified offset. }); ``` -### goToRow(deprecated) +### goToRow goToRow(position: number): boolean Moves the cursor to the specified row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToRow](#gotorow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| position | number | Yes| Position to which the cursor is to be moved.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | position | number | Yes| Position to which the cursor is to be moved.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -719,23 +167,19 @@ Moves the cursor to the specified row in the result set. }); ``` -### goToFirstRow(deprecated) +### goToFirstRow goToFirstRow(): boolean Moves the cursor to the first row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToFirstRow](#gotofirstrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -750,23 +194,19 @@ Moves the cursor to the first row of the result set. }); ``` -### goToLastRow(deprecated) +### goToLastRow goToLastRow(): boolean Moves the cursor to the last row of the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToLastRow](#gotolastrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -781,23 +221,19 @@ Moves the cursor to the last row of the result set. }); ``` -### goToNextRow(deprecated) +### goToNextRow goToNextRow(): boolean Moves the cursor to the next row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToNextRow](#gotonextrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -812,23 +248,19 @@ Moves the cursor to the next row in the result set. }); ``` -### goToPreviousRow(deprecated) +### goToPreviousRow goToPreviousRow(): boolean Moves the cursor to the previous row in the result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToPreviousRow](#gotopreviousrow9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -843,29 +275,25 @@ Moves the cursor to the previous row in the result set. }); ``` -### getBlob(deprecated) +### getBlob getBlob(columnIndex: number): Uint8Array Obtains the value in the specified column in the current row as a byte array. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getBlob](#getblob9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| Uint8Array | Value in the specified column as a byte array.| + | Type| Description| + | -------- | -------- | + | Uint8Array | Value in the specified column as a byte array.| **Example** @@ -873,29 +301,25 @@ Obtains the value in the specified column in the current row as a byte array. const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` -### getString(deprecated) +### getString getString(columnIndex: number): string Obtains the value in the specified column in the current row as a string. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getString](#getstring9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| string | Value in the specified column as a string.| + | Type| Description| + | -------- | -------- | + | string | Value in the specified column as a string.| **Example** @@ -903,29 +327,25 @@ Obtains the value in the specified column in the current row as a string. const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` -### getLong(deprecated) +### getLong getLong(columnIndex: number): number Obtains the value in the specified column in the current row as a Long. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getLong](#getlong9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a Long.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a Long.| **Example** @@ -933,29 +353,25 @@ Obtains the value in the specified column in the current row as a Long. const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` -### getDouble(deprecated) +### getDouble getDouble(columnIndex: number): number Obtains the value in the specified column in the current row as a double. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDouble](#getdouble9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| number | Value in the specified column as a double.| + | Type| Description| + | -------- | -------- | + | number | Value in the specified column as a double.| **Example** @@ -963,29 +379,25 @@ Obtains the value in the specified column in the current row as a double. const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` -### isColumnNull(deprecated) +### isColumnNull isColumnNull(columnIndex: number): boolean Checks whether the value in the specified column of the current row is null. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isColumnNull](#iscolumnnull9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| columnIndex | number | Yes| Index of the specified column, starting from 0.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the value is null; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the value is null; returns **false** otherwise.| **Example** @@ -993,16 +405,12 @@ Checks whether the value in the specified column of the current row is null. const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` -### close(deprecated) +### close close(): void Closes this result set. -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [close](#close9). - **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** diff --git a/en/application-dev/reference/apis/js-apis-data-storage.md b/en/application-dev/reference/apis/js-apis-data-storage.md index b724dfabc1fed1e99d98ad5bba715d81d91677b8..8df3ab1e84ff92e39f31566416a34c4ffb3afa9b 100644 --- a/en/application-dev/reference/apis/js-apis-data-storage.md +++ b/en/application-dev/reference/apis/js-apis-data-storage.md @@ -1,6 +1,6 @@ -# Lightweight Storage +# @ohos.data.storage -Lightweight storage provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type. +The **DataStorage** module provides applications with data processing capability and allows applications to perform lightweight data storage and query. Data is stored in key-value (KV) pairs. Keys are of the string type, and values can be of the number, string, or Boolean type. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-defaultAppManager.md b/en/application-dev/reference/apis/js-apis-defaultAppManager.md index 28830ea0737c3243e97dd2a02256b32f54616f6d..ad8ab9f54dfd43754e6e00cdfbe5ba5c9e1d39c4 100644 --- a/en/application-dev/reference/apis/js-apis-defaultAppManager.md +++ b/en/application-dev/reference/apis/js-apis-defaultAppManager.md @@ -1,4 +1,4 @@ -# DefaultAppManager +# @ohos.bundle.defaultAppManager (Default Application Management) The **DefaultAppManager** module provides APIs to query whether the current application is the default application of a specific type. @@ -18,25 +18,25 @@ import defaultAppMgr from '@ohos.bundle.defaultAppManager'; | --------------------------------------- | ----------- | ---------------- | | ohos.permission.GET_DEFAULT_APPLICATION | system_core | Permission related to the default application.| -For details, see in [Permission Levels](../../security/accesstoken-overview.md#permission-levels). +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). ## defaultAppMgr.ApplicationType -Enumerates the application types. +Enumerates the default application types. **System capability**: SystemCapability.BundleManager.BundleFramework.DefaultApp -| Name | Type | Value | Description | -| -------- | -------- | -------------------------------------- | -------------------------------------- | -| BROWSER | string | Web Browser | Default browser. | -| IMAGE | string | Image Gallery | Default image viewer. | -| AUDIO | string | Audio Player | Default audio player. | -| VIDEO | string | Video Player | Default video player. | -| PDF | string | PDF Viewer | Default PDF reader. | -| WORD | string | Word Viewer | Default Word viewer. | -| EXCEL | string | Excel Viewer | Default Excel viewer. | -| PPT | string | PPT Viewer | Default PowerPoint viewer. | +| Name | Value| Description | +| -------- | -------------------------------------- | -------------------------------------- | +| BROWSER | "Web Browser" | Default browser. | +| IMAGE | "Image Gallery" | Default image viewer. | +| AUDIO | "Audio Player" | Default audio player. | +| VIDEO | "Video Player" | Default video player. | +| PDF | "PDF Viewer" | Default PDF reader. | +| WORD | "Word Viewer" | Default Word viewer. | +| EXCEL | "Excel Viewer" | Default Excel viewer. | +| PPT | "PPT Viewer" | Default PowerPoint viewer. | ## defaultAppMgr.isDefaultApplication @@ -58,10 +58,6 @@ Checks whether this application is the default application of a system-defined a | ------------------------- | ------------------ | | Promise\ | Promise used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** @@ -90,13 +86,9 @@ Checks whether this application is the default application of a system-defined a | type | string | Yes | Type of the target application. It must be set to a value defined by [ApplicationType](#defaultappmgrapplicationtype). | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the application is the default application, `true` is returned; otherwise, `false` is returned.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.isDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { @@ -144,7 +136,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER) .then((data) => { @@ -195,7 +187,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { @@ -246,7 +238,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.getDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, (err, data) => { if (err) { @@ -302,12 +294,12 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -316,9 +308,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -326,9 +318,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId).then((data) => { console.info('Operation successful.'); }).catch((error) => { @@ -369,13 +361,13 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -385,9 +377,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, userId, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -432,9 +424,9 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc ```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -444,9 +436,9 @@ defaultAppMgr.setDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, { }); defaultAppMgr.setDefaultApplication("image/png", { - bundleName: "com.test.app", + bundleName: "com.example.myapplication", moduleName: "module01", - abilityName: "MainAbility" + abilityName: "EntryAbility" }, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + JSON.stringify(err)); @@ -486,7 +478,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId) @@ -537,7 +529,7 @@ For details about the error codes, see [Bundle Error Codes](../errorcodes/errorc **Example** -```js +```ts import defaultAppMgr from '@ohos.bundle.defaultAppManager'; let userId = 100; defaultAppMgr.resetDefaultApplication(defaultAppMgr.ApplicationType.BROWSER, userId, (err, data) => { diff --git a/en/application-dev/reference/apis/js-apis-deque.md b/en/application-dev/reference/apis/js-apis-deque.md index 594984e1deb513a21c165c04d0d7d95a918a8766..d227b545aa9f5ad3b719b2da86800cab6ccc5084 100644 --- a/en/application-dev/reference/apis/js-apis-deque.md +++ b/en/application-dev/reference/apis/js-apis-deque.md @@ -1,7 +1,6 @@ -# Linear Container Deque +# @ohos.util.Deque (Linear Container Deque) > **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. Double-ended queue (deque) is a sequence container implemented based on the queue data structure that follows the principles of First In First Out (FIFO) and Last In First Out (LIFO). It allows insertion and removal of elements at both the ends. **Deque** can dynamically adjust the capacity based on project requirements. It doubles the capacity each time. **Deque** differs from **[Queue](js-apis-queue.md)** and **[Vector](js-apis-vector.md)** mainly in the following aspects: @@ -41,7 +40,7 @@ A constructor used to create a **Deque** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -51,11 +50,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let deque = new Deque(); -try { - let deque2 = Deque(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insertFront @@ -74,7 +68,7 @@ Inserts an element at the front of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -91,11 +85,6 @@ deque.insertFront(b); let c = {name : "Dylon", age : "13"}; deque.insertFront(c); deque.insertFront(false); -try { - deque.insertFront.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insertEnd @@ -114,7 +103,7 @@ Inserts an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -131,11 +120,6 @@ deque.insertEnd(b); let c = {name : "Dylon", age : "13"}; deque.insertEnd(c); deque.insertEnd(false); -try { - deque.insertEnd.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -160,7 +144,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -173,11 +157,6 @@ let deque = new Deque(); let result = deque.has("squirrel"); deque.insertFront("squirrel"); let result1 = deque.has("squirrel"); -try { - deque.has.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### popFirst @@ -192,11 +171,11 @@ Removes the first element of this container. | Type| Description| | -------- | -------- | -| T | Element removed.| +| T | First element removed.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -212,11 +191,6 @@ deque.insertEnd(5); deque.insertFront(2); deque.insertFront(4); let result = deque.popFirst(); -try { - deque.popFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### popLast @@ -231,11 +205,11 @@ Removes the last element of this container. | Type| Description| | -------- | -------- | -| T | Element removed.| +| T | Last element removed.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -251,16 +225,11 @@ deque.insertFront(5); deque.insertFront(2); deque.insertFront(4); let result = deque.popLast(); -try { - deque.popLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, deque?: Deque<T>) => void, +forEach(callbackFn: (value: T, index?: number, deque?: Deque<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -271,7 +240,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -284,7 +253,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -301,13 +270,6 @@ deque.insertEnd(4); deque.forEach((value, index) => { console.log("value:" + value, index); }); -try { - deque.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -326,7 +288,7 @@ Obtains the first element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -341,11 +303,6 @@ deque.insertEnd(4); deque.insertFront(5); deque.insertFront(4); let result = deque.getFirst(); -try { - deque.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -364,7 +321,7 @@ Obtains the last element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -379,11 +336,6 @@ deque.insertFront(4); deque.insertFront(5); deque.insertFront(4); let result = deque.getLast(); -try { - deque.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -402,7 +354,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -428,9 +380,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - deque[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` 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 46a110814dc474f66393135a91313ab5df03b98e..d413556b36e7e8ebaacbe053ffbe0f0c97b98019 100644 --- a/en/application-dev/reference/apis/js-apis-device-info.md +++ b/en/application-dev/reference/apis/js-apis-device-info.md @@ -1,9 +1,8 @@ -# Device Information +# @ohos.deviceInfo The **deviceInfo** module provides product information. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import 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 46c9d2e80e30fad1c21827d41de7418934f3bbdc..e8363f6203436eec807f436ca3c63c00cfc3bc74 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -1,6 +1,6 @@ -# Device Management +# @ohos.distributedHardware.deviceManager (Device Management) -The **DeviceManager** module provides APIs for distributed device management. +The **deviceManager** module provides APIs for distributed device management. System applications can call the APIs to do the following: @@ -34,10 +34,10 @@ Creates a **DeviceManager** instance. **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 the application. | +| callback | AsyncCallback<[DeviceManager](#devicemanager)> | Yes | Callback used to return the **DeviceManager** instance created.| **Error codes** @@ -85,7 +85,7 @@ Enumerates the device types. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Default Value | Description | +| Name | Value | Description | | ------------ | ---- | ---- | | SPEAKER | 0x0A | Smart speaker.| | PHONE | 0x0E | Phone. | @@ -102,7 +102,7 @@ Enumerates the device states. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Default Value | Description | +| Name | Value | Description | | ------- | ---- | --------------- | | ONLINE | 0 | The device is physically online. | | READY | 1 | The information between devices has been synchronized in the Distributed Data Service (DDS) module, and the device is ready for running distributed services.| @@ -132,7 +132,7 @@ Enumerates the device discovery modes. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Default Value | Description | +| Name | Value | Description | | --------------------- | ---- | ----- | | DISCOVER_MODE_PASSIVE | 0x55 | Passive discovery.| | DISCOVER_MODE_ACTIVE | 0xAA | Active discovery.| @@ -144,7 +144,7 @@ Enumerates the media used for device discovery. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Default Value | Description | +| Name | Value | Description | | ---- | ---- | --------- | | AUTO | 0 | Automatic. | | BLE | 1 | Bluetooth. | @@ -157,7 +157,7 @@ Enumerates the device discovery frequencies. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Default Value | Description | +| Name | Value | Description | | ---------- | ---- | ----- | | LOW | 0 | Low frequency. | | MID | 1 | Medium frequency. | @@ -171,7 +171,7 @@ Enumerates the discovery capabilities. **System capability**: SystemCapability.DistributedHardware.DeviceManager -| Name | Default Value | Description | +| Name | Value | Description | | ------------------------- | ---- | -------------- | | SUBSCRIBE_CAPABILITY_DDMP | 0 | DDMP capability. This will be deprecated later.| | SUBSCRIBE_CAPABILITY_OSD | 1 | OSD capability. | @@ -186,7 +186,7 @@ Defines the authentication parameters. | Name | Type | Mandatory | Description | | --------- | -------------------- | ---- | ---------- | | authType | number | Yes | Authentication type. | -| extraInfo | {[key:string] : any} | No | Extended field.| +| extraInfo | {[key:string] : any} | No | Extended field.| ## AuthInfo @@ -198,9 +198,9 @@ Defines authentication information. | --------- | -------------------- | ---- | ---------- | | authType | number | Yes | Authentication type. | | token | number | Yes | Authentication token. | -| extraInfo | {[key:string] : any} | No | Extended field.| +| extraInfo | {[key:string] : any} | No | Extended field.| -## PublishInfo9+
+## PublishInfo9+ Defines published device information. @@ -249,6 +249,8 @@ getTrustedDeviceListSync(): Array<DeviceInfo> Obtains all trusted devices synchronously. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -281,6 +283,8 @@ getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): voi Obtains all trusted devices. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -319,6 +323,8 @@ getTrustedDeviceList(): Promise<Array<DeviceInfo>> Obtains all trusted devices. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -351,6 +357,8 @@ getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) Obtains local device information synchronously. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -383,6 +391,8 @@ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void Obtains local device information. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -421,6 +431,8 @@ getLocalDeviceInfo(): Promise<DeviceInfo> Obtains local device information. This API uses a promise to return the result. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Return value** @@ -447,12 +459,14 @@ For details about the error codes, see [Device Management Error Codes](../errorc }); ``` -### startDeviceDiscovery8+
+### startDeviceDiscovery8+ startDeviceDiscovery(subscribeInfo: SubscribeInfo): void Starts to discover peripheral devices. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -491,12 +505,14 @@ For details about the error codes, see [Device Management Error Codes](../errorc } ``` -### startDeviceDiscovery9+
+### startDeviceDiscovery9+ startDeviceDiscovery(subscribeInfo: SubscribeInfo, filterOptions?: string): void Starts to discover peripheral devices and filters discovered devices. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -551,6 +567,8 @@ stopDeviceDiscovery(subscribeId: number): void Stops device discovery. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -578,12 +596,14 @@ For details about the error codes, see [Device Management Error Codes](../errorc } ``` -### publishDeviceDiscovery9+
+### publishDeviceDiscovery9+ publishDeviceDiscovery(publishInfo: PublishInfo): void Publishes device information for discovery purposes. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -618,13 +638,15 @@ For details about the error codes, see [Device Management Error Codes](../errorc console.error("publishDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); } ``` - -### unPublishDeviceDiscovery9+
+ +### unPublishDeviceDiscovery9+ unPublishDeviceDiscovery(publishId: number): void Stops publishing device information. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -654,10 +676,12 @@ For details about the error codes, see [Device Management Error Codes](../errorc ### authenticateDevice -authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: AsyncCallback<{deviceId: string, pinToken ?: number}>): void +authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: AsyncCallback<{deviceId: string, pinToken ?: number}>): void Authenticates a device. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -666,7 +690,7 @@ Authenticates a device. | ---------- | ---------------------------------------- | ---- | ------- | | 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.| + | callback | AsyncCallback<{deviceId: string, pinToken ?: number}> | Yes | Callback used to return the authentication result.| **Error codes** @@ -710,6 +734,8 @@ unAuthenticateDevice(deviceInfo: DeviceInfo): void Deauthenticates a device. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -738,10 +764,12 @@ For details about the error codes, see [Device Management Error Codes](../errorc ### verifyAuthInfo -verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void +verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void Verifies authentication information. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -749,7 +777,7 @@ Verifies authentication information. | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------- | | authInfo | [AuthInfo](#authinfo) | Yes | Authentication information. | - | callback | AsyncCallback<{ deviceId: string, level: number }> | Yes | Callback used to return the verification result.| + | callback | AsyncCallback<{deviceId: string, level: number}> | Yes | Callback used to return the verification result.| **Error codes** @@ -780,11 +808,13 @@ For details about the error codes, see [Device Management Error Codes](../errorc } ``` -### setUserOperation9+
+### setUserOperation9+ setUserOperation(operateAction: number, params: string): void; -Sets a user operation action. +Sets a user operation. + +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) **System capability**: SystemCapability.DistributedHardware.DeviceManager @@ -792,7 +822,7 @@ Sets a user operation action. | Name | Type | Mandatory | Description | | ------------- | --------------- | ---- | ------------------- | - | operateAction | number | Yes | User operation action. | + | operateAction | number | Yes | User operation. | | params | string | Yes | Input parameters of the user.| **Example** @@ -804,8 +834,8 @@ Sets a user operation action. 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. + operateAction = 4 - Cancel the display of the PIN input box. + operateAction = 5 - Confirm the input in the PIN input box. */ let operation = 0; this.dmInstance.setUserOperation(operation, "extra") @@ -814,12 +844,14 @@ Sets a user operation action. } ``` -### on('uiStateChange')9+
+### on('uiStateChange')9+ -on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; +on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; Subscribes to UI status changes. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -827,7 +859,7 @@ Subscribes to UI status changes. | 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. | + | callback | Callback<{ param: string}> | Yes | Callback used to return the UI status. | **Example** @@ -847,12 +879,14 @@ Subscribes to UI status changes. } ``` -### off('uiStateChange')9+
+### off('uiStateChange')9+ -off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; +off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; Unsubscribes from UI status changes. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -860,7 +894,7 @@ Unsubscribes from UI status changes. | 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.| + | callback | Callback<{ param: string}> | No | Callback used to return the UI status.| **Example** @@ -878,6 +912,8 @@ on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChange Subscribes to changes in the device state. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -905,6 +941,8 @@ off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChang Unsubscribes from changes in the device state. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -912,7 +950,7 @@ Unsubscribes from changes in the device 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.| + | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | No | Callback used to return the device information and state.| **Example** @@ -932,6 +970,8 @@ on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: Dev Subscribes to device discovery events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -939,7 +979,7 @@ Subscribes to device discovery events. | 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. | + | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | Yes | Callback used for device discovery. | **Example** @@ -959,6 +999,8 @@ off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: D Unsubscribes from device discovery events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -966,7 +1008,7 @@ Unsubscribes from device discovery events. | 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.| + | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | No | Callback used to return the device information and state.| **Example** @@ -986,6 +1028,8 @@ on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: nu Subscribes to device discovery failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -993,7 +1037,7 @@ Subscribes to device discovery failures. | 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. | + | callback | Callback<{ subscribeId: number, reason: number }> | Yes | Callback used for the device discovery failure. | **Example** @@ -1013,6 +1057,8 @@ off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: Unsubscribes from device discovery failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1020,7 +1066,7 @@ Unsubscribes from device discovery failures. | 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.| + | callback | Callback<{ subscribeId: number, reason: number }> | No | Callback used for the device discovery failure.| **Example** @@ -1034,12 +1080,14 @@ Unsubscribes from device discovery failures. } ``` -### on('publishSuccess')9+
+### on('publishSuccess')9+ on(type: 'publishSuccess', callback: Callback<{ publishId: number }>): void Subscribes to device information publication success events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1047,7 +1095,7 @@ Subscribes to device information publication success events. | 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. | + | callback | Callback<{ publishId: number }> | Yes | Callback used to return the publish ID. | **Example** @@ -1062,12 +1110,14 @@ Subscribes to device information publication success events. } ``` -### off('publishSuccess')9+
+### off('publishSuccess')9+ off(type: 'publishSuccess', callback?: Callback<{ publishId: number }>): void Unsubscribes from device information publication success events. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1075,7 +1125,7 @@ Unsubscribes from device information publication success events. | 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.| + | callback | Callback<{ publishId: number }> | No | Callback used to return the publish ID.| **Example** @@ -1089,12 +1139,14 @@ Unsubscribes from device information publication success events. } ``` -### on('publishFail')9+
+### on('publishFail')9+ on(type: 'publishFail', callback: Callback<{ publishId: number, reason: number }>): void Subscribes to device information publication failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1102,7 +1154,7 @@ Subscribes to device information publication failures. | 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. | + | callback | Callback<{ publishId: number, reason: number }> | Yes | Callback used for the publication failure. | **Example** @@ -1116,12 +1168,14 @@ Subscribes to device information publication failures. } ``` -### off('publishFail')9+
+### off('publishFail')9+ off(type: 'publishFail', callback?: Callback<{ publishId: number, reason: number }>): void Unsubscribes from device information publication failures. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1129,7 +1183,7 @@ Unsubscribes from device information publication failures. | 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.| + | callback | Callback<{ publishId: number, reason: number }> | No | Callback used for the device discovery failure.| **Example** @@ -1149,6 +1203,8 @@ on(type: 'serviceDie', callback: () => void): void Subscribes to dead events of the **DeviceManager** service. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** @@ -1176,6 +1232,8 @@ off(type: 'serviceDie', callback?: () => void): void Unsubscribes from dead events of the **DeviceManager** service. +**Required permissions**: ohos.permission.ACCESS_SERVICE_DM (available only to system applications) + **System capability**: SystemCapability.DistributedHardware.DeviceManager **Parameters** diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 935211cb5ead58fd8823c87358bafc9eebafc449..f9a998f37ca17b4d4c70342bc648ed519fbe1652 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -1,4 +1,4 @@ -# Device Usage Statistics +# @ohos.deviceUsageStatistics (Device Usage Statistics) This module provides APIs for collecting statistics on device usage. @@ -487,7 +487,7 @@ Enumerates the interval types for querying the application usage duration. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name | Default Value | Description | +| Name | Value | Description | | ------------ | ---- | ---------------------------------------- | | BY_OPTIMIZED | 0 | The system obtains the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| | BY_DAILY | 1 | The system obtains the application usage duration statistics in the specified time frame on a daily basis. | diff --git a/en/application-dev/reference/apis/js-apis-display.md b/en/application-dev/reference/apis/js-apis-display.md index 199469589d8a67a47b993eacc36eac69a25aa8c1..15f5d8bdbc7796954b7c7129f3ab43321bba5555 100644 --- a/en/application-dev/reference/apis/js-apis-display.md +++ b/en/application-dev/reference/apis/js-apis-display.md @@ -1,4 +1,5 @@ -# Display +# @ohos.display (Display) + The **Display** module provides APIs for managing displays, such as obtaining information about the default display, obtaining information about all displays, and listening for the addition and removal of displays. > **NOTE** @@ -35,10 +36,10 @@ Describes a rectangle on the display. | Name | Type| Readable| Writable| Description | | ------ | -------- | ---- | ---- | ------------------ | -| left | number | Yes | Yes | Left boundary of the rectangle.| -| top | number | Yes | Yes | Top boundary of the rectangle.| -| width | number | Yes | Yes | Width of the rectangle. | -| height | number | Yes | Yes | Height of the rectangle. | +| left | number | Yes | Yes | Left boundary of the rectangle, in pixels.| +| top | number | Yes | Yes | Top boundary of the rectangle, in pixels.| +| width | number | Yes | Yes | Width of the rectangle, in pixels. | +| height | number | Yes | Yes | Height of the rectangle, in pixels. | ## WaterfallDisplayAreaRects9+ @@ -94,7 +95,7 @@ try { displayClass = display.getDefaultDisplaySync(); } catch (exception) { console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); -}; +} ``` ## display.getAllDisplays9+ @@ -188,7 +189,7 @@ 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** @@ -204,25 +205,24 @@ For details about the error codes, see [Display Error Codes](../errorcodes/error let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); -} catch (exception) { - console.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); - return; -}; -let ret = undefined; -try { - 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."); + } + if (ret) { + console.log("There has privateWindow."); + } else if (!ret) { + console.log("There has no privateWindow."); + } } 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.error('Failed to obtain the default display object. Code: ' + JSON.stringify(exception)); } -if (ret) { - console.log("There has privateWindow."); -} else if (!ret) { - console.log("There has no privateWindow."); -}; ``` ## display.on('add'|'remove'|'change') @@ -237,7 +237,7 @@ Subscribes to display changes. | 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.| +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event that a display is disconnected.
- **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** @@ -250,7 +250,7 @@ try { display.on("add", callback); } catch (exception) { console.error('Failed to register callback. Code: ' + JSON.stringify(exception)); -}; +} ``` ## display.off('add'|'remove'|'change') @@ -265,7 +265,7 @@ Unsubscribes from display changes. | 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.| +| type | string | Yes| Event type.
- **add**, indicating the display addition event. Example: event that a display is connected.
- **remove**, indicating the display removal event. Example: event that a display is disconnected.
- **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** @@ -275,7 +275,7 @@ try { display.off("remove"); } catch (exception) { console.error('Failed to unregister callback. Code: ' + JSON.stringify(exception)); -}; +} ``` ## display.getDefaultDisplay(deprecated) @@ -405,6 +405,8 @@ Implements a **Display** instance, with properties and APIs defined. Before calling any API in **Display**, you must use [getAllDisplays()](#displaygetalldisplays9) or [getDefaultDisplaySync()](#displaygetdefaultdisplaysync9) to obtain a **Display** instance. +### Attributes + **System capability**: SystemCapability.WindowManager.WindowManager.Core | Name| Type| Readable| Writable| Description| @@ -417,9 +419,9 @@ Before calling any API in **Display**, you must use [getAllDisplays()](#displayg | 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.| -| densityPixels | number | Yes| No| Screen density of the display, in pixels.| -| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display.| +| densityDPI | number | Yes| No| Screen density of the display, that is, the number of dots per inch. Generally, the value is **160** or **480**.| +| densityPixels | number | Yes| No| Logical density of the display, which is a scaling coefficient independent of the pixel unit. Generally, the value is **1** or **3**.| +| scaledDensity | number | Yes| No| Scaling factor for fonts displayed on the display. Generally, the value is the same as that of **densityPixels**.| | xDPI | number | Yes| No| Exact physical dots per inch of the screen in the horizontal direction.| | yDPI | number | Yes| No| Exact physical dots per inch of the screen in the vertical direction.| @@ -434,7 +436,7 @@ Obtains the cutout information of the display. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| 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.| +| callback | AsyncCallback<[CutoutInfo](#cutoutinfo9)> | Yes | Callback used to return the **CutoutInfo** object.| **Error codes** @@ -450,17 +452,17 @@ For details about the error codes, see [Display Error Codes](../errorcodes/error let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); + + displayClass.getCutoutInfo((err, data) => { + if (err.code) { + console.error('Failed to get cutoutInfo. Code: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); + }); } 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. Code: ' + JSON.stringify(err)); - return; - } - console.info('Succeeded in getting cutoutInfo. data: ' + JSON.stringify(data)); -}); +} ``` ### getCutoutInfo9+ getCutoutInfo(): Promise<CutoutInfo> @@ -489,12 +491,14 @@ For details about the error codes, see [Display Error Codes](../errorcodes/error let displayClass = null; try { displayClass = display.getDefaultDisplaySync(); + + let promise = displayClass.getCutoutInfo(); + promise.then((data) => { + console.info('Succeeded in getting cutoutInfo. Data: ' + JSON.stringify(data)); + }).catch((err) => { + console.error('Failed to obtain all the display objects. Code: ' + JSON.stringify(err)); + }); } 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-distributed-account.md b/en/application-dev/reference/apis/js-apis-distributed-account.md index 4dc76cd2d39f631d74d5c51b61259bd88a1ea924..5a4a93c46fbe2492cecf4569f8e4e7db63469371 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-account.md +++ b/en/application-dev/reference/apis/js-apis-distributed-account.md @@ -1,18 +1,17 @@ -# Distributed Account Management +# @ohos.account.distributedAccount -The distributedAccount module provides basic functions for managing distributed accounts, including querying and updating account login status. +The **distributedAccount** module provides APIs for managing distributed accounts, including querying and updating account login states. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import ```js import account_distributedAccount from '@ohos.account.distributedAccount'; ``` - ## account_distributedAccount.getDistributedAccountAbility getDistributedAccountAbility(): DistributedAccountAbility @@ -25,7 +24,7 @@ Obtains a **DistributedAccountAbility** instance. | Type| Description| | -------- | -------- | - | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides methods for querying and updating the login state of a distributed account.| + | [DistributedAccountAbility](#distributedaccountability) | **DistributedAccountAbility** instance obtained. This instance provides APIs for querying and updating the login state of a distributed account.| **Example** ```js @@ -34,13 +33,88 @@ Obtains a **DistributedAccountAbility** instance. ## DistributedAccountAbility -Provides methods for querying and updating the login state of a distributed account. You must obtain a **DistributedAccountAbility** instance first. +Provides APIs for querying and updating the login state of a distributed account. You must obtain a **DistributedAccountAbility** instance first. + +### getOsAccountDistributedInfo9+ + +getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void + +Obtains distributed account information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS, ohos.permission.GET_DISTRIBUTED_ACCOUNTS, or ohos.permission.DISTRIBUTED_DATASYNC + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + try { + accountAbility.getOsAccountDistributedInfo((err, data) => { + console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }); + } catch (e) { + console.log("getOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` -### queryOsAccountDistributedInfo +### getOsAccountDistributedInfo9+ + +getOsAccountDistributedInfo(): Promise<DistributedInfo> + +Obtains distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS, ohos.permission.GET_DISTRIBUTED_ACCOUNTS, or ohos.permission.DISTRIBUTED_DATASYNC + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[DistributedInfo](#distributedinfo)> | Promise used to return the distributed account information obtained.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + try { + accountAbility.getOsAccountDistributedInfo().then((data) => { + console.log('Query account info name: ' + data.name); + console.log('Query account info id: ' + data.id); + }).catch((err) => { + console.log("getOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("getOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` +### queryOsAccountDistributedInfo(deprecated) queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void Obtains distributed account information. 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 [getOsAccountDistributedInfo](#getosaccountdistributedinfo9). **System capability**: SystemCapability.Account.OsAccount @@ -50,24 +124,28 @@ Obtains distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the distributed account information obtained.| + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the distributed account information obtained. Otherwise, **err** is an error object.| **Example** ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo((err, data) => { + accountAbility.queryOsAccountDistributedInfo((err, data) => { console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); console.log('Query account info name: ' + data.name); console.log('Query account info id: ' + data.id); }); ``` -### queryOsAccountDistributedInfo +### queryOsAccountDistributedInfo(deprecated) queryOsAccountDistributedInfo(): Promise<DistributedInfo> Obtains distributed account information. 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 [getOsAccountDistributedInfo](#getosaccountdistributedinfo9-1). + **System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS or ohos.permission.DISTRIBUTED_DATASYNC @@ -81,7 +159,7 @@ Obtains distributed account information. This API uses a promise to return the r **Example** ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); - accountAbility.queryOsAccountDistributedInfo().then((data) => { + accountAbility.queryOsAccountDistributedInfo().then((data) => { console.log('Query account info name: ' + data.name); console.log('Query account info id: ' + data.id); }).catch((err) => { @@ -89,12 +167,97 @@ Obtains distributed account information. This API uses a promise to return the r }); ``` -### updateOsAccountDistributedInfo +### setOsAccountDistributedInfo9+ + +setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void + +Sets the distributed account information. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | Invalid accountInfo. | +| 12300003 | Account not found. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + try { + accountAbility.setOsAccountDistributedInfo(accountInfo, (err) => { + console.log("setOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("setOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` + +### setOsAccountDistributedInfo9+ + +setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> + +Sets the distributed account information. This API uses a promise to return the result. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.MANAGE_DISTRIBUTED_ACCOUNTS + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information to set.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<void> | Promise that returns no value.| + +**Error codes** + +| ID| Error Message| +| -------- | ------------------- | +| 12300001 | System service exception. | +| 12300002 | invalid accountInfo. | + +**Example** + ```js + const accountAbility = account_distributedAccount.getDistributedAccountAbility(); + let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; + try { + accountAbility.setOsAccountDistributedInfo(accountInfo).then(() => { + console.log('setOsAccountDistributedInfo Success'); + }).catch((err) => { + console.log("setOsAccountDistributedInfo err: " + JSON.stringify(err)); + }); + } catch (e) { + console.log("setOsAccountDistributedInfo exception: " + JSON.stringify(e)); + } + ``` +### updateOsAccountDistributedInfo(deprecated) updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void Updates distributed account information. 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 [setOsAccountDistributedInfo](#setosaccountdistributedinfo9). + **System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -103,24 +266,26 @@ Updates distributed account information. This API uses an asynchronous callback | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| - | callback | AsyncCallback<void> | Yes| Callback invoked when the distributed account information is updated.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the distributed account information is set successfully, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** ```js const accountAbility = account_distributedAccount.getDistributedAccountAbility(); let accountInfo = {id: '12345', name: 'ZhangSan', event: 'Ohos.account.event.LOGIN'}; - accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { + accountAbility.updateOsAccountDistributedInfo(accountInfo, (err) => { console.log("queryOsAccountDistributedInfo err: " + JSON.stringify(err)); }); ``` -### updateOsAccountDistributedInfo +### updateOsAccountDistributedInfo(deprecated) updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> -Updates distributed account information. This API uses a promise to return the result. - +Updates the distributed account information. 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 [setOsAccountDistributedInfo](#setosaccountdistributedinfo9-1). **System capability**: SystemCapability.Account.OsAccount **Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS @@ -129,13 +294,13 @@ Updates distributed account information. This API uses a promise to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | accountInfo | [DistributedInfo](#distributedinfo) | Yes| Distributed account information.| + | accountInfo | [DistributedInfo](#distributedinfo) | Yes| New distributed account information.| **Return value** | Type| Description| | -------- | -------- | - | Promise<void> | Promise used to return the result.| + | Promise<void> | Promise that returns no value.| **Example** ```js @@ -147,8 +312,6 @@ Updates distributed account information. This API uses a promise to return the r console.log("updateOsAccountDistributedInfo err: " + JSON.stringify(err)); }); ``` - - ## DistributedInfo Defines distributed OS account information. @@ -157,7 +320,9 @@ Defines distributed OS account information. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| name | string | Yes| Name of a distributed account. It must be a non-null string.| -| id | string | Yes| UID of a distributed account. It must be a non-null string.| -| event | string | Yes| Login state of a distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | -| scalableData | object | No| Extended information about a distributed account. Customized information is passed in key-value pairs.
Note: This parameter is reserved and not used in query and update methods.| +| name | string | Yes| Name of the distributed account. It must be a non-null string.| +| id | string | Yes| UID of the distributed account. It must be a non-null string.| +| event | string | Yes| Login state of the distributed account. The state can be login, logout, token invalid, or logoff, which correspond to the following strings respectively:
- Ohos.account.event.LOGIN
- Ohos.account.event.LOGOUT
- Ohos.account.event.TOKEN_INVALID
- Ohos.account.event.LOGOFF | +| nickname9+ | string | No| Nickname of the distributed account. It must be a non-null string.| +| avatar9+ | string | No| Avatar of the distributed account. It must be a non-null string.| +| scalableData | object | No| Extended information about the distributed account, passed in key-value (KV) pairs.
**NOTE**
This parameter is reserved and not used in the setters and getters.| diff --git a/en/application-dev/reference/apis/js-apis-distributed-data.md b/en/application-dev/reference/apis/js-apis-distributed-data.md index b1ceeabca8640799415596532a757f67d62e92c8..772a7372c276270eaa9a2e2d63d9eec009b06e58 100644 --- a/en/application-dev/reference/apis/js-apis-distributed-data.md +++ b/en/application-dev/reference/apis/js-apis-distributed-data.md @@ -13,7 +13,9 @@ This module provides the following functions: >**NOTE**
> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- The APIs provided by this module are no longer maintained since API version 9. You are advised to use `@ohos.data.distributedKVStore`](js-apis-distributedKVStore.md). +> +>- 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 @@ -39,56 +41,28 @@ Creates a **KVManager** instance to manage KV stores. This API uses an asynchron | callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created.| **Example** +```js -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; - }); - } -} -``` - -FA model: -```js -import featureAbility from '@ohos.ability.featureAbility' -let kvManager; -let context = featureAbility.getContext() -const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); } -distributedData.createKVManager(kvManagerConfig, function (err, manager) { - if (err) { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - return; - } - console.log("Created KVManager successfully"); - kvManager = manager; -}); ``` ## distributedData.createKVManager @@ -112,52 +86,28 @@ Creates a **KVManager** instance to manage KV stores. This API uses a promise to | Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| **Example** +```js -Stage model: -```ts -import AbilityStage from '@ohos.application.Ability' let kvManager; -export default class MyAbilityStage extends AbilityStage { - onCreate() { - console.log("MyAbilityStage onCreate") - let context = this.context - const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID - } +try { + const kvManagerConfig = { + bundleName : 'com.example.datamanagertest', + userInfo : { + userId : '0', + userType : distributedData.UserType.SAME_USER_ID } - distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; - }).catch((err) => { - console.log("Failed to create KVManager: " + JSON.stringify(err)); - }); - } -} -``` - -FA model: -```js -import featureAbility from '@ohos.ability.featureAbility' -let kvManager; -let context = featureAbility.getContext() -const kvManagerConfig = { - context: context, - bundleName: 'com.example.datamanagertest', - userInfo: { - userId: '0', - userType: distributedData.UserType.SAME_USER_ID } + distributedData.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.log("Failed to create KVManager: " + JSON.stringify(err)); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); +} catch (e) { + console.log("An unexpected error occurred. Error:" + e); } -distributedData.createKVManager(kvManagerConfig).then((manager) => { - console.log("Created KVManager successfully"); - kvManager = manager; -}).catch((err) => { - console.log("Failed to create KVManager: " + JSON.stringify(err)); -}); ``` ## KVManagerConfig @@ -168,7 +118,6 @@ Provides configuration of the **KVManager** object, including the bundle name an | Name| Type| Mandatory| Description| | ----- | ------ | ------ | ------ | -| context9+ | Context | Yes| Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| | userInfo | [UserInfo](#userinfo) | Yes | User information.| | bundleName | string | Yes | Bundle name.| @@ -179,9 +128,9 @@ Defines user information. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core | Name| Type| Mandatory| Description| -| ----- | ------ | ------ | ------ | -| userId | string | Yes | User ID.| -| userType | [UserType](#usertype) | Yes | User type.| +| ----- | ------ |------ | ------ | +| userId | string | No | User ID.| +| userType | [UserType](#usertype) | No | User type.| ## UserType @@ -213,7 +162,7 @@ Creates and obtains a KV store. This API uses an asynchronous callback to return | ----- | ------ | ------ | ------ | | storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| | options | [Options](#options) | Yes | Configuration of the KV store.| -| callback | AsyncCallback<T> , <T extends [KVStore](#kvstore)>| Yes | Callback invoked to return the KV store created.| +| callback | AsyncCallback<T> | Yes | Callback invoked to return the KV store created.| **Example** @@ -500,7 +449,7 @@ Obtains the IDs of all KV stores that are created by [getKVStore()](#getkvstore) | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | appId | string | Yes | Bundle name of the app that invokes the KV store. | -| callback | AsyncCallback<string[]> | Yes |Callback invoked to return the KV store IDs obtained. | +| callback | AsyncCallback<string[]> | Yes |Callback invoked to return the KV store IDs obtained.| **Example** @@ -560,7 +509,7 @@ try { on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void -Subscribes to service status changes. This API returns the result synchronously. +Subscribes to service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -591,7 +540,7 @@ try { off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void -Unsubscribes from service status changes. This API returns the result synchronously. +Unsubscribes from service status changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore @@ -624,8 +573,8 @@ try { Provides KV store configuration. -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | +| Name | Type| Mandatory | Description | +| ----- | ------ | ------ | -------------------| | createIfMissing | boolean | No| Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | encrypt | boolean | No|Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | | backup | boolean | No|Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core | @@ -642,8 +591,8 @@ Enumerates the KV store types. | Name | Value| Description | | --- | ---- | ----------------------- | -| DEVICE_COLLABORATION | 0 | Device KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | -| SINGLE_VERSION | 1 | Single KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| DEVICE_COLLABORATION | 0 | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore | +| SINGLE_VERSION | 1 | Single KV store.
The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| | MULTI_VERSION | 2 | Multi-version KV store. This type is not supported currently.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| @@ -682,12 +631,12 @@ Defines the schema of a KV store. You can create a **Schema** object and place i **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| Name | Type| Description | -| --- | ---- | ----------------------- | -| root8+ | [FieldNode](#fieldnode8) | JSON root object.| -| indexes8+ | Array\ | String array in JSON format. | -| mode8+ | number | Schema mode. | -| skip8+ | number | Size of a skip of the schema. | +| Name | Type| Readable| Writable| Description | +| --- | ---- | ---- | ---- | ----------------------- | +| root8+ | [FieldNode](#fieldnode8) | Yes| Yes| JSON root object.| +| indexes8+ | Array\ | Yes| Yes| String array in JSON format. | +| mode8+ | number | Yes| Yes| Schema mode. | +| skip8+ | number | Yes| Yes| Size of a skip of the schema. | ### constructor8+ @@ -703,11 +652,11 @@ Represents a **Schema** instance, which provides the methods for defining the va **System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore -| Name | Type| Description | -| --- | ---- | ----------------------- | -| nullable8+ | boolean | Whether the database field can be null. | -| default8+ | string | Default value of a **FieldNode**.| -| type8+ | number | Value of the data type corresponding to the specified node.| +| Name | Type| Readable| Writable| Description | +| --- | ---- | ---- | ---- | ----------------------- | +| nullable8+ | boolean | Yes| Yes| Whether the database field can be null. | +| default8+ | string | Yes| Yes| Default value of a **FieldNode**.| +| type8+ | number | Yes| Yes| Value of the data type corresponding to the specified node.| ### constructor8+ @@ -1389,7 +1338,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| value | number\|string | Yes | Value specified.| **Return value** @@ -1424,7 +1373,7 @@ Creates a **Query** object to match the specified field whose value is greater t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| value | number\|string | Yes | Value specified.| **Return value** @@ -1459,7 +1408,7 @@ Creates a **Query** object to match the specified field whose value is less than | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | fieId | string | Yes |Field to match. It cannot contain '^'. | -| value | number\|string\|boolean | Yes | Value specified.| +| value | number\|string | Yes | Value specified.| **Return value** @@ -2160,7 +2109,6 @@ try { } ``` - ### put put(key: string, value: Uint8Array | string | number | boolean): Promise<void> @@ -2282,317 +2230,20 @@ try { } ``` -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) - -Deletes KV pairs that meet the specified conditions. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| -| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - kvStore.delete(predicates, function (err, data) { - if (err == undefined) { - console.log('delete success'); - } else { - console.log('delete fail' + err); - } - }); -} catch (e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` - -### delete9+ - -delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> - -Deletes KV pairs that meet the specified conditions. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |Conditions for deleting data. If this parameter is **null**, define the processing logic.| - - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let predicates = new dataSharePredicates.DataSharePredicates(); - let arr = ["name"]; - predicates.inKeys(arr); - kvStore.put("name", "bob").then((data) => { - console.log('put success' + JSON.stringify(data)); - kvStore.delete(predicates).then((data) => { - console.log('delete success'); - }).catch((err) => { - console.log('delete fail' + JSON.stringify(err)); - }); - }) .catch((err) => { - console.log(' put fail' + err); - }); -}catch (e) { - console.log("An unexpected error occurred. Error:" + e); -} - -``` - -### backup9+ - -backup(file:string, callback: AsyncCallback<void>):void - -Backs up an RDB store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is the error object.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.backup(file, (err, data) => { - if (err) { - console.info("backup err : " + err); - } else { - console.info("backup data : " + data); - } - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### backup9+ - -backup(file:string): Promise<void> - -Backs up an RDB store. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the RDB store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.backup(file).then((data) => { - console.info("backup data : " + data); - }).catch((err) => { - console.info("backup err : " + err); - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### restore9+ - -restore(file:string, callback: AsyncCallback<void>):void - -Restores an RDB store from a database file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.restore(file, (err, data) => { - if (err) { - console.info("restore err : " + err); - } else { - console.info("restore data : " + data); - } - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### restore9+ - -restore(file:string): Promise<void> - -Restores an RDB store from a database file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | ------------------------------------------------------------ | -| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| - -**Return value** - -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| - -**Example** - -```js -let kvStore; -let file = "BK001"; -try { - kvStore.restore(file).then((data) => { - console.info("restore data : " + data); - }).catch((err) => { - console.info("restore err : " + err); - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### deleteBackup9+ - -deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void - -Deletes a backup file. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | -| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants). | -| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | - -**Example** - -```js -let kvStore; -let files = ["BK001", "BK002"]; -try { - kvStore.deleteBackup(files, (err, data) => { - if (err) { - console.info("deleteBackup err : " + err); - } else { - console.info("deleteBackup data : " + data); - } - }); -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - -### deleteBackup9+ - -deleteBackup(files:Array<string>): Promise<Array<[string, number]>> - -Deletes a backup file. This API uses a promise to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name| Type| Mandatory| Description | -| ------ | -------- | ---- | ------------------------------------------------------------ | -| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| - -**Return value** - -| Type | Description | -| -------------------------------------------- | ----------------------------------------------- | -| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| - -**Example** - -```js -let kvStore; -let files = ["BK001", "BK002"]; -try { - kvStore.deleteBackup(files).then((data) => { - console.info("deleteBackup data : " + data); - }).catch((err) => { - console.info("deleteBackup err : " + err); - }) -} catch (e) { - console.log("An unexpected error occurred. Error : " + e); -} - -``` - ### on('dataChange') on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Subscribes to data changes of the specified type. This API returns the result synchronously. +Subscribes to data changes of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | -| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | +| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| +| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | | listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| **Example** @@ -2604,21 +2255,20 @@ kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, fun }); ``` - ### on('syncComplete') on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to synchronization complete events. This API returns the result synchronously. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return a synchronization complete event.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | **Example** @@ -2633,17 +2283,19 @@ kvStore.on('syncComplete', function (data) { off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from data changes. This API returns the result synchronously. +Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| | listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| + + **Example** ```js @@ -2665,19 +2317,19 @@ class KvstoreModel { } ``` -### off('syncComplete')9+ +### off('syncComplete')8+ off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from the synchronization complete events. This API returns the result synchronously. +Unsubscribes from synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| | syncCallback |Callback<Array<[string, number]>> | No |Callback for the synchronization complete event. | **Example** @@ -2701,7 +2353,6 @@ class KvstoreModel { } ``` - ### putBatch8+ putBatch(entries: Entry[], callback: AsyncCallback<void>): void @@ -2715,7 +2366,7 @@ Inserts KV pairs in batches to this KV store. This API uses an asynchronous call | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | entries |[Entry](#entry)[] | Yes |KV pairs to insert in batches. | -| callback |Asyncallback<void> |Yes |Callback invoked to return the result.| +| callback |AsyncCallback<void> |Yes |Callback invoked to return the result.| **Example** @@ -2803,13 +2454,11 @@ try { } ``` -### putBatch9+ - -putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void +### deleteBatch8+ -Writes data to this KV store. This API uses an asynchronous callback to return the result. +deleteBatch(keys: string[], callback: AsyncCallback<void>): void -**System API**: This is a system API. +Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core @@ -2817,94 +2466,8 @@ Writes data to this KV store. This API uses an asynchronous callback to return | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | -| callback |Asyncallback<void> |Yes |Callback invoked to return the result.| - -**Example** - -```js -let kvStore; -try { - let v8Arr = []; - let arr = new Uint8Array([4,5,6,7]); - let vb1 = {key : "name_1", value : 32} - let vb2 = {key : "name_2", value : arr}; - let vb3 = {key : "name_3", value : "lisi"}; - - v8Arr.push(vb1); - v8Arr.push(vb2); - v8Arr.push(vb3); - kvStore.putBatch(v8Arr, async function (err,data) { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('putBatch e ' + JSON.stringify(e)); -} -``` - -### putBatch9+ - -putBatch(value: Array<ValuesBucket>): Promise<void> - -Write data to this KV store. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| value |Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes |Data to write. | - -**Return value** - -| Type | Description | -| ------ | ------- | -| Promise<void> |Promise that returns no value.| - -**Example** - -```js -let kvStore; -try { - let v8Arr = []; - let arr = new Uint8Array([4,5,6,7]); - let vb1 = {key : "name_1", value : 32} - let vb2 = {key : "name_2", value : arr}; - let vb3 = {key : "name_3", value : "lisi"}; - - v8Arr.push(vb1); - v8Arr.push(vb2); - v8Arr.push(vb3); - kvStore.putBatch(v8Arr).then(async (err) => { - console.log('putBatch success'); - }).catch((err) => { - console.log('putBatch fail ' + JSON.stringify(err)); - }); -}catch(e) { - console.log('PutBatch e ' + JSON.stringify(e)); -} - -``` - -### deleteBatch8+ - -deleteBatch(keys: string[], callback: AsyncCallback<void>): void - -Deletes KV pairs in batches from this KV store. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| keys |string[] | Yes |KV pairs to delete in batches. | -| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | +| keys |string[] | Yes |KV pairs to delete in batches. | +| callback |AsyncCallback<void> | Yes |Callback invoked to return the result. | **Example** @@ -3364,12 +2927,12 @@ Defines the content of data change notifications, including inserted data, updat **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| insertEntries | [Entry](#entry)[] | Yes | Yes|Data inserted. | -| updateEntries | [Entry](#entry)[] | Yes | Yes|Data updated. | -| deleteEntries | [Entry](#entry)[] | Yes | Yes|Data deleted. | -| deviceId | string | Yes | Yes|UUID of the device. | +| Name | Type |Mandatory | Description | +| ----- | ------- | ------|------------------------ | +| insertEntries | [Entry](#entry)[] | Yes|Data inserted. | +| updateEntries | [Entry](#entry)[] | Yes|Data updated. | +| deleteEntries | [Entry](#entry)[] | Yes|Data deleted. | +| deviceId | string | Yes|UUID of the device. | ## Entry @@ -3377,10 +2940,10 @@ Defines the KV pairs stored in the KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| key | string | Yes | Yes|Key of the KV pair stored in the KV store. | -| value | [Value](#value) | Yes | Yes|Value of the KV pair stored in the KV store. | +| Name | Type |Mandatory | Description | +| ----- | ------- | ------|------------------------ | +| key | string | Yes|Key of the KV pair stored in the KV store. | +| value | [Value](#value) | Yes|Value of the KV pair stored in the KV store. | ## Value @@ -3389,10 +2952,10 @@ Defines the **value** object in a KV store. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core -| Name | Type |Readable |Writable | Description | -| ----- | ------- | -----| ------|------------------------ | -| type | [ValueType](#value) | Yes | Yes|Type of the value. | -| value | Uint8Array \| string \| number \| boolean| Yes | Yes|Value of the KV pair stored in the KV store. | +| Name | Type |Mandatory | Description | +| ----- | ------- | ------|------------------------ | +| type | [ValueType](#value) | Yes|Type of the value. | +| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. | ## ValueType @@ -3430,7 +2993,7 @@ Obtains the value of the specified key. This API uses an asynchronous callback t | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | -| callback |AsyncCallback<Uint8Array \| string \| boolean \| number>) | Yes |Callback invoked to return the value obtained. | +| callback |AsyncCallback<Uint8Array \| string \| boolean \| number> | Yes |Callback invoked to return the value obtained. | **Example** @@ -3924,85 +3487,6 @@ try { } ``` -### getResultSet9+ - -getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KvStoreResultSet>): void - -Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates | [DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let resultSet; - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.prefixKey("batch_test_string_key"); - kvStore.getResultSet(predicates, async function (err, result) { - console.log(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` -### getResultSet9+ - -getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KvStoreResultSet> - -Obtains a **KvStoreResultSet** object that matches the specified **DataSharePredicates** object. This API uses a promise to return the result. - -**System API**: This is a system API. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| predicates |[DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes |**DataSharePredicates** object to match. If this parameter is **null**, define the processing logic. | - -**Return value** - -| Type | Description | -| ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise that returns no value.| - -**Example** - -```js -import dataSharePredicates from '@ohos.data.dataSharePredicates'; -let kvStore; -try { - let resultSet; - let predicates = new dataSharePredicates.DataSharePredicates(); - predicates.prefixKey("batch_test_string_key"); - kvStore.getResultSet(predicates) .then((result) => { - console.log(' GetResultSet success'); - resultSet = result; - kvStore.closeResultSet(resultSet, function (err, data) { - console.log(' closeResultSet success'); - }) - }); -}catch(e) { - console.log('An unexpected error occurred. Error:' + e); -} -``` ### closeResultSet8+ closeResultSet(resultSet: KvStoreResultSet, callback: AsyncCallback<void>): void @@ -4265,118 +3749,105 @@ try { } ``` +### sync -### on('syncComplete')8+ -on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void +sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void + +Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). -Subscribes to synchronization complete events. This API returns the result synchronously. +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | Yes |Callback invoked to return a synchronization complete event. | +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------------------------- | +| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | +| delayMs | number | No | Allowed synchronization delay time, in ms. | **Example** ```js let kvStore; -const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; -const VALUE_TEST_FLOAT_ELEMENT = 321.12; -try { - kvStore.on('syncComplete', function (data) { - console.log('syncComplete ' + data) - }); - kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { - console.log('syncComplete put success'); - }).catch((error) => { - console.log('syncComplete put fail ' + error); - }); -}catch(e) { - console.log('syncComplete put e ' + e); -} +kvStore.sync(['deviceIds'], distributedData.SyncMode.PULL_ONLY, 1000); ``` +### on('dataChange')8+ -### off('syncComplete')8+ - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Unsubscribes from synchronization complete events. This API returns the result synchronously. +Subscribes to data changes of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event. | -| syncCallback |Callback<Array<[string, number]>> | No |Callback for the synchronization complete event. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | +| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| +| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | +| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | **Example** ```js let kvStore; -class KvstoreModel { - call(data) { - console.log("syncComplete: " + data); - } - subscribeSyncComplete() { - if (kvStore != null) { - kvStore.on('syncComplete', this.call); - } - } - unsubscribeSyncComplete() { - if (kvStore != null) { - kvStore.off('syncComplete', this.call); - } - } -} +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); ``` -### on('dataChange')9+ +### on('syncComplete')8+ -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void +on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to data changes of the specified type. This API returns the result synchronously. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | -| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | **Example** ```js let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); - +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +const VALUE_TEST_FLOAT_ELEMENT = 321.12; +try { + kvStore.on('syncComplete', function (data) { + console.log('syncComplete ' + data) + }); + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + console.log('syncComplete put success'); + }).catch((error) => { + console.log('syncComplete put fail ' + error); + }); +}catch(e) { + console.log('syncComplete put e ' + e); +} ``` -### off('dataChange')9+ +### off('dataChange')8+ off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from data changes. This API returns the result synchronously. +Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| | listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| **Example** @@ -4399,71 +3870,40 @@ class KvstoreModel { } } ``` -### sync7+ +### off('syncComplete')8+ -sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | - -**Example** - -```js -let kvStore; -kvStore.sync('deviceIds', distributedData.SyncMode.PULL_ONLY, 1000); -``` - -### sync9+ -sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void - -Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). +off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Unsubscribes from synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |List of IDs of the devices in the same networking environment to be synchronized. | -| mode |[SyncMode](#syncmode) | Yes |Synchronization mode. | -| query |[Query](#query8) | Yes |**Query** object to match. | -| delayMs |number | No |Allowed synchronization delay time, in ms. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback for a synchronization complete event. | **Example** ```js let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, mode , 1000); - }); -}catch(e) { - console.log('Sync e' + e); +class KvstoreModel { + call(data) { + console.log("syncComplete: " + data); + } + subscribeSyncComplete() { + if (kvStore != null) { + kvStore.on('syncComplete', this.call); + } + } + unsubscribeSyncComplete() { + if (kvStore != null) { + kvStore.off('syncComplete', this.call); + } + } } ``` @@ -5026,7 +4466,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | keyPrefix |string | Yes |Key prefix to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -5066,7 +4506,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and k | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** @@ -5104,7 +4544,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec | Name | Type| Mandatory | Description | | ----- | ------ | ---- | ----------------------- | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -5161,7 +4601,7 @@ Obtains a **KvStoreResultSet** object that matches the specified **Query** objec | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** @@ -5221,7 +4661,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and * | ----- | ------ | ---- | ----------------------- | | deviceId |string | Yes |ID of the target device. | | query |[Query](#query8) | Yes |**Query** object to match. | -| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)[]> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | +| callback |AsyncCallback<[KvStoreResultSet](#kvstoreresultset8)> | Yes |Callback invoked to return the **KvStoreResultSet** object obtained. | **Example** @@ -5278,7 +4718,7 @@ Obtains a **KvStoreResultSet** object that matches the specified device ID and * | Type | Description | | ------ | ------- | -|Promise<[KvStoreResultSet](#kvstoreresultset8)[]> |Promise used to return the **KvStoreResultSet** object obtained.| +|Promise<[KvStoreResultSet](#kvstoreresultset8)> |Promise used to return the **KvStoreResultSet** object obtained.| **Example** @@ -5734,62 +5174,45 @@ try { } ``` -### sync9+ +### on('dataChange')8+ -sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void -Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). - -**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC +Subscribes to data changes of the specified type. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| deviceIds |string[] | Yes |IDs of the devices to be synchronized.| -| query |[Query](#query8) | Yes | **Query** object to match.| -| delayMs |number | No |Allowed synchronization delay time, in ms. | +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | +| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| +| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | +| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | **Example** ```js let kvStore; -const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; -const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; -try { - kvStore.on('syncComplete', function (data) { - console.log('Sync dataChange'); - }); - kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err,data) { - console.log('Sync put success'); - const devices = ['deviceList']; - const mode = distributedData.SyncMode.PULL_ONLY; - const query = new distributedData.Query(); - query.prefixKey("batch_test"); - query.deviceId('localDeviceId'); - kvStore.sync(devices, query, 1000); - }); -}catch(e) { - console.log('Sync e' + e); -} +kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log("dataChange callback call data: " + JSON.stringify(data)); +}); ``` ### on('syncComplete')8+ on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void -Subscribes to synchronization complete events. This API returns the result synchronously. +Subscribes to synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback |Callback | Yes |Callback invoked to return a synchronization complete event. | +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback invoked to return a synchronization complete event. | **Example** @@ -5811,21 +5234,20 @@ try { } ``` +### off('dataChange')8+ -### off('syncComplete')8+ - -off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void +off(event:'dataChange', listener?: Callback<ChangeNotification>): void -Unsubscribes from synchronization complete events. This API returns the result synchronously. +Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| -| syncCallback |Callback9+
- -on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void - -Subscribes to data changes of the specified type. This API returns the result synchronously. - -**System capability**: SystemCapability.DistributedDataManager.KVStore.Core - -**Parameters** - -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to subscribe to. The value is **dataChange**, which indicates a data change event. | -| type |[SubscribeType](#subscribetype) | Yes |Type of data change. | -| listener |Callback<[ChangeNotification](#changenotification)> | Yes |Callback invoked to return a data change event.| - -**Example** - -```js -let kvStore; -kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { - console.log("dataChange callback call data: " + JSON.stringify(data)); -}); -``` - - -### off('dataChange')9+ +### off('syncComplete')8+ -off(event:'dataChange', listener?: Callback<ChangeNotification>): void +off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void -Unsubscribes from data changes. This API returns the result synchronously. +Unsubscribes from synchronization complete events. **System capability**: SystemCapability.DistributedDataManager.KVStore.Core **Parameters** -| Name | Type| Mandatory | Description | -| ----- | ------ | ---- | ----------------------- | -| event |string | Yes |Event to unsubscribe from. The value is **dataChange**, which indicates a data change event. | -| listener |Callback<[ChangeNotification](#changenotification)> |No |Callback for the data change event.| +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback for a synchronization complete event. | **Example** @@ -5895,16 +5291,16 @@ Unsubscribes from data changes. This API returns the result synchronously. let kvStore; class KvstoreModel { call(data) { - console.log("dataChange: " + data); + console.log("syncComplete: " + data); } - subscribeDataChange() { + subscribeSyncComplete() { if (kvStore != null) { - kvStore.on('dataChange', distributedData.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + kvStore.on('syncComplete', this.call); } } - unsubscribeDataChange() { + unsubscribeSyncComplete() { if (kvStore != null) { - kvStore.off('dataChange', this.call); + kvStore.off('syncComplete', this.call); } } } diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md new file mode 100644 index 0000000000000000000000000000000000000000..9c3e0e6c94da1406b29e69e27cb68595c2225dd4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md @@ -0,0 +1,6657 @@ +# @ohos.data.distributedKVStore (Distributed KV Store) + +The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores. + +The **distributedKVStore** module provides the following functions: + +- [KVManager](#kvmanager): provides a **KVManager** instance to obtain KV store information. +- [KVStoreResultSet](#kvstoreresultset): provides APIs for obtaining KV store result sets. +- [Query](#query): provides APIs for setting predicates and querying data using predicates. +- [SingleKVStore](#singlekvstore): provides APIs for querying data in single KV stores and synchronizing data. The single KV stores manage data without distinguishing devices. +- [DeviceKVStore](#devicekvstore): provides APIs for querying in device KV stores and synchronizing data. This class inherits from [SingleKVStore](#singlekvstore). The device KV stores manage data by device. + +> **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 distributedKVStore from '@ohos.data.distributedKVStore'; +``` + +## KVManagerConfig + +Provides the **KVManager** instance configuration, including the bundle name of the invoker and the application context. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory| Description | +| ---------- | --------------------- | ---- | ------------------------------------------------------------ | +| context | Context | Yes |Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| bundleName | string | Yes | Bundle name. | + +## Constants + +Provides constants of the distributed KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Value | Description | +| --------------------- | ------- | --------------------------------------- | +| MAX_KEY_LENGTH | 1024 | Maximum length of a key in the distributed KV store, in bytes. | +| MAX_VALUE_LENGTH | 4194303 | Maximum length of a value in the distributed KV store, in bytes.| +| MAX_KEY_LENGTH_DEVICE | 896 | Maximum length of a device key, in bytes. | +| MAX_STORE_ID_LENGTH | 128 | Maximum length of a KV store ID, in bytes. | +| MAX_QUERY_LENGTH | 512000 | Maximum query length, in bytes. | +| MAX_BATCH_SIZE | 128 | Maximum number of batch operations. | + +## ValueType + +Enumerates the data types. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| ---------- | ---------------------- | +| STRING | String. | +| INTEGER | Integer. | +| FLOAT | Float (single-precision floating point). | +| BYTE_ARRAY | Byte array.| +| BOOLEAN | Boolean. | +| DOUBLE | Double (double-precision floating point).| + +## Value + +Defines the **value** object in a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type |Mandatory | Description | +| ----- | ------- |-----|------------------------ | +| type | [ValueType](#valuetype) | Yes|Type of the value. | +| value | Uint8Array \| string \| number \| boolean| Yes|Value of the KV pair stored in the KV store. | + +## Entry + +Defines the KV pairs stored in the KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory| Description | +| ----- | --------------- | ---- | -------- | +| key | string | Yes | Key of the KV pair stored in the KV store. | +| value | [Value](#value) | Yes | Value of the KV pair stored in the KV store.| + +## ChangeNotification + +Defines the content of a data change notification, including inserted data, updated data, deleted data, and device ID. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Type | Mandatory | Description | +| ------------- | ----------------- | ---- | ------------------------ | +| insertEntries | [Entry](#entry)[] | Yes | Data inserted. | +| updateEntries | [Entry](#entry)[] | Yes | Data updated. | +| deleteEntries | [Entry](#entry)[] | Yes | Data deleted. | +| deviceId | string | Yes | UUID of the device.| + +## SyncMode + +Enumerates the synchronization modes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| --------- | ---------------------------------------------------- | +| PULL_ONLY | Pull data from the peer end to the local end only. | +| PUSH_ONLY | Push data from the local end to the peer end only. | +| PUSH_PULL | Push data from the local end to the peer end and then pull data from the peer end to the local end.| + +## SubscribeType + +Enumerates the subscription types. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| --------------------- | ---------------------------- | +| SUBSCRIBE_TYPE_LOCAL | Local data changes. | +| SUBSCRIBE_TYPE_REMOTE | Remote data changes. | +| SUBSCRIBE_TYPE_ALL | Local and remote data changes.| + +## KVStoreType + +Enumerates the distributed KV store types. + +| Name | Description | +| -------------------- | ------------------------------------------------------------ | +| DEVICE_COLLABORATION | Device KV store.
The device KV store manages data by device, which eliminates conflicts. Data can be queried by device.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| +| SINGLE_VERSION | Single KV store.
The single KV store does not differentiate data by device. If the same key is modified by different devices, the data will be overwritten.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| + +## SecurityLevel + +Enumerates the KV store security levels. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +| Name | Description | +| -------: | ------------------------------------------------------------ | +| S1 | The KV store security level is low. If data leakage occurs, minor impact will be caused on the database. For example, a KV store that contains system data such as wallpapers.| +| S2 | The KV store security level is medium. If data leakage occurs, moderate impact will be caused on the database. For example, a KV store that contains information created by users or call records, such as audio or video clips.| +| S3 | The KV store security level is high. If data leakage occurs, major impact will be caused on the database. For example, a KV store that contains information such as user fitness, health, and location data.| +| S4 | The KV store security level is critical. If data leakage occurs, severe impact will be caused on the database. For example, a KV store that contains information such as authentication credentials and financial data.| + +## Options + +Provides KV store configuration. + +| Name | Type | Mandatory| Description | +| --------------- | -------------- | ---- | -------------------------| +| createIfMissing | boolean | No | Whether to create a KV store if no database file exists. By default, a KV store is created.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| encrypt | boolean | No | Whether to encrypt database files. By default, database files are not encrypted.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| backup | boolean | No | Whether to back up database files. By default, database files are backed up.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| autoSync | boolean | No | Whether database files are automatically synchronized. By default, database files are not automatically synchronized.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core
**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC| +| kvStoreType | [KVStoreType](#kvstoretype) | No | Type of the KV store to create. By default, a device KV store is created. The device KV store stores data for multiple devices that collaborate with each other.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| securityLevel | [SecurityLevel](#securitylevel) | Yes |Security level of the KV store.
**System capability**: SystemCapability.DistributedDataManager.KVStore.Core| +| schema | [Schema](#schema) | No | Schema used to define the values stored in the KV store. By default, **schema** is not used.
**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore| + +## Schema + +Defines the schema of a KV store. You can create a **Schema** object and place it in [Options](#options) when creating or opening a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +| Name | Type | Readable| Writable| Description | +| ------- | ----------------------- | ---- | ---- | -------------------------- | +| root | [FieldNode](#fieldnode) | Yes | Yes | JSON root object. | +| indexes | Array\ | Yes | Yes | String array in JSON format.| +| mode | number | Yes | Yes | Schema mode. | +| skip | number | Yes | Yes | Size of a skip of the schema. | + +### constructor + +constructor() + +A constructor used to create a **Schema** instance. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +## FieldNode + +Represents a **Schema** instance, which provides the methods for defining the values stored in a KV store. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +| Name | Type | Readable| Writable| Description | +| -------- | ------- | ---- | ---- | ------------------------------ | +| nullable | boolean | Yes | Yes | Whether the database field can be null. | +| default | string | Yes | Yes | Default value of a **FieldNode**. | +| type | number | Yes | Yes | Value of the data type corresponding to the specified node.| + +### constructor + +constructor(name: string) + +A constructor used to create a **FieldNode** instance with a string field. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | --------------- | +| name | string | Yes | Value of **FieldNode**.| + +### appendChild + +appendChild(child: FieldNode): boolean + +Appends a child node to this **FieldNode**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ---------------- | +| child | [FieldNode](#fieldnode) | Yes | Child node to append.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +import ddm from '@ohos.data.distributedKVStore'; + +try { + let node = new ddm.FieldNode("root"); + let child1 = new ddm.FieldNode("child1"); + let child2 = new ddm.FieldNode("child2"); + let child3 = new ddm.FieldNode("child3"); + node.appendChild(child1); + node.appendChild(child2); + node.appendChild(child3); + console.log("appendNode " + JSON.stringify(node)); + child1 = null; + child2 = null; + child3 = null; + node = null; +} catch (e) { + console.log("AppendChild " + e); +} +``` + +## distributedKVStore.createKVManager + +createKVManager(config: KVManagerConfig, callback: AsyncCallback<KVManager>): void + +Creates a **KVManager** instance to manage KV stores. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ----------------------------------------------------------- | +| config | [KVManagerConfig](#kvmanagerconfig) | Yes | **KVManager** instance configuration, including the bundle name of the invoker and the context of the application.| +| callback | AsyncCallback<[KVManager](#kvmanager)> | Yes | Callback invoked to return the **KVManager** instance created. | + +**Example** + +Stage model: + +```js +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + } + try { + distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); + } catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); + } + } +} +``` + +FA model: + +```js +import featureAbility from '@ohos.ability.featureAbility' +let kvManager; +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', +} +try { + distributedKVStore.createKVManager(kvManagerConfig, function (err, manager) { + if (err) { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Created KVManager successfully"); + kvManager = manager; + }); +} catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); +} +``` + +## distributedKVStore.createKVManager + +createKVManager(config: KVManagerConfig): Promise<KVManager> + +Creates a **KVManager** instance to manage KV stores. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | --------------------------------------------------------- | +| config | [KVManagerConfig](#kvmanager) | Yes | Configuration of the **KVManager** instance, including the bundle name and user information of the caller.| + +**Return value** + +| Type | Description | +| -------------------------------------- | ------------------------------------------ | +| Promise<[KVManager](#kvmanager)> | Promise used to return the **KVManager** instance created.| + +**Example** + +Stage model: + +```js +import AbilityStage from '@ohos.application.Ability' +let kvManager; +export default class MyAbilityStage extends AbilityStage { + onCreate() { + console.log("MyAbilityStage onCreate") + let context = this.context + const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', + } + try { + distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; + }).catch((err) => { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + }); + } catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); + } + } +} +``` + +FA model: + +```js +import featureAbility from '@ohos.ability.featureAbility' +let kvManager; +let context = featureAbility.getContext() +const kvManagerConfig = { + context: context, + bundleName: 'com.example.datamanagertest', +} +try { + distributedKVStore.createKVManager(kvManagerConfig).then((manager) => { + console.log("Created KVManager successfully"); + kvManager = manager; + }).catch((err) => { + console.error(`Failed to create KVManager.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Failed to create KVManager.code is ${e.code},message is ${e.message}`); +} +``` + +## KVManager + +Provides an instance to obtain information about a distributed KV store. Before calling any API in **KVManager**, you must use [createKVManager](#distributedkvstorecreatekvmanager) to create a **KVManager** instance. + +### getKVStore + +getKVStore<T >(storeId: string, options: Options, callback: AsyncCallback<T>): void + +Creates and obtains a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| options | [Options](#options) | Yes | Configuration of the KV store to create. | +| callback | AsyncCallback<T> | Yes | Callback invoked to return the distributed single or device KV store created. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| ID| **Error Message** | +| ------------ | ------------------------------------------- | +| 15100002 | Open existed database with changed options. | +| 15100003 | Database corrupted. | + +**Example** + +```js +let kvStore; +let kvManager; +try { + const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + securityLevel: distributedKVStore.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options, function (err, store) { + if (err) { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Obtained the KVStore successfully."); + kvStore = store; + }); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### getKVStore + +getKVStore<T >(storeId: string, options: Options): Promise<T> + +Creates and obtains a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ------------------------------------------------------------ | +| storeId | string | Yes | Unique identifier of the KV store. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| options | [Options](#options) | Yes | Configuration of the distributed KV store to create. | + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise<T> | Promise used to return the distributed single or device KV store created.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| ID| **Error Message** | +| ------------ | ------------------------------------------- | +| 15100002 | Open existed database with changed options. | +| 15100003 | Database corrupted. | + +**Example** + +```js +let kvStore; +let kvManager; +try { + const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + securityLevel: distributedKVStore.SecurityLevel.S2, + }; + kvManager.getKVStore('storeId', options).then((store) => { + console.log("Obtained the KVStore successfully."); + kvStore = store; + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### closeKVStore + +closeKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void + +Closes a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +let kvManager; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options, async function (err, store) { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId', function (err, data) { + if (err != undefined) { + console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the KVStore successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### closeKVStore + +closeKVStore(appId: string, storeId: string): Promise<void> + +Closes a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to close. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise that returns no value.| + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.closeKVStore('appId', 'storeId').then(() => { + console.log('Closed the KVStore successfully.'); + }).catch((err) => { + console.error(`Fail to close KVStore.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to close KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteKVStore + +deleteKVStore(appId: string, storeId: string, callback: AsyncCallback<void>): void + +Deletes a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message**| +| ------------ | ------------ | +| 15100004 | Not found. | + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('store', options, async function (err, store) { + if (err != undefined) { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.deleteKVStore('appId', 'storeId', function (err, data) { + if (err != undefined) { + console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Deleted the KVStore successfully.`); + }); + }); +} catch (e) { + console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteKVStore + +deleteKVStore(appId: string, storeId: string): Promise<void> + +Deletes a distributed KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | ------------------------------------------------------------ | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| storeId | string | Yes | Unique identifier of the KV store to delete. The length cannot exceed [MAX_STORE_ID_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message**| +| ------------ | ------------ | +| 15100004 | Not found. | + +**Example** + +```js +let kvManager; +let kvStore; +const options = { + createIfMissing: true, + encrypt: false, + backup: false, + autoSync: true, + kvStoreType: distributedKVStore.KVStoreType.SINGLE_VERSION, + schema: '', + securityLevel: distributedKVStore.SecurityLevel.S2, +} +try { + kvManager.getKVStore('storeId', options).then(async (store) => { + console.log('Obtained the KVStore successfully.'); + kvStore = store; + kvManager.deleteKVStore('appId', 'storeId').then(() => { + console.log('Deleted the KVStore successfully.'); + }).catch((err) => { + console.error(`Fail to delete KVStore.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get KVStore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to delete KVStore.code is ${e.code},message is ${e.message}`); +} +``` + +### getAllKVStoreId + +getAllKVStoreId(appId: string, callback: AsyncCallback<string[]>): void + +Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | --------------------------------------------------- | +| appId | string | Yes | Bundle name of the app that invokes the KV store. | +| callback | AsyncCallback<string[]> | Yes | Callback invoked to return the IDs of the distributed KV stores obtained.| + +**Example** + +```js +let kvManager; +try { + kvManager.getAllKVStoreId('appId', function (err, data) { + if (err != undefined) { + console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained all KV store IDs successfully.'); + console.log(`GetAllKVStoreId size = ${data.length}`); + }); +} catch (e) { + console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); +} +``` + +### getAllKVStoreId + +getAllKVStoreId(appId: string): Promise<string[]> + +Obtains the IDs of all distributed KV stores that are created by [getKVStore](#getkvstore) and have not been deleted by [deleteKVStore](#deletekvstore). This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| appId | string | Yes | Bundle name of the app that invokes the KV store.| + +**Return value** + +| Type | Description | +| ----------------------- | ------------------------------------------------------ | +| Promise<string[]> | Promise used to return the IDs of the distributed KV stores obtained.| + +**Example** + +```js +let kvManager; +try { + console.log('GetAllKVStoreId'); + kvManager.getAllKVStoreId('appId').then((data) => { + console.log('Obtained all KV store IDs successfully.'); + console.log(`GetAllKVStoreId size = ${data.length}`); + }).catch((err) => { + console.error(`Fail to get AllKVStoreId.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get AllKVStoreId.code is ${e.code},message is ${e.message}`); +} +``` + +### on('distributedDataServiceDie') + +on(event: 'distributedDataServiceDie', deathCallback: Callback<void>): void + +Subscribes to service status changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ------------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvManager; +try { + console.log('KVManagerOn'); + const deathCallback = function () { + console.log('death callback call'); + } + kvManager.on('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### off('distributedDataServiceDie') + +off(event: 'distributedDataServiceDie', deathCallback?: Callback<void>): void + +Unsubscribes from service status changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------- | -------------------- | ---- | ------------------------------------------------------------ | +| event | string | Yes | Event to unsubscribe from. The value is **distributedDataServiceDie**, which indicates a service status change event.| +| deathCallback | Callback<void> | No | Callback for the service status change event. | + +**Example** + +```js +let kvManager; +try { + console.log('KVManagerOff'); + const deathCallback = function () { + console.log('death callback call'); + } + kvManager.off('distributedDataServiceDie', deathCallback); +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +## KVStoreResultSet + +Provides APIs for obtaining the distributed KV store result sets. + +Before calling any API in **KVStoreResultSet**, you must use **[getKVStore](#getkvstore)** to construct a **SingleKVStore** or **DeviceKVStore** instance. + +### getCount + +getCount(): number + +Obtains the total number of rows in the result set. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Total number of rows obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const count = resultSet.getCount(); + console.log("getCount succeed:" + count); +} catch (e) { + console.log("getCount failed: " + e); +} +``` + +### getPosition + +getPosition(): number + +Obtains the current data read position (position from which data is read) in the result set. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Current data read position obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const position = resultSet.getPosition(); + console.log("getPosition succeed:" + position); +} catch (e) { + console.log("getPosition failed: " + e); +} +``` + +### moveToFirst + +moveToFirst(): boolean + +Moves the data read position to the first row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved1 = resultSet.moveToFirst(); + console.log("moveToFirst succeed: " + moved1); +} catch (e) { + console.log("moveToFirst failed " + e); +} +``` + +### moveToLast + +moveToLast(): boolean + +Moves the data read position to the last row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved2 = resultSet.moveToLast(); + console.log("moveToLast succeed:" + moved2); +} catch (e) { + console.log("moveToLast failed: " + e); +} +``` + +### moveToNext + +moveToNext(): boolean + +Moves the data read position to the next row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved3 = resultSet.moveToNext(); + console.log("moveToNext succeed: " + moved3); +} catch (e) { + console.log("moveToNext failed: " + e); +} +``` + +### moveToPrevious + +moveToPrevious(): boolean + +Moves the data read position to the previous row. If the result set is empty, **false** will be returned. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const moved4 = resultSet.moveToPrevious(); + console.log("moveToPrevious succeed:" + moved4); +} catch (e) { + console.log("moveToPrevious failed: " + e); +} +``` + +### move + +move(offset: number): boolean + +Moves the data read position with the specified offset from the current position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| offset | number | Yes | Offset to move the data read position. A negative value means to move backward, and a positive value means to move forward.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + const moved5 = resultSet.move(1); + console.log(`Succeeded in moving.moved5 = ${moved5}`); +} catch (e) { + console.log(`Fail to move.code is ${e.code},message is ${e.message}`); +} +``` + +### moveToPosition + +moveToPosition(position: number): boolean + +Moves the data read position from 0 to an absolute position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | -------------- | +| position | number | Yes | Absolute position to move to.| + +**Return value** + +| Type | Description | +| ------- | ----------------------------------------------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + const moved6 = resultSet.moveToPosition(1); + console.log(`Succeeded in moving to position.moved6=${moved6}`); +} catch (e) { + console.error(`Fail to move to position.code is ${e.code},message is ${e.message}`); +} +``` + +### isFirst + +isFirst(): boolean + +Checks whether the data read position is the first row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the first row is being read; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isfirst = resultSet.isFirst(); + console.log("Check isFirst succeed:" + isfirst); +} catch (e) { + console.log("Check isFirst failed: " + e); +} +``` + +### isLast + +isLast(): boolean + +Checks whether the data read position is the last row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the last row is being read; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const islast = resultSet.isLast(); + console.log("Check isLast succeed: " + islast); +} catch (e) { + console.log("Check isLast failed: " + e); +} +``` + +### isBeforeFirst + +isBeforeFirst(): boolean + +Checks whether the data read position is before the first row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the data read position is before the first row; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isbeforefirst = resultSet.isBeforeFirst(); + console.log("Check isBeforeFirst succeed: " + isbeforefirst); +} catch (e) { + console.log("Check isBeforeFirst failed: " + e); +} +``` + +### isAfterLast + +isAfterLast(): boolean + +Checks whether the data read position is after the last row. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the data read position is after the last row; returns **false** otherwise.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const isafterlast = resultSet.isAfterLast(); + console.log("Check isAfterLast succeed:" + isafterlast); +} catch (e) { + console.log("Check isAfterLast failed: " + e); +} +``` + +### getEntry + +getEntry(): Entry + +Obtains the KV pair from the current position. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| --------------- | ------------ | +| [Entry](#entry) | KV pair obtained.| + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('getResultSet succeed.'); + resultSet = result; + }).catch((err) => { + console.log('getResultSet failed: ' + err); + }); + const entry = resultSet.getEntry(); + console.log("getEntry succeed:" + JSON.stringify(entry)); +} catch (e) { + console.log("getEntry failed: " + e); +} +``` + +## Query + +Provides methods to create a **Query** object, which defines different data query criteria. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +### constructor + +constructor() + +A constructor used to create a **Schema** instance. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +### reset + +reset(): Query + +Resets the **Query** object. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------------- | +| [Query](query) | **Query** object reset.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.equalTo("key", "value"); + console.log("query is " + query.getSqlLike()); + query.reset(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("simply calls should be ok :" + e); +} +``` + +### equalTo + +equalTo(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is equal to the given value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.equalTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.ode is ${e.code},message is ${e.message}`); +} +``` + +### notEqualTo + +notEqualTo(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is not equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### greaterThan + +greaterThan(field: string, value: number|string|boolean): Query + +Creates a **Query** object to match the specified field whose value is greater than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string\|boolean | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.greaterThan("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### lessThan + +lessThan(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is less than the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.lessThan("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### greaterThanOrEqualTo + +greaterThanOrEqualTo(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is greater than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.greaterThanOrEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### lessThanOrEqualTo + +lessThanOrEqualTo(field: string, value: number|string): Query + +Creates a **Query** object to match the specified field whose value is less than or equal to the specified value. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| fieId | string | Yes |Field to match. It cannot contain '^'. | +| value | number\|string | Yes | Value specified.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.lessThanOrEqualTo("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### isNull + +isNull(field: string): Query + +Creates a **Query** object to match the specified field whose value is **null**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.isNull("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### inNumber + +inNumber(field: string, valueList: number[]): Query + +Creates a **Query** object to match the specified field whose value is within the specified list of numbers. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | number[] | Yes | List of numbers. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.inNumber("field", [0, 1]); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### inString + +inString(field: string, valueList: string[]): Query + +Creates a **Query** object to match the specified field whose value is within the specified list of strings. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | string[] | Yes | List of strings. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.inString("field", ['test1', 'test2']); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### notInNumber + +notInNumber(field: string, valueList: number[]): Query + +Creates a **Query** object to match the specified field whose value is not within the specified list of numbers. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | number[] | Yes | List of numbers. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notInNumber("field", [0, 1]); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### notInString + +notInString(field: string, valueList: string[]): Query + +Creates a **Query** object to match the specified field whose value is not within the specified list of strings. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| valueList | string[] | Yes | List of strings. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notInString("field", ['test1', 'test2']); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### like + +like(field: string, value: string): Query + +Creates a **Query** object to match the specified field whose value is similar to the specified string. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| value | string | Yes | String specified. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.like("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### unlike + +unlike(field: string, value: string): Query + +Creates a **Query** object to match the specified field whose value is not similar to the specified string. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| +| value | string | Yes | String specified. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.unlike("field", "value"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### and + +and(): Query + +Creates a **Query** object with the AND condition. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | -------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value1"); + query.and(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### or + +or(): Query + +Creates a **Query** object with the OR condition. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | -------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value1"); + query.or(); + query.notEqualTo("field", "value2"); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### orderByAsc + +orderByAsc(field: string): Query + +Creates a **Query** object to sort the query results in ascending order. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.orderByAsc("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### orderByDesc + +orderByDesc(field: string): Query + +Creates a **Query** object to sort the query results in descending order. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.orderByDesc("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### limit + +limit(total: number, offset: number): Query + +Creates a **Query** object to specify the number of results and where to start. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| total | number | Yes | Number of results to query.| +| offset | number | Yes | Start position for query. | + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +let total = 10; +let offset = 1; +try { + let query = new distributedKVStore.Query(); + query.notEqualTo("field", "value"); + query.limit(total, offset); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### isNotNull + +isNotNull(field: string): Query + +Creates a **Query** object to match the specified field whose value is not **null**. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ----------------------------- | +| fieId | string | Yes | Field to match. It cannot contain '^'.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.isNotNull("field"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### beginGroup + +beginGroup(): Query + +Creates a **Query** object for a query condition group with a left parenthesis. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### endGroup + +endGroup(): Query + +Creates a **Query** object for a query condition group with a right parenthesis. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.beginGroup(); + query.isNotNull("field"); + query.endGroup(); + console.log("query is " + query.getSqlLike()); + query = null; +} catch (e) { + console.log("duplicated calls should be ok :" + e); +} +``` + +### prefixKey + +prefixKey(prefix: string): Query + +Creates a **Query** object with a specified key prefix. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| prefix | string | Yes | Key prefix.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.prefixKey("$.name"); + query.prefixKey("0"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### setSuggestIndex + +setSuggestIndex(index: string): Query + +Creates a **Query** object with an index preferentially used for query. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------ | +| index | string | Yes | Index preferentially used for query.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.setSuggestIndex("$.name"); + query.setSuggestIndex("0"); + console.log(`query is ${query.getSqlLike()}`); + query = null; +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### deviceId + +deviceId(deviceId:string):Query + +Creates a **Query** object with the device ID as the key prefix. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ------------------ | +| deviceId | string | Yes | Device ID.| + +**Return value** + +| Type | Description | +| -------------- | --------------- | +| [Query](query) | **Query** object created.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + query.deviceId("deviceId"); + console.log(`query is ${query.getSqlLike()}`); +} catch (e) { + console.error(`duplicated calls should be ok.code is ${e.code},message is ${e.message}`); +} +``` + +### getSqlLike + +getSqlLike():string + +Obtains the query statement of the **Query** object. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------ | ------------------------------------ | +| string | Returns the query statement obtained.| + +**Example** + +```js +try { + let query = new distributedKVStore.Query(); + let sql1 = query.getSqlLike(); + console.log(`GetSqlLike sql= ${sql1}`); +} catch (e) { + console.log("duplicated calls should be ok : " + e); +} +``` + +## SingleKVStore + +Implements data management in a single KV store, such as adding data, deleting data, and subscribing to data changes or data synchronization completion. + +Before calling any method in **SingleKVStore**, you must use [getKVStore](#getkvstore) to obtain a **SingleKVStore** instance. + +### put + +put(key: string, value: Uint8Array | string | number | boolean, callback: AsyncCallback<void>): void + +Adds a KV pair of the specified type to this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | +| callback | AsyncCallback<void> | Yes |Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### put + +put(key: string, value: Uint8Array | string | number | boolean): Promise<void> + +Adds a KV pair of the specified type to this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| key | string | Yes |Key of the KV pair to add. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| value | Uint8Array \| string \| number \| boolean | Yes |Value of the KV pair to add. The value type can be Uint8Array, number, string, or boolean. A value of the Uint8Array or string type cannot exceed [MAX_VALUE_LENGTH](#constants). | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### putBatch + +putBatch(entries: Entry[], callback: AsyncCallback<void>): void + +Batch inserts KV pairs to this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------ | +| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### putBatch + +putBatch(entries: Entry[]): Promise<void> + +Batch inserts KV pairs to this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------- | ---- | ------------------------ | +| entries | [Entry](#entry)[] | Yes | KV pairs to insert in batches.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### putBatch + +putBatch(value: Array<ValuesBucket>, callback: AsyncCallback<void>): void + +Writes data to this single KV store. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------ | +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let v8Arr = []; + let arr = new Uint8Array([4, 5, 6, 7]); + let vb1 = { key: "name_1", value: 32 } + let vb2 = { key: "name_2", value: arr }; + let vb3 = { key: "name_3", value: "lisi" }; + + v8Arr.push(vb1); + v8Arr.push(vb2); + v8Arr.push(vb3); + kvStore.putBatch(v8Arr, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + }) +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### putBatch + +putBatch(value: Array<ValuesBucket>): Promise<void> + +Write data to this KV store. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------ | +| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write. | + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let v8Arr = []; + let arr = new Uint8Array([4, 5, 6, 7]); + let vb1 = { key: "name_1", value: 32 } + let vb2 = { key: "name_2", value: arr }; + let vb3 = { key: "name_3", value: "lisi" }; + + v8Arr.push(vb1); + v8Arr.push(vb2); + v8Arr.push(vb3); + kvStore.putBatch(v8Arr).then(async (data) => { + console.log(`Batch put data successfully.`); + }).catch((err) => { + console.error(`putBatch fail.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`putBatch fail.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(key: string, callback: AsyncCallback<void>): void + +Deletes a KV pair from this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + kvStore.delete(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Deleted data successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(key: string): Promise<void> + +Deletes a KV pair from this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully: ${data}`); + kvStore.delete(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<void>) + +Deletes KV pairs from this KV store. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + kvStore.delete(predicates, function (err, data) { + if (err == undefined) { + console.log('Deleted data successfully.'); + } else { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### delete + +delete(predicates: dataSharePredicates.DataSharePredicates): Promise<void> + +Deletes KV pairs from this KV store. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the KV pairs to delete. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let arr = ["name"]; + predicates.inKeys(arr); + kvStore.put("name", "bob").then((data) => { + console.log(`Put data successfully: ${data}`); + kvStore.delete(predicates).then((data) => { + console.log('Deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBatch + +deleteBatch(keys: string[], callback: AsyncCallback<void>): void + +Batch deletes KV pairs from this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| keys | string[] | Yes | KV pairs to delete in batches.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + keys.push(key + i); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.deleteBatch(keys, async function (err, data) { + if (err != undefined) { + console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch deleted data successfully.'); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBatch + +deleteBatch(keys: string[]): Promise<void> + +Batch deletes KV pairs from this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------ | +| keys | string[] | Yes | KV pairs to delete in batches.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + let keys = []; + for (var i = 0; i < 5; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + keys.push(key + i); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (data) => { + console.log('Batch put data successfully.'); + kvStore.deleteBatch(keys).then((err) => { + console.log('Batch deleted data successfully.'); + }).catch((err) => { + console.error(`Fail to delete Batch.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### removeDeviceData + +removeDeviceData(deviceId: string, callback: AsyncCallback<void>): void + +Deletes data of a device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| deviceId | string | Yes | ID of the target device.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + console.log('Put data successfully.'); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid, async function (err, data) { + if (err == undefined) { + console.log('Removed device data successfully.'); + } else { + console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + kvStore.get(KEY_TEST_STRING_ELEMENT, async function (err, data) { + console.log('Obtained data successfully.'); + }); + } + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`) +} +``` + +### removeDeviceData + +removeDeviceData(deviceId: string): Promise<void> + +Deletes data of a device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ---------------------- | +| deviceId | string | Yes | ID of the target device.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-001'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((err) => { + console.log('Put data successfully.'); + }).catch((err) => { + console.error(`Fail to put data.code is ${err.code},message is ${err.message} `); + }); + const deviceid = 'no_exist_device_id'; + kvStore.removeDeviceData(deviceid).then((err) => { + console.log('Removed device data successfully.'); + }).catch((err) => { + console.error(`Fail to remove device data.code is ${err.code},message is ${err.message} `); + }); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Obtained data successfully.'); + }).catch((err) => { + console.error(`Fail to get data.code is ${err.code},message is ${err.message} `); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`) +} +``` + +### get + +get(key: string, callback: AsyncCallback): void + +Obtains the value of the specified key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| key |string | Yes |Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants). | +| callback |AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes |Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Obtained data successfully. data=${data}`); + }); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(key: string): Promise<boolean | string| number | Uint8Array> + +Obtains the value of the specified key. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------ | ------- | +|Promise<Uint8Array \| string \| boolean \| number> |Promise used to return the value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log(`Obtained data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------- | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains the KV pairs that match the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ----------------------------------------------- | +| query | [Query](query) | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query): Promise<Entry[]> + +Obtains the KV pairs that match the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | -------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a result set with the specified prefix from this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getResultSet('batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a result set with the specified prefix from this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(query: Query, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------------- | ---- | --------------------------------------------------------- | +| query | Query | Yes | **Query** object to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### closeResultSet + +closeResultSet(resultSet: KVStoreResultSet, callback: AsyncCallback<void>): void + +Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------- | ---- | ---------------------------------- | +| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err == undefined) { + console.log('Closed the result set successfully'); + } else { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### closeResultSet + +closeResultSet(resultSet: KVStoreResultSet): Promise<void> + +Closes the **KVStoreResultSet** object returned by [SingleKvStore.getResultSet](#getresultset-1). This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------- | ---- | ---------------------------------- | +| resultSet | [KVStoreResultSet](#kvstoreresultset) | Yes | **KVStoreResultSet** object to close.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + let resultSet = null; + kvStore.closeResultSet(resultSet).then(() => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query, callback: AsyncCallback<number>): void + +Obtains the number of results that matches the specified **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------- | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set size successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query): Promise<number> + +Obtains the number of results that matches the specified **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| --------------------- | ----------------------------------------------- | +| Promise<number> | Promise used to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('Obtained the result set size successfully'); + }).catch((err) => { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### backup + +backup(file:string, callback: AsyncCallback<void>):void + +Backs up a distributed KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file, (err, data) => { + if (err) { + console.error(`Fail to backup.code is ${err.code},message is ${err.message} `); + } else { + console.info(`Backed up data successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### backup + +backup(file:string): Promise<void> + +Backs up an RDB store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the KV store. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.backup(file).then((data) => { + console.info(`Backed up data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to backup.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### restore + +restore(file:string, callback: AsyncCallback<void>):void + +Restores a distributed KV store from a database file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file, (err, data) => { + if (err) { + console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + } else { + console.info(`Restored data successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### restore + +restore(file:string): Promise<void> + +Restores a distributed KV store from a database file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| file | string | Yes | Name of the database file. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +let file = "BK001"; +try { + kvStore.restore(file).then((data) => { + console.info(`Restored data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to restore.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBackup + +deleteBackup(files:Array<string>, callback: AsyncCallback<Array<[string, number]>>):void + +Deletes a backup file. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<Array<[string, number]>> | Yes | Callback invoked to return the name of the backup file deleted and the operation result. | + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files, (err, data) => { + if (err) { + console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + } else { + console.info(`Deleted the backup file successfully. data=${data}`); + } + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### deleteBackup + +deleteBackup(files:Array<string>): Promise<Array<[string, number]>> + +Deletes a backup file. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ------------------------------------------------------------ | +| files | Array<string> | Yes | Name of the backup file to delete. The value cannot be empty or exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------------------------------------- | ----------------------------------------------- | +| Promise<Array<[string, number]>> | Promise used to return the name of the backup file deleted and the operation result.| + +**Example** + +```js +let kvStore; +let files = ["BK001", "BK002"]; +try { + kvStore.deleteBackup(files).then((data) => { + console.info(`Deleted the backup file successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to delete Backup.code is ${err.code},message is ${err.message}`); + }) +} catch (e) { + console.log(`An unexpected error occurred.code is ${e.code},message is ${e.message}`); +} +``` + +### startTransaction + +startTransaction(callback: AsyncCallback<void>): void + +Starts the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +function putBatchString(len, prefix) { + let entries = []; + for (var i = 0; i < len; i++) { + var entry = { + key: prefix + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + return entries; +} + +try { + var count = 0; + kvStore.on('dataChange', 0, function (data) { + console.log(`startTransaction 0 ${data}`); + count++; + }); + kvStore.startTransaction(async function (err, data) { + if (err != undefined) { + console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Started the transaction successfully.'); + let entries = putBatchString(10, 'batch_test_string_key'); + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + }); + }); +} catch (e) { + console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); +} +``` + +### startTransaction + +startTransaction(): Promise<void> + +Starts the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var count = 0; + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_ALL, function (data) { + console.log(`startTransaction 0 ${data}`); + count++; + }); + kvStore.startTransaction().then(async (err) => { + console.log('Started the transaction successfully.'); + }).catch((err) => { + console.error(`Fail to start Transaction.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to start Transaction.code is ${e.code},message is ${e.message}`); +} +``` + +### commit + +commit(callback: AsyncCallback<void>): void + +Commits the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.commit(function (err, data) { + if (err == undefined) { + console.log('Committed the transaction successfully.'); + } else { + console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### commit + +commit(): Promise<void> + +Commits the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.commit().then(async (err) => { + console.log('Committed the transaction successfully.'); + }).catch((err) => { + console.error(`Fail to commit.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.ode is ${e.code},message is ${e.message}`); +} +``` + +### rollback + +rollback(callback: AsyncCallback<void>): void + +Rolls back the transaction in this single KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.rollback(function (err,data) { + if (err == undefined) { + console.log('Rolled back the transaction successfully'); + } else { + console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + } + }); +}catch(e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### rollback + +rollback(): Promise<void> + +Rolls back the transaction in this single KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.rollback().then(async (err) => { + console.log('Rolled back the transaction successfully'); + }).catch((err) => { + console.error(`Fail to rollback.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### enableSync + +enableSync(enabled: boolean, callback: AsyncCallback<void>): void + +Sets data synchronization, which can be enabled or disabled. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | --------------------------------------------------------- | +| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + kvStore.enableSync(true, function (err, data) { + if (err == undefined) { + console.log('Enabled sync successfully.'); + } else { + console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + } + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### enableSync + +enableSync(enabled: boolean): Promise<void> + +Sets data synchronization, which can be enabled or disabled. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | --------------------------------------------------------- | +| enabled | boolean | Yes | Whether to enable data synchronization. The value **true** means to enable data synchronization, and **false** means the opposite.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + kvStore.enableSync(true).then((err) => { + console.log('Enabled sync successfully.'); + }).catch((err) => { + console.error(`Fail to enable sync.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncRange + +setSyncRange(localLabels: string[], remoteSupportLabels: string[], callback: AsyncCallback<void>): void + +Sets the data synchronization range. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------- | ------------------------- | ---- | -------------------------------- | +| localLabels | string[] | Yes | Synchronization labels set for the local device. | +| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels, function (err, data) { + if (err != undefined) { + console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Set syncRange successfully.'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncRange + +setSyncRange(localLabels: string[], remoteSupportLabels: string[]): Promise<void> + +Sets the data synchronization range. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------------------- | -------- | ---- | -------------------------------- | +| localLabels | string[] | Yes | Synchronization labels set for the local device. | +| remoteSupportLabels | string[] | Yes | Synchronization labels set for remote devices.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + const localLabels = ['A', 'B']; + const remoteSupportLabels = ['C', 'D']; + kvStore.setSyncRange(localLabels, remoteSupportLabels).then((err) => { + console.log('Set syncRange successfully.'); + }).catch((err) => { + console.error(`Fail to set syncRange.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncParam + +setSyncParam(defaultAllowedDelayMs: number, callback: AsyncCallback<void>): void + +Sets the default delay allowed for KV store synchronization. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------- | ------------------------- | ---- | -------------------------------------------- | +| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | + +**Example** + +```js +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs, function (err, data) { + if (err != undefined) { + console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Set syncParam successfully'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### setSyncParam + +setSyncParam(defaultAllowedDelayMs: number): Promise<void> + +Sets the default delay allowed for KV store synchronization. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------------------- | -------- | ---- | -------------------------------------------- | +| defaultAllowedDelayMs | number | Yes | Default delay allowed for database synchronization, in ms.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let kvStore; +try { + const defaultAllowedDelayMs = 500; + kvStore.setSyncParam(defaultAllowedDelayMs).then((err) => { + console.log('Set syncParam successfully'); + }).catch((err) => { + console.error(`Fail to set syncParam.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### sync + +sync(deviceIds: string[], mode: SyncMode, delayMs?: number): void + +Synchronizes the KV store manually. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------------------------- | +| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | +| delayMs | number | No | Allowed synchronization delay time, in ms. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | + +**Example** + +```js +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + const devices = ['deviceList']; + const mode = distributedKVStore.SyncMode.PULL_ONLY; + kvStore.sync(devices, mode, 1000); + }); +} catch (e) { + console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); +} +``` + +### sync + +sync(deviceIds: string[], query: Query, mode: SyncMode, delayMs?: number): void + +Synchronizes the KV store manually. This API returns the result synchronously. For details about the synchronization modes of the distributed data service, see [Distributed Data Service Overview](../../database/database-mdds-overview.md). + +**Required permissions**: ohos.permission.DISTRIBUTED_DATASYNC + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------------------------- | +| deviceIds | string[] | Yes | List of IDs of the devices in the same networking environment to be synchronized.| +| mode | [SyncMode](#syncmode) | Yes | Synchronization mode. | +| query | [Query](query) | Yes | **Query** object to match. | +| delayMs | number | No | Allowed synchronization delay time, in ms. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | ------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | + +**Example** + +```js +let kvStore; +const KEY_TEST_SYNC_ELEMENT = 'key_test_sync'; +const VALUE_TEST_SYNC_ELEMENT = 'value-string-001'; +try { + kvStore.on('syncComplete', function (data) { + console.log('Sync dataChange'); + }); + kvStore.put(KEY_TEST_SYNC_ELEMENT + 'testSync101', VALUE_TEST_SYNC_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to sync.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + const devices = ['deviceList']; + const mode = distributedKVStore.SyncMode.PULL_ONLY; + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + query.deviceId('localDeviceId'); + kvStore.sync(devices, query, mode, 1000); + }); +} catch (e) { + console.error(`Fail to sync.code is ${e.code},message is ${e.message}`); +} +``` + +### on('dataChange') + +on(event: 'dataChange', type: SubscribeType, listener: Callback<ChangeNotification>): void + +Subscribes to data changes of the specified type. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------------------------------------------- | +| event | string | Yes | Event to subscribe to. The value is **dataChange**, which indicates a data change event.| +| type | [SubscribeType](#subscribetype) | Yes | Type of data change. | +| listener | Callback<[ChangeNotification](#changenotification)> | Yes | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100001 | Over max subscribe limits. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_LOCAL, function (data) { + console.log(`dataChange callback call data: ${data}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### on('syncComplete') + +on(event: 'syncComplete', syncCallback: Callback<Array<[string, number]>>): void + +Subscribes to synchronization complete events. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ------------------------------------------------------ | +| event | string | Yes | Event to subscribe to. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | Yes | Callback used to return the synchronization result. | + +**Example** + +```js +let kvStore; +const KEY_TEST_FLOAT_ELEMENT = 'key_test_float'; +const VALUE_TEST_FLOAT_ELEMENT = 321.12; +try { + kvStore.on('syncComplete', function (data) { + console.log(`syncComplete ${data}`); + }); + kvStore.put(KEY_TEST_FLOAT_ELEMENT, VALUE_TEST_FLOAT_ELEMENT).then((data) => { + console.log('Put data successfully.'); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to subscribe syncComplete.code is ${e.code},message is ${e.message}`); +} +``` + +### off('dataChange') + +off(event:'dataChange', listener?: Callback<ChangeNotification>): void + +Unsubscribes from data changes. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | -------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **dataChange**, which indicates a data change event.| +| listener | Callback<[ChangeNotification](#changenotification)> | No | Callback invoked to return the result. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +class KvstoreModel { + call(data) { + console.log(`dataChange : ${data}`); + } + + subscribeDataChange() { + try { + if (kvStore != null) { + kvStore.on('dataChange', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } catch (err) { + console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } + + unsubscribeDataChange() { + try { + if (kvStore != null) { + kvStore.off('dataChange', this.call); + } + } catch (err) { + console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } +} +``` + +### off('syncComplete') + +off(event: 'syncComplete', syncCallback?: Callback<Array<[string, number]>>): void + +Unsubscribes from synchronization complete events. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | --------------------------------------------- | ---- | ---------------------------------------------------------- | +| event | string | Yes | Event to unsubscribe from. The value is **syncComplete**, which indicates a synchronization complete event.| +| syncCallback | Callback<Array<[string, number]>> | No | Callback used to return the synchronization result. | + +**Example** + +```js +let kvStore; +class KvstoreModel { + call(data) { + console.log(`syncComplete : ${data}`); + } + + subscribeDataChange() { + try { + if (kvStore != null) { + kvStore.on('syncComplete', distributedKVStore.SubscribeType.SUBSCRIBE_TYPE_REMOTE, this.call); + } + } catch (err) { + console.error(`Fail to subscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } + + unsubscribeDataChange() { + try { + if (kvStore != null) { + kvStore.off('dsyncComplete', this.call); + } + } catch (err) { + console.error(`Fail to unsubscribeDataChange.code is ${err.code},message is ${err.message}`); + } + } +} +``` + +### getSecurityLevel + +getSecurityLevel(callback: AsyncCallback<SecurityLevel>): void + +Obtains the security level of this KV store. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------------- | ---- | -------------------------------- | +| callback | AsyncCallback<[SecurityLevel](#securitylevel)> | Yes | Callback invoked to return the security level obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID** | **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.getSecurityLevel(function (err, data) { + if (err != undefined) { + console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained securityLevel successfully'); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getSecurityLevel + +getSecurityLevel(): Promise<SecurityLevel> + +Obtains the security level of this KV store. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------- | ----------------------------------- | +| Promise<[SecurityLevel](#securitylevel)> | Promise used to return the security level obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + kvStore.getSecurityLevel().then((data) => { + console.log('Obtained securityLevel successfully'); + }).catch((err) => { + console.error(`Fail to get SecurityLevel.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +## DeviceKVStore + +Provides APIs for querying and synchronizing data in a device KV store. This class inherits from **SingleKVStore**. + +Data is distinguished by device in a device KV store. Each device can only write and modify its own data. Data of other devices is read-only and cannot be modified. + +For example, a device KV store can be used to implement image sharing between devices. The images of other devices can be viewed, but not be modified or deleted. + +Before calling any method in **DeviceKVStore**, you must use [getKVStore](#getkvstore) to obtain a **DeviceKVStore** object. + +### get + +get(key: string, callback: AsyncCallback): void + +Obtains the value of the specified key for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| +| callback | AsyncCallback<boolean \| string \| number \| Uint8Array> | Yes | Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log("Put data successfully."); + kvStore.get(KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log(`Obtained data successfully. data=${data}`); + }); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(key: string): Promise<boolean | string| number | Uint8Array> + +Obtains the value of the specified key for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the value to obtain. It cannot be empty, and the length cannot exceed [MAX_KEY_LENGTH](#constants).| + +**Return value** + +| Type | Description | +| -------------------------------------------------------- | ------------------------------- | +| Promise<Uint8Array \| string \| boolean \| number> | Promise used to return the value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string'; +const VALUE_TEST_STRING_ELEMENT = 'value-test-string'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then((data) => { + console.log(`Put data successfully. data=${data}`); + kvStore.get(KEY_TEST_STRING_ELEMENT).then((data) => { + console.log(`Obtained data successfully. data=${data}`); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(deviceId: string, key: string, callback: AsyncCallback<boolean|string|number|Uint8Array>): void + +Obtains a string value that matches the specified device ID and key. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory | Description | +| ----- | ------ | ---- | ----------------------- | +| deviceId |string | Yes |ID of the target device. | +| key |string | Yes |Key to match. | +| callback |AsyncCallback<boolean\|string\|number\|Uint8Array> | Yes |Callback invoked to return the value obtained. | + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Put data successfully.'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT, function (err, data) { + if (err != undefined) { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained data successfully'); + }); + }) +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### get + +get(deviceId: string, key: string): Promise<boolean|string|number|Uint8Array> + +Obtains a string value that matches the specified device ID and key. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| key | string | Yes | Key to match. | + +**Return value** + +| Type | Description | +| ------ | ------- | +|Promise<boolean\|string\|number\|Uint8Array> |Promise used to return the string value obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100004 | Not found. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +const KEY_TEST_STRING_ELEMENT = 'key_test_string_2'; +const VALUE_TEST_STRING_ELEMENT = 'value-string-002'; +try { + kvStore.put(KEY_TEST_STRING_ELEMENT, VALUE_TEST_STRING_ELEMENT).then(async (data) => { + console.log('Put data successfully.'); + kvStore.get('localDeviceId', KEY_TEST_STRING_ELEMENT).then((data) => { + console.log('Obtained data successfully'); + }).catch((err) => { + console.error(`Fail to get.code is ${err.code},message is ${err.message}`); + }); + }).catch((error) => { + console.error(`Fail to put.code is ${error.code},message is ${error.message}`); + }); +} catch (e) { + console.error(`Fail to get.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified key prefix for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------- | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified key prefix for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (entries) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`PutBatch ${entries}`); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put Batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occurred.code is ${e.code},message is ${e.message} `); +} +``` + +### getEntries + +getEntries(deviceId: string, keyPrefix: string, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified device ID and key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | ---------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries : ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getEntries('localDeviceId', 'batch_test_string_key', function (err, entries) { + if (err != undefined) { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, keyPrefix: string): Promise<Entry[]> + +Obtains all KV pairs that match the specified device ID and key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| keyPrefix | string | Yes | Key prefix to match. | + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + kvStore.getEntries('localDeviceId', 'batch_test_string_key').then((entries) => { + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + console.log(`entries[0].value: ${entries[0].value}`); + console.log(`entries[0].value.value: ${entries[0].value.value}`); + }).catch((err) => { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to put batch.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains all KV pairs that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ----------------------------------------------------- | +| query | [Query](query) | Yes | Key prefix to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }); + }); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(query: Query): Promise<Entry[]> + +Obtains all KV pairs that match the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| -------------------------------- | -------------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: {entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getEntries(query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to get Entries.code is ${err.code},message is ${err.message}`) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get Entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, query: Query, callback: AsyncCallback<Entry[]>): void + +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<[Entry](#entry)[]> | Yes | Callback invoked to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + var query = new distributedKVStore.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + kvStore.getEntries('localDeviceId', query, function (err, entries) { + if (err != undefined) { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the entries successfully.'); + console.log(`entries.length: ${entries.length}`); + console.log(`entries[0]: ${entries[0]}`); + }) + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getEntries + +getEntries(deviceId: string, query: Query): Promise<Entry[]> + +Obtains the KV pairs that match the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | -------------------- | +| deviceId | string | Yes | ID of the target device.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| -------------------------------- | ---------------------------------------------------------- | +| Promise<[Entry](#entry)[]> | Promise used to return the KV pairs obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + var arr = new Uint8Array([21, 31]); + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_bool_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.BYTE_ARRAY, + value: arr + } + } + entries.push(entry); + } + console.log(`entries: ${entries}`); + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + var query = new distributedKVStore.Query(); + query.deviceId('localDeviceId'); + query.prefixKey("batch_test"); + kvStore.getEntries('localDeviceId', query).then((entries) => { + console.log('Obtained the entries successfully.'); + }).catch((err) => { + console.error(`Fail to get entries.code is ${err.code},message is ${err.message}`); + }); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + console.log('Obtained the entries successfully.'); +} catch (e) { + console.error(`Fail to get entries.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a result set with the specified prefix for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ---------------------------------------------------------- | ---- | ------------------------------------ | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + kvStore.getResultSet('batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a result set with the specified prefix for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------------- | +| keyPrefix | string | Yes | Key prefix to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | --------------------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the result set obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + kvStore.getResultSet('batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, keyPrefix: string, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the target device. | +| keyPrefix | string | Yes | Key prefix to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key', async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully.'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully.'); + }) + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, keyPrefix: string): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and key prefix. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type| Mandatory| Description | +| --------- | -------- | ---- | ------------------------ | +| deviceId | string | Yes | ID of the target device.| +| keyPrefix | string | Yes | Key prefix to match. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + kvStore.getResultSet('localDeviceId', 'batch_test_string_key').then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully.'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully.'); + }) + }); + }); +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| ------------------------------------------------------ | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); + +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return Obtains a **KVStoreResultSet** object that matches the specified **Query** object for this device.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet(query).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, query: Query): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------------------------------------------ | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise used to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let resultSet; + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSet('localDeviceId', query).then((result) => { + console.log('Obtained the result set successfully.'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultSet.code is ${err.code},message is ${err.message}`); + }); + query.deviceId('localDeviceId'); + console.log("GetResultSet " + query.getSqlLike()); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully.'); + }).catch((err) => { + console.error(`Fail to close resultSet.code is ${err.code},message is ${err.message}`); + }); + +} catch (e) { + console.error(`Fail to get resultSet.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object for this device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet(predicates).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates, callback: AsyncCallback<KVStoreResultSet>): void + +Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| deviceId | string | Yes | ID of the target device. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic. | +| callback | AsyncCallback<[KVStoreResultSet](#kvstoreresultset)> | Yes | Callback invoked to return the **KVStoreResultSet** object obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet('localDeviceId', predicates, async function (err, result) { + if (err != undefined) { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set successfully'); + resultSet = result; + kvStore.closeResultSet(resultSet, function (err, data) { + if (err != undefined) { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Closed the result set successfully'); + }) + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSet + +getResultSet(deviceId: string, predicates: dataSharePredicates.DataSharePredicates): Promise<KVStoreResultSet> + +Obtains a **KVStoreResultSet** object that matches the specified predicate object and device ID. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.DistributedDataManager.DataShare.Provider + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------------------------------------------ | ---- | ----------------------------------------------- | +| deviceId | string | Yes | ID of the target device. | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md#datasharepredicates) | Yes | **DataSharePredicates** object that specifies the **KVStoreResultSet** object to obtain. If this parameter is **null**, define the processing logic.| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------------- | +| Promise<[KVStoreResultSet](#kvstoreresultset)> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +import dataSharePredicates from '@ohos.data.dataSharePredicates'; +let kvStore; +try { + let resultSet; + let predicates = new dataSharePredicates.DataSharePredicates(); + predicates.prefixKey("batch_test_string_key"); + kvStore.getResultSet('localDeviceId', predicates).then((result) => { + console.log('Obtained the result set successfully'); + resultSet = result; + }).catch((err) => { + console.error(`Fail to get resultset.code is ${err.code},message is ${err.message}`); + }); + kvStore.closeResultSet(resultSet).then((err) => { + console.log('Closed the result set successfully'); + }).catch((err) => { + console.error(`Fail to close resultset.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query, callback: AsyncCallback<number>): void + +Obtains the number of results that match the specified **Query** object for this device. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------- | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results that match the specified **Query** object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained the result set size successfully'); + }); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(query: Query): Promise<number> + +Obtains the number of results that match the specified **Query** object for this device. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | -------------- | ---- | -------------- | +| query | [Query](query) | Yes | **Query** object to match.| + +**Return value** + +| Type | Description | +| --------------------- | ---------------------------------------------------- | +| Promise<number> | Promise used to return the number of results that match the specified **Query** object.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize(query).then((resultSize) => { + console.log('Obtained the result set size successfully'); + }).catch((err) => { + console.error(`Fail to get result size.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`An unexpected error occured.code is ${e.code},message is ${e.code}`); +} +``` + +### getResultSize + +getResultSize(deviceId: string, query: Query, callback: AsyncCallback<number>): void; + +Obtains the number of results that matches the specified device ID and **Query** object. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | --------------------------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs. | +| query | [Query](query) | Yes | **Query** object to match. | +| callback | AsyncCallback<number> | Yes | Callback invoked to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries, async function (err, data) { + if (err != undefined) { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Batch put data successfully.'); + const query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query, async function (err, resultSize) { + if (err != undefined) { + console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + return; + } + console.log('Obtained resultSize successfully'); + ; + }); + }); +} catch (e) { + console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); +} +``` + +### getResultSize + +getResultSize(deviceId: string, query: Query): Promise<number> + +Obtains the number of results that matches the specified device ID and **Query** object. This API uses a promise to return the result. + +**System capability**: SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ---------------------------------- | +| deviceId | string | Yes | ID of the device to which the **KVStoreResultSet** object belongs.| +| query | [Query](query) | Yes | **Query** object to match. | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------------ | +| Promise<number> | Promise used to return the number of results obtained.| + +**Error codes** + +For details about the error codes, see [Distributed KV Store Error Codes](../errorcodes/errorcode-distributedKVStore.md). + +| **ID**| **Error Message** | +| ------------ | -------------------------------------- | +| 15100003 | Database corrupted. | +| 15100005 | Database or result set already closed. | + +**Example** + +```js +let kvStore; +try { + let entries = []; + for (var i = 0; i < 10; i++) { + var key = 'batch_test_string_key'; + var entry = { + key: key + i, + value: { + type: distributedKVStore.ValueType.STRING, + value: 'batch_test_string_value' + } + } + entries.push(entry); + } + kvStore.putBatch(entries).then(async (err) => { + console.log('Batch put data successfully.'); + }).catch((err) => { + console.error(`Fail to put batch.code is ${err.code},message is ${err.message}`); + }); + var query = new distributedKVStore.Query(); + query.prefixKey("batch_test"); + kvStore.getResultSize('localDeviceId', query).then((resultSize) => { + console.log('Obtained resultSize successfully'); + ; + }).catch((err) => { + console.error(`Fail to get resultSize.code is ${err.code},message is ${err.message}`); + }); +} catch (e) { + console.error(`Fail to get resultSize.code is ${e.code},message is ${e.message}`); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md index aa49db0f38c911850ec73e2fdb00fa98399ff1fc..770689ba93a6a375f7d48a46d49cbe2334bd9bc3 100644 --- a/en/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/en/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -1,4 +1,4 @@ -# Distributed Mission Management +# @ohos.distributedMissionManager (Distributed Mission Management) The **distributedMissionManager** module implements system mission management across devices. You can use the APIs provided by this module to register or deregister a mission status listener, start or stop synchronizing a remote mission list, and continue a mission on a remote device. @@ -372,6 +372,19 @@ Continues a mission on a remote device. This API uses an asynchronous callback t | options | [ContinueCallback](#continuecallback) | Yes | Callback invoked when the mission continuation is complete.| | callback | AsyncCallback<void> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 16300501 | The system ability work abnormally. | +| 16300502 | Failed to get the missionInfo of the specified missionId. | +| 16300503 | The application is not installed on the remote end and installation-free is not supported. | +| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. | +| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. | +| 16300506 | The local continuation task is already in progress. | + **Example** ```ts @@ -381,11 +394,11 @@ Continues a mission on a remote device. This API uses an asynchronous callback t missionId: 1, wantParam: {"key": "value"} }; - function OnContinueDone(resultCode) { - console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + function onContinueDone(resultCode) { + console.log('onContinueDone resultCode: ' + JSON.stringify(resultCode)); }; var options = { - OnContinueDone: OnContinueDone + onContinueDone: onContinueDone }; try { distributedMissionManager.continueMission(parameter, options, (error) => { @@ -422,6 +435,19 @@ Continues a mission on a remote device. This API uses a promise to return the re | ------------------- | ---------------- | | Promise<void> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Distributed Scheduler Error Codes](../errorcodes/errorcode-DistributedSchedule.md). + +| ID| Error Message| +| ------- | -------------------------------------------- | +| 16300501 | The system ability work abnormally. | +| 16300502 | Failed to get the missionInfo of the specified missionId. | +| 16300503 | The application is not installed on the remote end and installation-free is not supported. | +| 16300504 | The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. | +| 16300505 | The operation device must be the device where the application to be continued is located or the target device to be continued. | +| 16300506 | The local continuation task is already in progress. | + **Example** ```ts @@ -431,11 +457,11 @@ Continues a mission on a remote device. This API uses a promise to return the re missionId: 1, wantParam: {"key": "value"} }; - function OnContinueDone(resultCode) { - console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); + function onContinueDone(resultCode) { + console.log('onContinueDone resultCode: ' + JSON.stringify(resultCode)); }; var options = { - OnContinueDone: OnContinueDone + onContinueDone: onContinueDone }; try { distributedMissionManager.continueMission(parameter, options) diff --git a/en/application-dev/reference/apis/js-apis-effectKit.md b/en/application-dev/reference/apis/js-apis-effectKit.md index d44645af1980b3a963bd73878dc040db60abe205..7826d164b3c3f9cfbcde07dd9989b1fce3021e4b 100644 --- a/en/application-dev/reference/apis/js-apis-effectKit.md +++ b/en/application-dev/reference/apis/js-apis-effectKit.md @@ -1,4 +1,4 @@ -# Image Effect +# @ohos.effectKit (Image Effects) The **EffectKit** module provides basic image processing capabilities, including brightness adjustment, blurring, grayscale adjustment, and color picker. diff --git a/en/application-dev/reference/apis/js-apis-emitter.md b/en/application-dev/reference/apis/js-apis-emitter.md index 0bc6f9c6a4c156cfa2d604885572fcbe4bdc41bc..a072663e8c5cf3f667860cd72d1ef50c2bb72334 100644 --- a/en/application-dev/reference/apis/js-apis-emitter.md +++ b/en/application-dev/reference/apis/js-apis-emitter.md @@ -1,4 +1,4 @@ -# Emitter +# @ohos.events.emitter The **Emitter** module provides APIs for sending and processing in-process events, including the APIs for processing events that are subscribed to in persistent or one-shot manner, unsubscribing from events, and emitting events to the event queue. diff --git a/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md new file mode 100644 index 0000000000000000000000000000000000000000..0fd78714ed4bdf8a177fa46a814c16107e05b3ff --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-enterprise-adminManager.md @@ -0,0 +1,957 @@ +# @ohos.enterprise.adminManager (Enterprise Device Management) + +The **adminManager** module provides enterprise device management capabilities so that devices have the custom capabilities required in enterprise settings. + +> **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 adminManager from '@ohos.enterprise.adminManager'; +``` + +## adminManager.enableAdmin + +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, callback: AsyncCallback\): void + +Enables a device administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------------ | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | --------------------------------------------------------------- | +| 9200003 | the administrator ability component is invalid. | +| 9200004 | failed to enable the administrator application of the device. | +| 9200007 | the system ability work abnormally. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_TYPE_NORMAL, error => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("enableAdmin success"); +}); +``` + +## adminManager.enableAdmin + +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId: number, callback: AsyncCallback\): void + +Enables a device administrator application for the specified user based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | --------------------------------------------------------------- | +| 9200003 | the administrator ability component is invalid. | +| 9200004 | failed to enable the administrator application of the device. | +| 9200007 | the system ability work abnormally. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_TYPE_NORMAL, 100, error => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("enableAdmin success"); +}); +``` + +## adminManager.enableAdmin + +enableAdmin(admin: Want, enterpriseInfo: EnterpriseInfo, type: AdminType, userId?: number): Promise\ + +Enables a device administrator application based on the specified bundle name and class name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. | +| type | [AdminType](#admintype) | Yes | Type of the device administrator to enable. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | --------------------------------------------------------------- | +| 9200003 | the administrator ability component is invalid. | +| 9200004 | failed to enable the administrator application of the device. | +| 9200007 | the system ability work abnormally. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +adminManager.enableAdmin(wantTemp, enterpriseInfo, adminManager.AdminType.ADMIN_TYPE_NORMAL, 100) +.catch(error => { + console.log("error occurs" + error); +}); +``` + +## adminManager.disableAdmin + +disableAdmin(admin: Want, callback: AsyncCallback\): void + +Disables a device common administrator application based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device common administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------------------- | +| 9200005 | failed to disable the administrator application of the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +adminManager.disableAdmin(wantTemp, error => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("disableAdmin success "); +}); +``` + +## adminManager.disableAdmin + +disableAdmin(admin: Want, userId: number, callback: AsyncCallback\): void + +Disables a device common administrator application for the specified user based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device common administrator application. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------------------- | +| 9200005 | failed to disable the administrator application of the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +adminManager.disableAdmin(wantTemp, 100, error => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("disableAdmin success "); +}); +``` + +## adminManager.disableAdmin + +disableAdmin(admin: Want, userId?: number): Promise\ + +Disables a device common administrator application based on the specified bundle name and class name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device common administrator application. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------------------- | +| 9200005 | failed to disable the administrator application of the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +adminManager.disableAdmin(wantTemp, 100).catch(error => { + console.log("error occurs" + error); +}); +``` + +## adminManager.disableSuperAdmin + +disableSuperAdmin(bundleName: String, callback: AsyncCallback\): void + +Disables a device super administrator application based on the specified bundle name. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | ------------------- | +| bundleName | String | Yes | Bundle name of the device super administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------------------- | +| 9200005 | failed to disable the administrator application of the device. | + +**Example** + +```js +let bundleName = "com.example.myapplication"; +adminManager.disableSuperAdmin(bundleName, error => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("disableSuperAdmin success"); +}); +``` + +## adminManager.disableSuperAdmin + +disableSuperAdmin(bundleName: String): Promise\ + +Disables a device super administrator application based on the specified bundle name. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.MANAGE_ENTERPRISE_DEVICE_ADMIN + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | ------------ | +| bundleName | String | Yes | Bundle name of the device super administrator application.| + +**Return value** + +| Type | Description | +| ----------------- | ----------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------------------- | +| 9200005 | failed to disable the administrator application of the device. | + +**Example** + +```js +let bundleName = "com.example.myapplication"; +adminManager.disableSuperAdmin(bundleName).catch(error => { + console.log("error occurs" + error); +}); +``` + +## adminManager.isAdminEnabled + +isAdminEnabled(admin: Want, callback: AsyncCallback\): void + +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | -------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +adminManager.isAdminEnabled(wantTemp, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## adminManager.isAdminEnabled + +isAdminEnabled(admin: Want, userId: number, callback: AsyncCallback\): void + +Checks whether a device administrator application is enabled for the specified user based on the specified bundle name and class name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +adminManager.isAdminEnabled(wantTemp, 100, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## adminManager.isAdminEnabled + +isAdminEnabled(admin: Want, userId?: number): Promise\ + +Checks whether a device administrator application is enabled based on the specified bundle name and class name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------ | ----------------------------------- | ---- | ---------------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0.| + +**Return value** + +| Type | Description | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +adminManager.isAdminEnabled(wantTemp, 100).then((result) => { + console.log("result is " + result); +}).catch(error => { + console.log("error occurs" + error); +}); +``` + +## adminManager.isSuperAdmin + +isSuperAdmin(bundleName: String, callback: AsyncCallback\): void + +Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ----------------------- | ---- | -------------------- | +| bundleName | String | Yes | Device administrator application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +adminManager.isSuperAdmin(bundleName, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("result is " + result); +}); +``` + +## adminManager.isSuperAdmin + +isSuperAdmin(bundleName: String): Promise\ + +Checks whether a device super administrator application is enabled based on the specified bundle name. This API uses a promise to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ---------- | ------ | ---- | --------- | +| bundleName | String | Yes | Device super administrator application.| + +**Return value** + +| ID | Error Message | +| ----------------- | ------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +adminManager.isSuperAdmin(bundleName).then((result) => { + console.log("result is " + result); +}).catch(error => { + console.log("error occurs" + error); +}); +``` + +## adminManager.setEnterpriseInfo + +setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo, callback: AsyncCallback\;): void + +Sets the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_ENTERPRISE_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ---------------------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application. | +| callback | AsyncCallback\; | Yes | Callback used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +adminManager.setEnterpriseInfo(wantTemp, enterpriseInfo, error => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log("setEnterpriseInfo success"); +}); +``` + +## adminManager.setEnterpriseInfo + +setEnterpriseInfo(admin: Want, enterpriseInfo: EnterpriseInfo): Promise\; + +Sets the enterprise information of a device administrator application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_ENTERPRISE_INFO + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------- | ----------------------------------- | ---- | ------------ | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| enterpriseInfo | [EnterpriseInfo](#enterpriseinfo) | Yes | Enterprise information of the device administrator application.| + +**Return value** + +| Type | Description | +| ----------------- | --------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +let enterpriseInfo = { + name: "enterprise name", + description: "enterprise description" +} +adminManager.setEnterpriseInfo(wantTemp, enterpriseInfo).catch(error => { + console.log("error occurs" + error); +}); +``` + +## adminManager.getEnterpriseInfo + +getEnterpriseInfo(admin: Want, callback: AsyncCallback<EnterpriseInfo>): void + +Obtains the enterprise information of a device administrator application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------------ | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application. | +| callback | AsyncCallback<[EnterpriseInfo](#enterpriseinfo)> | Yes | Callback used to return the enterprise information of the device administrator application.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +adminManager.getEnterpriseInfo(wantTemp, (error, result) => { + if (error != null) { + console.log("error occurs" + error); + return; + } + console.log(result.name); + console.log(result.description); +}); +``` + +## adminManager.getEnterpriseInfo + +getEnterpriseInfo(admin: Want): Promise<EnterpriseInfo> + +Obtains the enterprise information of a device administrator application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------- | +| Promise<[EnterpriseInfo](#enterpriseinfo)> | Promise used to return the enterprise information of the device administrator application.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "com.example.myapplication", + abilityName: "EntryAbility", +}; +adminManager.getEnterpriseInfo(wantTemp).then((result) => { + console.log(result.name); + console.log(result.description); +}).catch(error => { + console.log("error occurs" + error); +}); +``` + +## adminManager.subscribeManagedEvent + +subscribeManagedEvent(admin: Want, managedEvents: Array\, callback: AsyncCallback\): void + +Subscribes to system management events. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| managedEvents | Array\<[ManagedEvent](#managedevent)> | Yes| Array of events to subscribe to.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the subscription is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +|ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200008 | the specified system events enum is invalid. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +let events = [0, 1]; +adminManager.subscribeManagedEvent(wantTemp, events, (error) => { + if (error) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## adminManager.subscribeManagedEvent + +subscribeManagedEvent(admin: Want, managedEvents: Array\): Promise\ + +Subscribes to system management events. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| managedEvents | Array\<[ManagedEvent](#managedevent)> | Yes| Array of events to subscribe to.| + +**Return value** + +| Type | Description | +| ----- | ----------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200008 | the specified system events enum is invalid. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +let events = [0, 1]; +adminManager.subscribeManagedEvent(wantTemp, events).then(() => { +}).catch((error) => { + console.log("error code:" + error.code + " error message:" + error.message); +}) +``` + +## adminManager.unsubscribeManagedEvent + +unsubscribeManagedEvent(admin: Want, managedEvents: Array\, callback: AsyncCallback\): void + +Unsubscribes from system management events. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| managedEvents | Array\<[ManagedEvent](#managedevent)> | Yes| Array of events to unsubscribe from.| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the unsubscription is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200008 | the specified system events enum is invalid. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +let events = [0, 1]; +adminManager.unsubscribeManagedEvent(wantTemp, events, (error) => { + if (error) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}); +``` + +## adminManager.unsubscribeManagedEvent + +unsubscribeManagedEvent(admin: Want, managedEvents: Array\): Promise\ + +Unsubscribes from system management events. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SUBSCRIBE_MANAGED_EVENT + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| managedEvents | Array\<[ManagedEvent](#managedevent)> | Yes| Array of events to unsubscribe from.| + +**Return value** + +| Type | Description | +| ----- | ----------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ----------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200008 | the specified system events enum is invalid. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +let events = [0, 1]; +adminManager.unsubscribeManagedEvent(wantTemp, events).then(() => { +}).catch((error) => { + console.log("error code:" + error.code + " error message:" + error.message); +}) +``` + +## EnterpriseInfo + +Describes the enterprise information of a device administrator application. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +| Name | Type | Readable| Writable | Description | +| ----------- | --------| ---- | ----- | ------------------------------- | +| name | string | Yes | No | Name of the enterprise to which the device administrator application belongs.| +| description | string | Yes | No | Description of the enterprise to which the device administrator application belongs.| + +## AdminType + +Enumerates the administrator types of the device administrator application. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +| Name | Value | Description | +| ----------------- | ---- | ----- | +| ADMIN_TYPE_NORMAL | 0x00 | Common administrator.| +| ADMIN_TYPE_SUPER | 0x01 | Super administrator.| + +## ManagedEvent + +Enumerates the system management events that can be subscribed to. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +| Name | Value | Description | +| -------------------------- | ---- | ------------- | +| MANAGED_EVENT_BUNDLE_ADDED | 0 | Application installation event.| +| MANAGED_EVENT_BUNDLE_REMOVED | 1 | Application uninstallation event.| diff --git a/en/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md b/en/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md new file mode 100644 index 0000000000000000000000000000000000000000..bc28cffaa5844cf46dbf73ffaa198e4b3e89ff7b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-enterprise-dateTimeManager.md @@ -0,0 +1,103 @@ +# @ohos.enterprise.dateTimeManager + +The **dateTimeManager** module provides APIs for system time management, which can only be called by device administrator applications. + +> **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 dateTimeManager from '@ohos.enterprise.dateTimeManager' +``` + +## dateTimeManager.setDateTime + +setDateTime(admin: Want, time: number, callback: AsyncCallback\): void + +Sets the system time. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| time | number | Yes| Timestamp (ms).| +| callback | AsyncCallback\ | Yes| Callback used to return the result. If the setting is successful, **err** is **null**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +dateTimeManager.setDateTime(wantTemp, 1526003846000, (error) => { + if (error) { + console.log("error code:" + error.code + " error message:" + error.message); + } +}) +``` + +## dateTimeManager.setDateTime + +setDateTime(admin: Want, time: number): Promise\ + +Sets the system time. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.ENTERPRISE_SET_DATETIME + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| admin | [Want](js-apis-app-ability-want.md) | Yes | Device administrator application.| +| time | number | Yes| Timestamp (ms).| + +**Return value** + +| Type | Description | +| ----- | ----------------------------------- | +| Promise\ | Promise that returns no value.| + +**Error codes** + +For details about the following error codes, see [Enterprise Device Management Error Codes](../errorcodes/errorcode-enterpriseDeviceManager.md). + +| ID| Error Message | +| ------- | ---------------------------------------------------------------------------- | +| 9200001 | the application is not an administrator of the device. | +| 9200002 | the administrator application does not have permission to manage the device. | + +**Example** + +```js +let wantTemp = { + bundleName: "bundleName", + abilityName: "abilityName", +}; +dateTimeManager.setDateTime(wantTemp, 1526003846000).then(() => { +}).catch((error) => { + console.log("error code:" + error.code + " error message:" + error.message); +}) +``` diff --git a/en/application-dev/reference/apis/js-apis-eventhub.md b/en/application-dev/reference/apis/js-apis-eventhub.md deleted file mode 100644 index 9ae7db735cbc61fa55a764cb285801297452c5d8..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-eventhub.md +++ /dev/null @@ -1,140 +0,0 @@ -# EventHub - -The **EventHub** module provides APIs to subscribe to, unsubscribe from, and trigger events. - -> **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. - -## Usage - -Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **Ability** instance. - -```js -import Ability from '@ohos.application.Ability'; -export default class MainAbility extends Ability { - func1(){ - console.log("func1 is called"); - } - onForeground() { - this.context.eventHub.on("123", this.func1); - } -} -``` - - -## EventHub.on - -on(event: string, callback: Function): void; - -Subscribes to an event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | string | Yes| Event name.| -| callback | Function | Yes| Callback invoked when the event is triggered.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", () => { - console.log("call anonymous func 1"); - }); - // Result - // func1 is called - // call anonymous func 1 - this.context.eventHub.emit("123"); - } - func1() { - console.log("func1 is called"); - } - } - ``` - - -## EventHub.off - -off(event: string, callback?: Function): void; - -Unsubscribes from an event. If **callback** is specified, this API unsubscribes from the specified callback. If **callback** is not specified, this API unsubscribes from all callbacks in the event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | string | Yes| Event name.| -| callback | Function | No| Callback for the event. If **callback** is unspecified, all callbacks of the event are unsubscribed.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - this.context.eventHub.off("123", this.func1); // Unsubscribe from func1. - this.context.eventHub.on("123", this.func1); - this.context.eventHub.on("123", this.func2); - this.context.eventHub.off("123"); // Unsubscribe from func1 and func2. - } - func1() { - console.log("func1 is called"); - } - func2() { - console.log("func2 is called"); - } - } - ``` - - -## EventHub.emit - -emit(event: string, ...args: Object[]): void; - -Triggers an event. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| event | string | Yes| Event name.| -| ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| - -**Example** - - ```js - import Ability from '@ohos.application.Ability'; - - export default class MainAbility extends Ability { - onForeground() { - this.context.eventHub.on("123", this.func1); - // Result - // func1 is called,undefined,undefined - this.context.eventHub.emit("123"); - // Result - // func1 is called,1,undefined - this.context.eventHub.emit("123", 1); - // Result - // func1 is called,1,2 - this.context.eventHub.emit("123", 1, 2); - } - func1(a, b) { - console.log("func1 is called," + a + "," + b); - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md b/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md deleted file mode 100644 index 841f7755273489a570865b41c63c5103c3af0c9a..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-extensionrunninginfo.md +++ /dev/null @@ -1,34 +0,0 @@ -# ExtensionRunningInfo - -The **ExtensionRunningInfo** module provides running information and states for Extension abilities. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module are system APIs and cannot be called by third-party applications. - -## Usage - -The Extension ability running information is obtained through an **abilityManager** instance. - -```js -import abilityManager from '@ohos.application.abilityManager'; -let upperLimit=1 -abilityManager.getExtensionRunningInfos(upperLimit, (err,data) => { - console.log("getExtensionRunningInfos err: " + err + " data: " + JSON.stringify(data)); -}); -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| extension | ElementName | Yes| No| Information that matches an Extension ability.| -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| startTime | number | Yes| No| Start time of the Extension ability.| -| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| -| type | [bundle.ExtensionAbilityType](js-apis-Bundle.md#extensionabilitytype9) | Yes| No| Extension ability type.| diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md index 5b84cfa1c1e778e0de657aeaea41e98c2146417c..dba3fb3f36ce7a0043738ff1c7bce26f22ae4973 100644 --- a/en/application-dev/reference/apis/js-apis-faultLogger.md +++ b/en/application-dev/reference/apis/js-apis-faultLogger.md @@ -1,5 +1,7 @@ -# Fault Logger -> **NOTE**
+# @ohos.faultLogger (FaultLogger) + +> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -8,14 +10,13 @@ import faultLogger from '@ohos.faultLogger' ``` - ## FaultType Enumerates the fault types. **System capability**: SystemCapability.HiviewDFX.Hiview.FaultLogger -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | NO_SPECIFIC | 0 | No specific fault type.| | CPP_CRASH | 2 | C++ program crash.| @@ -28,16 +29,16 @@ Defines the data structure of the fault log information. **System capability**: SystemCapability.HiviewDFX.Hiview.FaultLogger -| Name| Type| Description| -| -------- | -------- | -------- | -| pid | number | Process ID of the faulty process.| -| uid | number | User ID of the faulty process.| -| type | [FaultType](#faulttype) | Fault type.| -| timestamp | number | Second-level timestamp when the log was generated.| -| reason | string | Reason for the fault.| -| module | string | Module on which the fault occurred.| -| summary | string | Summary of the fault.| -| fullLog | string | Full log text.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pid | number | Yes| Process ID of the faulty process.| +| uid | number | Yes| User ID of the faulty process.| +| type | [FaultType](#faulttype) | Yes| Fault type.| +| timestamp | number | Yes| Second-level timestamp when the log was generated.| +| reason | string | Yes| Reason for the fault.| +| module | string | Yes| Module on which the fault occurred.| +| summary | string | Yes| Summary of the fault.| +| fullLog | string | Yes| Full log text.| ## faultLogger.querySelfFaultLog(deprecated) @@ -54,7 +55,7 @@ Obtains the fault information about the current process. This API uses an asynch | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | faultType | [FaultType](#faulttype) | Yes| Fault type.| -| callback | AsyncCallbackArray<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. +| callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. **Example** @@ -139,11 +140,11 @@ Obtains the fault information about the current process. This API uses an asynch | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | faultType | [FaultType](#faulttype) | Yes| Fault type.| -| callback | AsyncCallbackArray<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. +| callback | AsyncCallback<Array<[FaultLogInfo](#faultloginfo)>> | Yes| Callback used to return the fault information array.
The value is the fault information array obtained. If the value is **undefined**, an exception occurs during the information retrieval. In this case, an error string will be returned. **Error codes** -For details about the error codes, see [faultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). +For details about the error codes, see [FaultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). | ID| Error Message| | --- | --- | @@ -200,7 +201,7 @@ Obtains the fault information about the current process. This API uses a promise **Error codes** -For details about the error codes, see [faultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). +For details about the error codes, see [FaultLogger Error Codes](../errorcodes/errorcode-faultlogger.md). | ID| Error Message| | --- | --- | diff --git a/en/application-dev/reference/apis/js-apis-fileAccess.md b/en/application-dev/reference/apis/js-apis-fileAccess.md index 743e17c77f8dd2c4baa48f90de3ff9ac47fedfc0..bea477cc5357a7026ca0fd3b4b11bb3f6049d53e 100644 --- a/en/application-dev/reference/apis/js-apis-fileAccess.md +++ b/en/application-dev/reference/apis/js-apis-fileAccess.md @@ -1,11 +1,11 @@ -# User File Access and Management +# @ohos.data.fileAccess -The **fileAccess** module is a framework for accessing and operating user files based on the extension mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of unified file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. +The **fileAccess** module is a framework for accessing and operating user files based on the Extension ability mechanism. This module interacts with diverse file management services, such as the media library and external storage management service, and provides a set of file access and management APIs for system applications. The media library service allows access to user files on local devices and distributed devices. The external storage management service allows access to the user files stored on devices such as shared disks, USB flash drives, and SD cards. >**NOTE** > >- The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by FilePicker and the file manager app. +>- The APIs provided by this module are system APIs and cannot be called by third-party applications. Currently, the APIs can be called only by **FilePicker** and **Files**. ## Modules to Import @@ -21,17 +21,13 @@ Obtains information about all wants with **extension** set to **fileAcesss** in **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER - -**Parameters** - -None +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Return value** -| Type| Description| -| --- | -- | -| Promise<Array<Want>> | Promise used to return the want information obtained.| + | Type| Description| + | --- | -- | + | Promise<Array<Want>> | Promise used to return the **want** information obtained.| **Example** @@ -55,27 +51,27 @@ Synchronously creates a **Helper** object to connect to the specified wants. The **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| context | Context | Yes| Context of the ability.| -| wants | Array<Want> | Yes| Wants to connect.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | context | Context | Yes| Context of the ability.| + | wants | Array<Want> | Yes| Wants to connect.| **Return value** -| Type| Description| -| --- | -- | -| FileAccessHelper | **Helper** object created.| + | Type| Description| + | --- | -- | + | FileAccessHelper | **Helper** object created.| **Example** ```js createFileAccessHelper() { - let fileAccesssHelper = null; - // Obtain want information by using getFileAccessAbilityInfo(). + let fileAccessHelper = null; + / / Obtain wantInfos by using getFileAccessAbilityInfo(). // Create a Helper object to interact with the media library service only. let wantInfos = [ { @@ -84,8 +80,9 @@ Synchronously creates a **Helper** object to connect to the specified wants. The }, ] try { - fileAccesssHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); - if (!fileAccesssHelper) + // This.context is passed by MainAbility. + fileAccessHelper = fileAccess.createFileAccessHelper(this.context, wantInfos); + if (!fileAccessHelper) console.error("createFileAccessHelper interface returns an undefined object"); } catch (error) { console.error("createFileAccessHelper failed, error " + error); @@ -97,23 +94,23 @@ Synchronously creates a **Helper** object to connect to the specified wants. The createFileAccessHelper(context: Context) : FileAccessHelper -Synchronously creates a **Helper** object that connects to all file management services in the current system. +Synchronously creates a **Helper** object to connect to all file management services in the system. **System capability**: SystemCapability.FileManagement.UserFileService -**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER +**Required permissions**: ohos.permission.FILE_ACCESS_MANAGER and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| context | Context | Yes| Context of the ability.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | context | Context | Yes| Context of the ability.| **Return value** -| Type| Description| -| --- | -- | -| FileAccessHelper | **Helper** object created.| + | Type| Description| + | --- | -- | + | FileAccessHelper | **Helper** object created.| **Example** @@ -122,6 +119,7 @@ Synchronously creates a **Helper** object that connects to all file management s let fileAccesssHelperAllServer = null; // Create a Helper object to interact with all file management services configured with fileAccess in the system. try { + // This.context is passed by MainAbility. fileAccesssHelperAllServer = fileAccess.createFileAccessHelper(this.context); if (!fileAccesssHelperAllServer) console.error("createFileAccessHelper interface returns an undefined object"); @@ -135,22 +133,18 @@ Synchronously creates a **Helper** object that connects to all file management s getRoots( ) : Promise<RootIterator> -Obtains information about the root nodes for the devices of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which +Obtains information about the device root nodes of the file management service type connected to the **Helper** object. This API uses a promise to return a **RootIterator** object, which returns [RootInfo](#rootinfo) by using [next()](#rootiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** -| Type| Description| -| --- | -- | -| Promise<RootIterator> | **RootIterator** object obtained.| + | Type| Description| + | --- | -- | + | Promise<RootIterator> | Promise used to return the **RootIterator** object obtained.| **Example** @@ -160,7 +154,8 @@ None let rootinfos = []; let isDone = false; try { - rootIterator = await fileAccesssHelper.getRoots(); + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + rootIterator = await fileAccessHelper.getRoots(); if (!rootIterator) { console.error("getRoots interface returns an undefined object"); return; @@ -182,7 +177,7 @@ None listFile(filter?: Filter) : FileIterator -Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the root node of a device. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). +Synchronously obtains the **FileIterator** object of the first-level files (file folder) matching the conditions of the filter from the device root node. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -190,28 +185,28 @@ Synchronously obtains the **FileIterator** object of the first-level files (file **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** ```js - / / Obtain root information by using getRoots(). + / / Obtain rootInfos by using getRoots(). // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; let rootInfo = rootinfos[0]; let fileInfos = []; let isDone = false; try { let fileIterator = rootInfo.listFile(); - // ListFile that contains the filter implementation. + // listFile contains the filter implementation. // let fileIterator = rootInfo.listFile(filter); if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -233,7 +228,7 @@ Synchronously obtains the **FileIterator** object of the first-level files (file scanFile(filter?: Filter) : FileIterator -Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the root node of a device synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using the [next()](#fileiteratornext). +Recursively obtains the **FileIterator** object of the files matching the conditions of the filter from the device root node synchronously. The **FileIterator** object then returns [FileInfo](#fileinfo) by using [next()](#fileiteratornext). **System capability**: SystemCapability.FileManagement.UserFileService @@ -241,39 +236,39 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** ```js - / / Obtain root information by using getRoots(). + // Obtain rootInfos by using getRoots(). // let filter = {suffix : [".txt", ".jpg", ".xlsx"]}; - let rootInfo = rootinfos[0]; + let rootInfo = rootInfos[0]; let fileInfos = []; let isDone = false; try { - let fileIterator = rootInfo.scanFile(); - // ScanFile that contains the filter implementation - // let fileIterator = rootInfo.scanFile(filter); - if (!fileIterator) { - console.error("scanFile interface returns undefined object"); - return; - } - while (!isDone) { - let result = fileIterator.next(); - console.log("next result = " + JSON.stringify(result)); - isDone = result.done; - if (!isDone) - fileInfos.push(result.value); - } + let fileIterator = rootInfo.scanFile(); + // scanFile contains the filter implementation. + // let fileIterator = rootInfo.scanFile(filter); + if (!fileIterator) { + console.error("scanFile interface returns undefined object"); + return; + } + while (!isDone) { + let result = fileIterator.next(); + console.log("next result = " + JSON.stringify(result)); + isDone = result.done; + if (!isDone) + fileInfos.push(result.value); + } } catch (error) { console.error("scanFile failed, error " + error); } @@ -291,15 +286,15 @@ Synchronously obtains the **FileIterator** object of the next-level files (file **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -311,7 +306,7 @@ Synchronously obtains the **FileIterator** object of the next-level files (file let isDone = false; try { let fileIterator = fileInfoDir.listFile(); - // ListFile that contains the filter implementation. + // listFile contains the filter implementation. // let fileIterator = rootInfo.listFile(filter); if (!fileIterator) { console.error("listFile interface returns an undefined object"); @@ -341,16 +336,16 @@ Recursively obtains the **FileIterator** object of the files matching the condit **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | -- | -- | -| filter | Filter | No| **Filter** object. | + | Name| Type| Mandatory| Description| + | --- | --- | -- | -- | + | filter | Filter | No| **Filter** object. | **Return value** -| Type| Description| -| --- | -- | -| FileIterator | **FileIterator** object obtained.| + | Type| Description| + | --- | -- | + | FileIterator | **FileIterator** object obtained.| **Example** @@ -362,7 +357,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit let isDone = false; try { let fileIterator = fileInfoDir.scanFile(); - // ScanFile that contains the filter implementation + // scanFile contains the filter implementation. // let fileIterator = rootInfo.scanFile(filter); if (!fileIterator) { console.error("scanFile interface returns an undefined object"); @@ -370,7 +365,7 @@ Recursively obtains the **FileIterator** object of the files matching the condit } while (!isDone) { let result = fileIterator.next(); - console.error("next result = " + JSON.stringify(result)); + console.log("next result = " + JSON.stringify(result)); isDone = result.done; if (!isDone) subfileInfos.push(result.value); @@ -392,25 +387,28 @@ Creates a file in a directory. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the parent directory for the file to create.| -| displayName | string | Yes| Name of the file to create. A file name extension must be added for a local file. It is not required for a file stored in a shared disk.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the parent directory for the file to create.| + | displayName | string | Yes| Name of the file to create. A file name extension must be added for a local file. It is not required for a file stored in a shared disk.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the file created.| +| Promise<string> | Promise used to return the URI of the file created.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; let displayName = "file1" let fileUri = null; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. fileUri = await fileAccessHelper.createFile(sourceUri, displayName) if (!fileUri) { console.error("createFile return undefined object"); @@ -434,25 +432,28 @@ Creates a folder in a directory. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| parentUri | string | Yes| URI of the parent directory for the folder to create.| -| displayName | string | Yes| Name of the folder to create.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | parentUri | string | Yes| URI of the parent directory for the folder to create.| + | displayName | string | Yes| Name of the folder to create.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the folder created.| +| Promise<string> | Promise used to return the URI of the folder created.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon"; + // The media library URI is used as an example. + // In the sample code, sourceUri indicates the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceUri = "datashare:///media/file/6"; let dirName = "dirTest" let dirUri = null; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. dirUri = await fileAccessHelper.mkDir(sourceUri, dirName) if (!dirUri) { console.error("mkDir return undefined object"); @@ -466,7 +467,7 @@ Creates a folder in a directory. This API uses a promise to return the result. ## FileAccessHelper.openFile -openFile(uri: string, flags: [OPENFLAGS](#openflags)) : Promise<number> +openFile(uri: string, flags: OPENFLAGS) : Promise<number> Opens a file. This API uses a promise to return the result. @@ -476,25 +477,28 @@ Opens a file. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file to open.| -| flags | OPENFLAGS | |File open mode.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file to open.| + | flags | [OPENFLAGS](#openflags) | Yes| File open mode.| **Return value** | Type| Description| | --- | -- | -| Promise<number> | Handle of the file opened.| +| Promise<number> | Promise used to return the handle to the file opened.| **Example** ```js - // The URI of a shared disk is used as an example. - let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + // The media library URI is used as an example. + //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let targetUri = "datashare:///media/file/100"; try { - let fd = await fileAccessHelper.openFile(targetUri, OPENFLAGS.READ); - } cache (error) { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. + let fd = await fileAccessHelper.openFile(targetUri, fileAccess.OPENFLAGS.READ); + } catch (error) { console.error("openFile failed, error " + error); }; ``` @@ -511,9 +515,9 @@ Deletes a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to delete.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or folder to delete.| **Return value** @@ -524,13 +528,16 @@ Deletes a file or folder. This API uses a promise to return the result. **Example** ```js - // The URI of a shared disk is used as an example. - let targetUri = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; + // The media library URI is used as an example. + //In the sample code, targetUri indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let targetUri = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let code = await fileAccessHelper.delete(targetUri); if (code != 0) console.error("delete failed, code " + code); - } cache (error) { + } catch (error) { console.error("delete failed, error " + error); }; ``` @@ -547,27 +554,30 @@ Moves a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFile | string | Yes| URI of the file or folder to move.| -| destFile | string | Yes| URI of the folder to which the file or folder is moved.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFile | string | Yes| URI of the file or folder to move.| + | destFile | string | Yes| URI of the folder to which the file or folder will be moved.| **Return value** | Type| Description| | ----- | ------ | -| Promise<string> | URI of the file or folder in the destination directory.| +| Promise<string> | Promise used to return the URI of the file or folder in the destination directory.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/file1"; - let destFile = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + //In the sample code, sourceFile destFile indicates the file or folder in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceFile = "datashare:///media/file/102"; + let destFile = "datashare:///media/file/101"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let fileUri = await fileAccessHelper.move(sourceFile, destFile); console.log("Operation successful. fileUri: " + JSON.stringify(fileUri)); - } cache (error) { + } catch (error) { console.error("move failed, error " + error); }; ``` @@ -584,26 +594,29 @@ Renames a file or folder. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| uri | string | Yes| URI of the file or folder to rename.| -| displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | uri | string | Yes| URI of the file or folder to rename.| + | displayName | string | Yes| New name of the file or folder, which can contain the file name extension.| **Return value** | Type| Description| | --- | -- | -| Promise<string> | URI of the renamed file or folder.| +| Promise<string> | Promise used to return the URI of the renamed file or folder.| **Example** ```js - // The URI of a shared disk is used as an example. - let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceDir = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let DestDir = await fileAccessHelper.rename(sourceDir, "testDir"); console.log("Operation successful. DestDir: " + JSON.stringify(DestDir)); - } cache (error) { + } catch (error) { console.error("rename failed, error " + error); }; ``` @@ -620,9 +633,9 @@ Checks whether a file or folder exists. This API uses a promise to return the re **Parameters** -| Name| Type| Mandatory| Description| -| --- | --- | --- | -- | -| sourceFileUri | string | Yes| URI of the file or folder.| + | Name| Type| Mandatory| Description| + | --- | --- | --- | -- | + | sourceFileUri | string | Yes| URI of the file or folder.| **Return value** @@ -633,15 +646,18 @@ Checks whether a file or folder exists. This API uses a promise to return the re **Example** ```js - // The URI of a shared disk is used as an example. - let sourceDir = "datashare:///com.ohos.UserFile.ExternalFileManager/data/storage/el1/bundle/storage_daemon/dirTest"; + // The media library URI is used as an example. + // In the sample code, sourceDir indicates a file in the Download directory. The URI is the URI in fileInfo. + // You can use the URI obtained. + let sourceDir = "datashare:///media/file/100"; try { + // Obtain fileAccessHelper by referring to the sample code of fileAccess.createFileAccessHelper. let existJudgment = await fileAccessHelper.access(sourceDir); if (existJudgment) console.log("sourceDir exists"); else console.log("sourceDir does not exist"); - } cache (error) { + } catch (error) { console.error("rename failed, error " + error); }; ``` @@ -656,10 +672,6 @@ Obtains the next-level device root directory. **RootIterator** is an iterator ob **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** | Type| Description| @@ -676,10 +688,6 @@ Obtains the information about the next-level file or folder. **FileIterator** is **Required permissions**: ohos.permission.FILE_ACCESS_MANAGER -**Parameters** - -None - **Return value** | Type| Description| @@ -720,7 +728,7 @@ Represents the file or folder attribute information and interface capabilities. | mode | number | Yes| No| Permissions on the file or folder.| | size | number | Yes| No| Size of the file or folder.| | mtime | number | Yes| No| Time when the file or folder was last modified.| -| mimeType | string | Yes| No| Media resource type of the file or folder.| +| mimeType | string | Yes| No| MIME type of the file or folder.| ## OPENFLAGS diff --git a/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md index fce0a93c72553be6306910412404e2fe09bc2290..43ccea2e0fadb8875acd0bbd18225d57a3ee62a8 100644 --- a/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md +++ b/en/application-dev/reference/apis/js-apis-fileExtensionInfo.md @@ -1,4 +1,4 @@ -# User File Extension Info +# @ohos.fileExtensionInfo The **fileExtensionInfo** module defines attributes in **RootInfo** and **FileInfo** of the user file access and management module. @@ -37,10 +37,10 @@ Defines the values of **deviceFlags** used in **RootInfo**. **deviceFlags** is u ### Attributes - | Name| Type | Value| Readable| Writable| Description | - | ------ | ------ | ---- | ---- | ---- | -------- | - | SUPPORTS_READ | number | 0b1 | Yes | No | Read support.| - | SUPPORTS_WRITE | number | 0b10 | Yes | No | Write support.| + | Name| Type | Readable| Writable| Description | + | ------ | ------ | ---- | ---- | -------- | + | SUPPORTS_READ | number | Yes | No | The device supports read.| + | SUPPORTS_WRITE | number | Yes | No | This device supports write.| ## fileExtensionInfo.DocumentFlag @@ -50,9 +50,9 @@ Defines the values of **mode** used in **FileInfo**. ### Attributes - | Name| Type | Value| Readable| Writable| Description | - | ------ | ------ | ---- | ---- | ---- | -------- | - | REPRESENTS_FILE | number | 0b1 | Yes | No | File.| - | REPRESENTS_DIR | number | 0b10 | Yes | No | Directory.| - | SUPPORTS_READ | number | 0b100 | Yes | No | Read support.| - | SUPPORTS_WRITE | number | 0b1000 | Yes | No | Write support.| + | Name| Type | Readable| Writable| Description | + | ------ | ------ | ---- | ---- | -------- | + | REPRESENTS_FILE | number | Yes | No | File.| + | REPRESENTS_DIR | number | Yes | No | Directory.| + | SUPPORTS_READ | number | Yes | No | This file is readable.| + | SUPPORTS_WRITE | number | Yes | No | This file is writable.| diff --git a/en/application-dev/reference/apis/js-apis-formInfo.md b/en/application-dev/reference/apis/js-apis-formInfo.md deleted file mode 100644 index 8acf0e5e3e1ccb81b2295b03c65ed8fd812efa8e..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formInfo.md +++ /dev/null @@ -1,133 +0,0 @@ -# FormInfo - -The **FormInfo** module provides widget information and state. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -``` -import formInfo from '@ohos.application.formInfo'; -``` - -## Required Permissions - -None - -## FormInfo - -Describes widget information. - -**System capability**: SystemCapability.Ability.Form - -| Name | Readable/Writable| Type | Description | -| ----------- | -------- | -------------------- | ------------------------------------------------------------ | -| bundleName | Read only | string | Name of the bundle to which the widget belongs. | -| moduleName | Read only | string | Name of the module to which the widget belongs. | -| abilityName | Read only | string | Name of the ability to which the widget belongs. | -| name | Read only | string | Widget name. | -| description | Read only | string | Description of the widget. | -| type | Read only | [FormType](#formtype) | Widget type. Currently, only JS widgets are supported.| -| jsComponentName | Read only | string | Component name of the JS widget. | -| colorMode | Read only | [ColorMode](#colormode) | Color mode of the widget. | -| isDefault | Read only | boolean | Whether the widget is the default one. | -| updateEnabled | Read only | boolean | Whether the widget is updatable. | -| formVisibleNotify | Read only | string | Whether to send a notification when the widget is visible. | -| relatedBundleName | Read only | string | Name of the associated bundle to which the widget belongs. | -| scheduledUpdateTime | Read only | string | Time when the widget was updated. | -| formConfigAbility | Read only | string | Configuration ability of the widget. | -| updateDuration | Read only | string | Widget update period.| -| defaultDimension | Read only | number | Default dimension of the widget. | -| supportDimensions | Read only | Array<number> | Dimensions supported by the widget. | -| customizeData | Read only | {[key: string]: [value: string]} | Custom data of the widget. | - -## FormType - -Enumerates the widget types. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| JS | 1 | JS widget. | - -## ColorMode - -Enumerates the color modes supported by the widget. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| MODE_AUTO | -1 | Auto mode. | -| MODE_DARK | 0 | Dark mode. | -| MODE_LIGHT | 1 | Light mode. | - -## FormStateInfo - -Describes the widget state information. - -**System capability**: SystemCapability.Ability.Form - -| Name | Readable/Writable| Type | Description | -| ----------- | -------- | -------------------- | ------------------------------------------------------------ | -| formState | Read only | [FormState](#formstate) | Widget state. | -| want | Read only | Want | Want text. | - -## FormState - -Enumerates the widget states. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| UNKNOWN | -1 | Unknown state. | -| DEFAULT | 0 | Default state. | -| READY | 1 | Ready state. | - -## FormParam - -Enumerates the widget parameters. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| IDENTITY_KEY9+ | "ohos.extra.param.key.form_identity" | ID of a widget.
**System API**: This is a system API and cannot be called by third-party applications. | -| DIMENSION_KEY | "ohos.extra.param.key.form_dimension" | Widget dimension. | -| NAME_KEY | "ohos.extra.param.key.form_name" | Widget name. | -| MODULE_NAME_KEY | "ohos.extra.param.key.module_name" | Name of the module to which the widget belongs. | -| WIDTH_KEY | "ohos.extra.param.key.form_width" | Widget width. | -| HEIGHT_KEY | "ohos.extra.param.key.form_height" | Widget height. | -| TEMPORARY_KEY | "ohos.extra.param.key.form_temporary" | Temporary widget. | -| ABILITY_NAME_KEY9+ | "ohos.extra.param.key.ability_name" | Ability name. | -| DEVICE_ID_KEY9+ | "ohos.extra.param.key.device_id" | Device ID.
This is a system API. | -| BUNDLE_NAME_KEY9+ | "ohos.extra.param.key.bundle_name" | Key that specifies the target bundle name.| - -## FormDimension - -Enumerates the widget dimensions. - -**System capability**: SystemCapability.Ability.Form - -| Name | Value | Description | -| ----------- | ---- | ------------ | -| Dimension_1_29+ | 1 | 1 x 2. | -| Dimension_2_29+ | 2 | 2 x 2. | -| Dimension_2_49+ | 3 | 2 x 4. | -| Dimension_4_49+ | 4 | 4 x 4. | -| Dimension_2_19+ | 5 | 2 x 1. | - - -## FormInfoFilter - -Defines the widget information filter. Only the widget information that meets the filter is returned. - -**System capability**: SystemCapability.Ability.Form - -| Name | Yes | Description | -| ----------- | ---- | ------------ | -| moduleName9+ | No | Module name.| diff --git a/en/application-dev/reference/apis/js-apis-formbindingdata.md b/en/application-dev/reference/apis/js-apis-formbindingdata.md deleted file mode 100644 index 612b2dc84f23f465a844d73656954bc983c5a233..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formbindingdata.md +++ /dev/null @@ -1,68 +0,0 @@ -# FormBindingData - -The **FormBindingData** module provides APIs for widget data binding. You can use the APIs to create a **FormBindingData** object and obtain related information. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -## Modules to Import - -``` -import formBindingData from '@ohos.application.formBindingData'; -``` - -## Required Permissions - -None - -## formBindingData.createFormBindingData - -createFormBindingData(obj?: Object | string): FormBindingData - -Creates a **FormBindingData** object. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | -------------- | ---- | ------------------------------------------------------------ | -| obj | Object or string| No | Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format. The image data is identified by "formImages", and the content is multiple key-value pairs, each of which consists of an image identifier and image file descriptor. The final format is {"formImages": {"key1": fd1, "key2": fd2}}.| - - -**Return value** - -| Type | Description | -| ----------------------------------- | --------------------------------------- | -| [FormBindingData](#formbindingdata) | **FormBindingData** object created based on the passed data.| - - -**Example** - - ```js - import featureAbility from '@ohos.ability.featureAbility'; - import fileio from '@ohos.fileio'; - let context=featureAbility.getContext(); - context.getOrCreateLocalDir((err,data)=>{ - let path=data+"/xxx.jpg"; - let fd = fileio.openSync(path); - let obj = { - "temperature": "21°", - "formImages": {"image": fd} - }; - let formBindingDataObj = formBindingData.createFormBindingData(obj); - }) - - - ``` - -## Attributes - -Describes a **FormBindingData** object. - -**System capability**: SystemCapability.Ability.Form - -| Name| Readable| Writable| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -------- | -------- | -| data | Yes| No| Object | Yes| Data to be displayed on the JS widget. The value can be an object containing multiple key-value pairs or a string in JSON format.| diff --git a/en/application-dev/reference/apis/js-apis-formextension.md b/en/application-dev/reference/apis/js-apis-formextension.md deleted file mode 100644 index 1540e538e1bcc8f53165a3fd277e60f76e73a7a1..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formextension.md +++ /dev/null @@ -1,289 +0,0 @@ -# FormExtension - -The **FormExtension** module provides APIs related to Form Extension abilities. - -> **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. - -## Modules to Import - -``` -import FormExtension from '@ohos.application.FormExtension'; -``` - -## Required Permissions - -None - -## Attributes - -**System capability**: SystemCapability.Ability.Form - -| Name | Type | Readable| Writable| Description | -| ------- | ------------------------------------------------------- | ---- | ---- | --------------------------------------------------- | -| context | [FormExtensionContext](js-apis-formextensioncontext.md) | Yes | No | Context of the **FormExtension**. This context is inherited from **ExtensionContext**.| - -## onCreate - -onCreate(want: Want): formBindingData.FormBindingData - -Called to notify the widget provider that a **Form** instance (widget) has been created. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | -------------------------------------- | ---- | ------------------------------------------------------------ | - | want | [Want](js-apis-application-Want.md) | Yes | Information related to the extension, including the widget ID, name, and style. The information must be managed as persistent data to facilitate subsequent widget update and deletion.| - -**Return value** - - | Type | Description | - | ------------------------------------------------------------ | ----------------------------------------------------------- | - | [formBindingData.FormBindingData](js-apis-formbindingdata.md#formbindingdata) | A **formBindingData.FormBindingData** object containing the data to be displayed on the widget.| - -**Example** - - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onCreate(want) { - console.log('FormExtension onCreate, want:' + want.abilityName); - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } - } - ``` - -## FormExtension.onCastToNormal - -onCastToNormal(formId: string): void - -Called to notify the widget provider that a temporary widget has been converted to a normal one. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------------ | - | formId | string | Yes | ID of the widget that requests to be converted to a normal one.| - -**Example** - - ``` - export default class MyFormExtension extends FormExtension { - onCastToNormal(formId) { - console.log('FormExtension onCastToNormal, formId:' + formId); - } - } - ``` - -## FormExtension.onUpdate - -onUpdate(formId: string): void - -Called to notify the widget provider that a widget has been updated. After obtaining the latest data, the caller invokes **updateForm** of the [FormExtensionContext](js-apis-formextensioncontext.md) class to update the widget data. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget that requests to be updated.| - -**Example** - - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onUpdate(formId) { - console.log('FormExtension onUpdate, formId:' + formId); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - this.context.updateForm(formId, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - ``` - -## FormExtension.onVisibilityChange - -onVisibilityChange(newStatus: { [key: string]: number }): void - -Called to notify the widget provider of the change of visibility. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | --------- | ------------------------- | ---- | ---------------------------- | - | newStatus | { [key: string]: number } | Yes | ID and visibility status of the widget to be changed.| - -**Example** - - ```js - import formBindingData from '@ohos.application.formBindingData' - export default class MyFormExtension extends FormExtension { - onVisibilityChange(newStatus) { - console.log('FormExtension onVisibilityChange, newStatus:' + newStatus); - let obj2 = formBindingData.createFormBindingData({temperature:"22c", time:"22:00"}); - - for (let key in newStatus) { - console.log('FormExtension onVisibilityChange, key:' + key + ", value=" + newStatus[key]); - this.context.updateForm(key, obj2) - .then((data)=>{ - console.log('FormExtension context updateForm, data:' + data); - }).catch((error) => { - console.error('Operation updateForm failed. Cause: ' + error);}); - } - } - } - ``` - -## FormExtension.onEvent - -onEvent(formId: string, message: string): void - -Called to instruct the widget provider to receive and process the widget event. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | ------- | ------ | ---- | ---------------------- | - | formId | string | Yes | ID of the widget that requests the event.| - | message | string | Yes | Event message. | - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onEvent(formId, message) { - console.log('FormExtension onEvent, formId:' + formId + ", message:" + message); - } - } - ``` - -## FormExtension.onDestroy - -onDestroy(formId: string): void - -Called to notify the widget provider that a **Form** instance (widget) has been destroyed. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------------------ | - | formId | string | Yes | ID of the widget to be destroyed.| - -**Example** - - ```js - export default class MyFormExtension extends FormExtension { - onDestroy(formId) { - console.log('FormExtension onDestroy, formId:' + formId); - } - } - ``` - -## FormExtension.onConfigurationUpdated - -onConfigurationUpdated(config: Configuration): void; - -Called when the configuration of the environment where the ability is running is updated. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [Configuration](js-apis-configuration.md) | Yes| New configuration.| - -**Example** - - ```js - class MyFormExtension extends FormExtension { - onConfigurationUpdated(config) { - console.log('onConfigurationUpdated, config:' + JSON.stringify(config)); - } - } - ``` - -## FormExtension.onAcquireFormState - -onAcquireFormState?(want: Want): formInfo.FormState; - -Called when the widget provider receives the status query result of a widget. By default, the initial state is returned. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | No| Description of the widget state, including the bundle name, ability name, module name, widget name, and widget dimension.| - -**Example** - - ```js - import formInfo from '@ohos.application.formInfo' - class MyFormExtension extends FormExtension { - onAcquireFormState(want) { - console.log('FormExtension onAcquireFormState, want:' + want); - return formInfo.FormState.UNKNOWN; - } - } - ``` - -## FormExtension.onShare - -onShare?(formId: string): {[key: string]: any}; - -Called by the widget provider to receive shared widget data. - -This is a system API. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | formId | string | Yes | ID of a widget.| - -**Return value** - - | Type | Description | - | ------------------------------------------------------------ | ----------------------------------------------------------- | - | {[key: string]: any} | Data to be shared by the widget, in the form of key-value pairs.| - -**Example** - - ```js - class MyFormExtension extends FormExtension { - onShare(formId) { - console.log('FormExtension onShare, formId:' + formId); - let wantParams = { - "temperature":"20", - "time":"2022-8-8 09:59", - }; - return wantParams; - } - } - ``` diff --git a/en/application-dev/reference/apis/js-apis-formextensioncontext.md b/en/application-dev/reference/apis/js-apis-formextensioncontext.md deleted file mode 100644 index 7cd19e0e0f9a5d4ae906abd1a6d469893c1e95e0..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formextensioncontext.md +++ /dev/null @@ -1,106 +0,0 @@ -# FormExtensionContext - -The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for Form Extension abilities. - -You can use the APIs of this module to start Form Extension abilities. - -> **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. - -## Usage - -Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtension** instance. -```js -import FormExtension from '@ohos.application.FormExtension'; -import formBindingData from '@ohos.application.formBindingData' -export default class MyFormExtension extends FormExtension { - onCreate() { - let dataObj1 = { - temperature:"11c", - "time":"11:00" - }; - let obj1 = formBindingData.createFormBindingData(dataObj1); - return obj1; - } -} - -``` - -## FormExtensionContext.startAbility - -startAbility(want: Want, callback: AsyncCallback<void>): void - -Starts an ability. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.Form - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------| --------------------------------- | ---- | -------------------------------------- | -| want| [Want](js-apis-application-Want.md) | Yes | Information about the ability to start, such as the ability name and bundle name.| -| callback| AsyncCallback<void> | Yes | Callback used to return the result.| - -**Example** - -```js -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want, function(err) { - console.info(err.code); -}) -``` - -## FormExtensionContext.startAbility - -startAbility(want: Want): Promise<void> - -Starts an ability. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.Form - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------| --------------------------------- | ---- | -------------------------------------- | -| want| [Want](js-apis-application-Want.md) | Yes | Information about the ability to start, such as the ability name and bundle name.| - -**Return value** - -| Type | Description | -| ------------ | ---------------------------------- | -| Promise<void< | Promise used to return the result.| - -**Example** - -```js -var want = { - deviceId: "", - bundleName: "com.example.formstartability", - abilityName: "MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: {} -} -this.context.startAbility(want).then(() => { - console.info("StartAbility Success"); -}).catch((error) => { - console.info("StartAbility failed"); -}); -``` diff --git a/en/application-dev/reference/apis/js-apis-formhost.md b/en/application-dev/reference/apis/js-apis-formhost.md deleted file mode 100644 index 7ed0ff46de845198aac96bbcf7ebdeaad4055ad1..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-formhost.md +++ /dev/null @@ -1,1124 +0,0 @@ -# FormHost - -The **FormHost** module provides APIs related to the widget host, which is an application that displays the widget content and controls the position where the widget is displayed. You can use the APIs to delete, release, and update widgets, send notifications to widgets, and obtain widget information and status. - -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> The APIs of this module are system APIs and cannot be called by third-party applications. - -## Modules to Import - -``` -import formHost from '@ohos.application.formHost'; -``` - -## Required Permissions - -ohos.permission.REQUIRE_FORM - -ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -## deleteForm - -deleteForm(formId: string, callback: AsyncCallback<void>): void; - -Deletes a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.deleteForm(formId, (error, data) => { - if (error.code) { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## deleteForm - -deleteForm(formId: string): Promise<void>; - -Deletes a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, and the Widget Manager will not retain the widget information. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Parameters** - - ```js - var formId = "12400633174999288"; - formHost.deleteForm(formId).then(() => { - console.log('formHost deleteForm success'); - }).catch((error) => { - console.log('formHost deleteForm, error:' + JSON.stringify(error)); - }); - ``` - -## releaseForm - -releaseForm(formId: string, callback: AsyncCallback<void>): void; - -Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager still retains the widget cache and storage information. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.releaseForm(formId, (error, data) => { - if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## releaseForm - -releaseForm(formId: string, isReleaseCache: boolean, callback: AsyncCallback<void>): void; - -Releases a widget. This API uses an asynchronous callback to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------------- | ------ | ---- | ----------- | -| formId | string | Yes | Widget ID. | -| isReleaseCache | boolean | Yes | Whether to release the cache.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.releaseForm(formId, true, (error, data) => { - if (error.code) { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## releaseForm - -releaseForm(formId: string, isReleaseCache?: boolean): Promise<void>; - -Releases a widget. This API uses a promise to return the result. After this API is called, the application can no longer use the widget, but the Widget Manager retains the storage information about the widget and retains or releases the cache information based on the setting. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name | Type | Mandatory| Description | - | -------------- | ------ | ---- | ----------- | - | formId | string | Yes | Widget ID. | - | isReleaseCache | boolean | No | Whether to release the cache.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.releaseForm(formId, true).then(() => { - console.log('formHost releaseForm success'); - }).catch((error) => { - console.log('formHost releaseForm, error:' + JSON.stringify(error)); - }); - ``` - -## requestForm - -requestForm(formId: string, callback: AsyncCallback<void>): void; - -Requests a widget update. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.requestForm(formId, (error, data) => { - if (error.code) { - console.log('formHost requestForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## requestForm - -requestForm(formId: string): Promise<void>; - -Requests a widget update. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.requestForm(formId).then(() => { - console.log('formHost requestForm success'); - }).catch((error) => { - console.log('formHost requestForm, error:' + JSON.stringify(error)); - }); - ``` - -## castTempForm - -castTempForm(formId: string, callback: AsyncCallback<void>): void; - -Converts a temporary widget to a normal one. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.castTempForm(formId, (error, data) => { - if (error.code) { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## castTempForm - -castTempForm(formId: string): Promise<void>; - -Converts a temporary widget to a normal one. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.castTempForm(formId).then(() => { - console.log('formHost castTempForm success'); - }).catch((error) => { - console.log('formHost castTempForm, error:' + JSON.stringify(error)); - }); - ``` - -## notifyVisibleForms - -notifyVisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget visible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId, (error, data) => { - if (error.code) { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyVisibleForms - -notifyVisibleForms(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget visible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyVisibleForms(formId).then(() => { - console.log('formHost notifyVisibleForms success'); - }).catch((error) => { - console.log('formHost notifyVisibleForms, error:' + JSON.stringify(error)); - }); - ``` - -## notifyInvisibleForms - -notifyInvisibleForms(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget invisible. This API uses an asynchronous callback to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId, (error, data) => { - if (error.code) { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyInvisibleForms - -notifyInvisibleForms(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget invisible. This API uses a promise to return the result. After this API is called, **onVisibilityChange** is invoked to notify the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.notifyInvisibleForms(formId).then(() => { - console.log('formHost notifyInvisibleForms success'); - }).catch((error) => { - console.log('formHost notifyInvisibleForms, error:' + JSON.stringify(error)); - }); - ``` - -## enableFormsUpdate - -enableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId, (error, data) => { - if (error.code) { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); - } - }); - ``` - -## enableFormsUpdate - -enableFormsUpdate(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget updatable. This API uses a promise to return the result. After this API is called, the widget is in the enabled state and can receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.enableFormsUpdate(formId).then(() => { - console.log('formHost enableFormsUpdate success'); - }).catch((error) => { - console.log('formHost enableFormsUpdate, error:' + JSON.stringify(error)); - }); - ``` - -## disableFormsUpdate - -disableFormsUpdate(formIds: Array<string>, callback: AsyncCallback<void>): void; - -Instructs the widget framework to make a widget not updatable. This API uses an asynchronous callback to return the result. After this API is called, the widget cannot receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs. | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId, (error, data) => { - if (error.code) { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); - } - }); - ``` - -## disableFormsUpdate - -disableFormsUpdate(formIds: Array<string>): Promise<void>; - -Instructs the widget framework to make a widget not updatable. This API uses a promise to return the result. After this API is called, the widget cannot receive updates from the widget provider. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = ["12400633174999288"]; - formHost.disableFormsUpdate(formId).then(() => { - console.log('formHost disableFormsUpdate success'); - }).catch((error) => { - console.log('formHost disableFormsUpdate, error:' + JSON.stringify(error)); - }); - ``` - -## isSystemReady - -isSystemReady(callback: AsyncCallback<void>): void; - -Checks whether the system is ready. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.isSystemReady((error, data) => { - if (error.code) { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); - } - }); - ``` - -## isSystemReady - -isSystemReady(): Promise<void>; - -Checks whether the system is ready. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.Form - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - formHost.isSystemReady().then(() => { - console.log('formHost isSystemReady success'); - }).catch((error) => { - console.log('formHost isSystemReady, error:' + JSON.stringify(error)); - }); - ``` - -## getAllFormsInfo - -getAllFormsInfo(callback: AsyncCallback<Array<formInfo.FormInfo>>): void; - -Obtains the widget information provided by all applications on the device. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| - -**Example** - - ```js - formHost.getAllFormsInfo((error, data) => { - if (error.code) { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formHost getAllFormsInfo, data:' + JSON.stringify(data)); - } - }); - ``` - -## getAllFormsInfo - -getAllFormsInfo(): Promise<Array<formInfo.FormInfo>>; - - -Obtains the widget information provided by all applications on the device. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| - -**Example** - - ```js - formHost.getAllFormsInfo().then((data) => { - console.log('formHost getAllFormsInfo data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost getAllFormsInfo, error:' + JSON.stringify(error)); - }); - ``` - -## getFormsInfo - -getFormsInfo(bundleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; - - -Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | bundleName | string | Yes| Bundle name of the target application.| - | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| - -**Example** - - ```js - formHost.getFormsInfo("com.example.ohos.formjsdemo", (error, data) => { - if (error.code) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); - } - }); - ``` - -## getFormsInfo - -getFormsInfo(bundleName: string, moduleName: string, callback: AsyncCallback<Array<formInfo.FormInfo>>): void; - - -Obtains the widget information provided by a given application on the device. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | bundleName | string | Yes| Bundle name of the target application.| - | moduleName | string | Yes| Module name.| - | callback | AsyncCallback<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Yes| Callback used to return the widget information.| - -**Example** - - ```js - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry", (error, data) => { - if (error.code) { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); - } else { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); - } - }); - ``` - -## getFormsInfo - -getFormsInfo(bundleName: string, moduleName?: string): Promise<Array<formInfo.FormInfo>>; - - -Obtains the widget information provided by a given application on the device. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | bundleName | string | Yes| Bundle name of the target application.| - | moduleName | string | No| Module name.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<Array<[FormInfo](./js-apis-formInfo.md#forminfo-1)>> | Promise used to return the widget information.| - -**Example** - - ```js - formHost.getFormsInfo("com.example.ohos.formjsdemo", "entry").then((data) => { - console.log('formHost getFormsInfo, data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost getFormsInfo, error:' + JSON.stringify(error)); - }); - ``` - -## deleteInvalidForms - -deleteInvalidForms(formIds: Array<string>, callback: AsyncCallback<number>): void; - -Deletes invalid widgets from the list. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of valid widget IDs.| -| callback | AsyncCallback<number> | Yes| Callback used to return the number of widgets deleted.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.deleteInvalidForms(formIds, (error, data) => { - if (error.code) { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); - } else { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); - } - }); - ``` - -## deleteInvalidForms - -deleteInvalidForms(formIds: Array<string>): Promise<number>; - -Deletes invalid widgets from the list. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of valid widget IDs.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<number> | Promise used to return the number of widgets deleted.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.deleteInvalidForms(formIds).then((data) => { - console.log('formHost deleteInvalidForms, data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost deleteInvalidForms, error:' + JSON.stringify(error)); - }); - ``` - -## acquireFormState - -acquireFormState(want: Want, callback: AsyncCallback<formInfo.FormStateInfo>): void; - -Obtains the widget state. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** information carried to query the widget state.| -| callback | AsyncCallback<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Yes| Callback used to return the widget state.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 - } - }; - formHost.acquireFormState(want, (error, data) => { - if (error.code) { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); - } else { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); - } - }); - ``` - -## acquireFormState - -acquireFormState(want: Want): Promise<formInfo.FormStateInfo>; - -Obtains the widget state. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM and ohos.permission.GET_BUNDLE_INFO_PRIVILEGED - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** information carried to query the widget state.| - -**Return value** - -| Type | Description | -| :------------ | :---------------------------------- | -| Promise<[FormStateInfo](js-apis-formInfo.md#formstateinfo)> | Promise used to return the widget state.| - -**Example** - - ```js - var want = { - "deviceId": "", - "bundleName": "ohos.samples.FormApplication", - "abilityName": "FormAbility", - "parameters": { - "ohos.extra.param.key.module_name": "entry", - "ohos.extra.param.key.form_name": "widget", - "ohos.extra.param.key.form_dimension": 2 - } - }; - formHost.acquireFormState(want).then((data) => { - console.log('formHost acquireFormState, data:' + JSON.stringify(data)); - }).catch((error) => { - console.log('formHost acquireFormState, error:' + JSON.stringify(error)); - }); - ``` - -## on("formUninstall") - -on(type: "formUninstall", callback: Callback<string>): void; - -Subscribes to widget uninstall events. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| type | string | Yes | Type of event to subscribe to. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | Yes| Callback used for event subscription.| - -**Example** - - ```js - let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); - } - formHost.on("formUninstall", callback); - ``` - -## off("formUninstall") - -off(type: "formUninstall", callback?: Callback<string>): void; - -Unsubscribes from widget uninstall events. - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| type | string | Yes | Type of event to subscribe to. The value **formUninstall** indicates a widget uninstallation event.| -| callback | Callback<string> | No| Callback used for event unsubscription. If it is left unspecified, it indicates the callback for all the events that have been subscribed.| - -**Example** - - ```js - let callback = function(formId) { - console.log('formHost on formUninstall, formId:' + formId); - } - formHost.off("formUninstall", callback); - ``` - -## notifyFormsVisible - -notifyFormsVisible(formIds: Array<string>, isVisible: boolean, callback: AsyncCallback<void>): void; - -Instructs the widgets to make themselves visible. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| -| isVisible | boolean | Yes | Whether to be visible.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsVisible(formIds, true, (error, data) => { - if (error.code) { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyFormsVisible - -notifyFormsVisible(formIds: Array<string>, isVisible: boolean): Promise<void>; - -Instructs the widgets to make themselves visible. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formIds | Array<string> | Yes | List of widget IDs.| - | isVisible | boolean | Yes | Whether to be visible.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsVisible(formIds, true).then(() => { - console.log('formHost notifyFormsVisible success'); - }).catch((error) => { - console.log('formHost notifyFormsVisible, error:' + JSON.stringify(error)); - }); - ``` - -## notifyFormsEnableUpdate - -notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean, callback: AsyncCallback<void>): void; - -Instructs the widgets to enable or disable updates. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formIds | Array<string> | Yes | List of widget IDs.| -| isEnableUpdate | boolean | Yes | Whether to enable update.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsEnableUpdate(formIds, true, (error, data) => { - if (error.code) { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); - } - }); - ``` - -## notifyFormsEnableUpdate - -notifyFormsEnableUpdate(formIds: Array<string>, isEnableUpdate: boolean): Promise<void>; - -Instructs the widgets to enable or disable updates. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formIds | Array<string> | Yes | List of widget IDs.| - | isEnableUpdate | boolean | Yes | Whether to enable update.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - var formIds = new Array("12400633174999288", "12400633174999289"); - formHost.notifyFormsEnableUpdate(formIds, true).then(() => { - console.log('formHost notifyFormsEnableUpdate success'); - }).catch((error) => { - console.log('formHost notifyFormsEnableUpdate, error:' + JSON.stringify(error)); - }); - ``` -## shareForm9+ - -shareForm(formId: string, deviceId: string, callback: AsyncCallback<void>): void; - -Shares a specified widget with a remote device. This API uses an asynchronous callback to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| formId | string | Yes | Widget ID.| -| deviceId | string | Yes | Remote device ID.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var formId = "12400633174999288"; - var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; - formHost.shareForm(formId, deviceId, (error, data) => { - if (error.code) { - console.log('formHost shareForm, error:' + JSON.stringify(error)); - } - }); - ``` - -## shareForm9+ - -shareForm(formId: string, deviceId: string): Promise<void>; - -Shares a specified widget with a remote device. This API uses a promise to return the result. - -This is a system API. - -**Required permissions**: ohos.permission.REQUIRE_FORM - -**System capability**: SystemCapability.Ability.Form - -**Parameters** - - | Name| Type | Mandatory| Description | - | ------ | ------ | ---- | ------- | - | formId | string | Yes | Widget ID.| - | deviceId | string | Yes | Remote device ID.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Parameters** - - ```js - var formId = "12400633174999288"; - var deviceId = "EFC11C0C53628D8CC2F8CB5052477E130D075917034613B9884C55CD22B3DEF2"; - formHost.shareForm(formId, deviceId).then(() => { - console.log('formHost shareForm success'); - }).catch((error) => { - console.log('formHost shareForm, error:' + JSON.stringify(error)); - }); - ``` diff --git a/en/application-dev/reference/apis/js-apis-freeInstall.md b/en/application-dev/reference/apis/js-apis-freeInstall.md index 76fb053e5ce06bb620efce53126ba907a78d22f7..73d618e2f6eeed9df97b72dd4df8ba5839b1864c 100644 --- a/en/application-dev/reference/apis/js-apis-freeInstall.md +++ b/en/application-dev/reference/apis/js-apis-freeInstall.md @@ -1,4 +1,4 @@ -# Bundle.freeInstall +# @ohos.bundle.freeInstall (freeInstall) The **Bundle.freeInstall** module provides APIs for setting and obtaining installation-free information and APIs for obtaining **BundlePackInfo** and **DispatchInfo**. @@ -63,7 +63,7 @@ Sets an upgrade flag for a module. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **null**; otherwise, **err** is an error object.| @@ -113,7 +113,7 @@ Sets an upgrade flag for a module. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | moduleName | string | Yes | Module name. | | upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| @@ -166,7 +166,7 @@ Checks whether a module can be removed. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | ---------- | ---------------------- | ---- | --------------------------------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name. | | moduleName | string | Yes | Module name. | | callback | AsyncCallback\ | Yes | Callback used to return the result. If the module can be removed, **true** is returned; otherwise, **false** is returned.| @@ -266,7 +266,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This | Name | Type | Mandatory| Description | | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | bundleName | string | Yes | Bundle name. | -| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package. | +| bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package. | | callback | AsyncCallback<[BundlePackInfo](js-apis-bundleManager-packInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null** and **data** is the **BundlePackInfo** object obtained; otherwise, **err** is an error object.| **Error codes** @@ -299,7 +299,7 @@ try { getBundlePackInfo(bundleName: string, bundlePackFlag : BundlePackFlag): Promise\; -Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This API uses a promise to return the result. +Obtains **bundlePackInfo** based on **bundleName** and **bundleFlag**. This API uses a promise to return the result. **System API**: This is a system API. @@ -311,7 +311,7 @@ Obtains **bundlePackInfo** based on **bundleName** and **bundlePackFlag**. This | Name | Type | Mandatory| Description | | -------------- | --------------------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name. | +| bundleName | string | Yes | Bundle name.| | bundlePackFlag | [BundlePackFlag](#bundlepackflag) | Yes | Flag of the bundle package.| **Return value** @@ -363,10 +363,6 @@ Obtains the dispatch information. This API uses an asynchronous callback to retu | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | callback | AsyncCallback<[DispatchInfo](js-apis-bundleManager-dispatchInfo.md)> | Yes | Callback used to return the result. If the operation is successful, **err** is **null**, and **data** is the [DispatchInfo](js-apis-bundleManager-dispatchInfo.md) object obtained. otherwise, **err** is an error object.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```js @@ -402,10 +398,6 @@ Obtains the dispatch information. This API uses a promise to return the result. | ------------------------------------------------ | ------------------------------------------------------------ | | Promise<[DispatchInfo](js-apis-bundleManager-dispatchInfo.md)> | Promise used to return the [DispatchInfo](js-apis-bundleManager-dispatchInfo.md) object obtained.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..e102353bf8b19431fab51151c9c634916fa39ff4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md @@ -0,0 +1,2207 @@ +# @ohos.geoLocationManager (Geolocation Manager) + +The **geoLocationManager** module provides location service management functions. + +> **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. + +## Applying for Permissions + +Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. + +The system provides the following location permissions: +- ohos.permission.LOCATION + +- ohos.permission.APPROXIMATELY_LOCATION + +- ohos.permission.LOCATION_IN_BACKGROUND + +If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: + +- API versions earlier than 9: Apply for **ohos.permission.LOCATION**. + +- API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. + +| API Version| Location Permission| Permission Application Result| Location Accuracy| +| -------- | -------- | -------- | -------- | +| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| +| 9 and later| ohos.permission.LOCATION | Failure| No location obtained| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| + +If your application needs to access the device location information when running in the background, it must be configured to be able to run in 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. + +You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md). + + +## Modules to Import + +```ts +import geoLocationManager from '@ohos.geoLocationManager'; +``` + + +## geoLocationManager.on('locationChange') + +on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void + +Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | request | [LocationRequest](#locationrequest) | Yes| Location request.| + | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var locationChange = (location) => { + console.log('locationChanger: data: ' + JSON.stringify(location)); + }; + try { + geoLocationManager.on('locationChange', requestInfo, locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + + ``` + + +## geoLocationManager.off('locationChange') + +off(type: 'locationChange', callback?: Callback<Location>): void + +Unregisters the listener for location changes with the corresponding location request deleted. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| + | callback | Callback<[Location](#location)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; + var locationChange = (location) => { + console.log('locationChanger: data: ' + JSON.stringify(location)); + }; + try { + geoLocationManager.on('locationChange', requestInfo, locationChange); + geoLocationManager.off('locationChange', locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('locationEnabledChange') + +on(type: 'locationEnabledChange', callback: Callback<boolean>): void + +Registers a listener for location service status change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.| + | callback | Callback<boolean> | Yes| Callback used to return the location service status change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationEnabledChange = (state) => { + console.log('locationEnabledChange: ' + JSON.stringify(state)); + } + try { + geoLocationManager.on('locationEnabledChange', locationEnabledChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('locationEnabledChange') + +off(type: 'locationEnabledChange', callback?: Callback<boolean>): void; + +Unregisters the listener for location service status change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **locationEnabledChange** indicates a location service status change event.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationEnabledChange = (state) => { + console.log('locationEnabledChange: state: ' + JSON.stringify(state)); + } + try { + geoLocationManager.on('locationEnabledChange', locationEnabledChange); + geoLocationManager.off('locationEnabledChange', locationEnabledChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('cachedGnssLocationsChange') + +on(type: 'cachedGnssLocationsChange', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; + +Registers a listener for cached GNSS location reports. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **cachedGnssLocationsChange** indicates reporting of cached GNSS locations.| + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.| + | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var cachedLocationsCb = (locations) => { + console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); + } + var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + try { + geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('cachedGnssLocationsChange') + +off(type: 'cachedGnssLocationsChange', callback?: Callback<Array<Location>>): void; + +Unregisters the listener for cached GNSS location reports. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **cachedGnssLocationsChange** indicates reporting of cached GNSS locations.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var cachedLocationsCb = (locations) => { + console.log('cachedGnssLocationsChange: locations: ' + JSON.stringify(locations)); + } + var requestInfo = {'reportingPeriodSec': 10, 'wakeUpCacheQueueFull': true}; + try { + geoLocationManager.on('cachedGnssLocationsChange', requestInfo, cachedLocationsCb); + geoLocationManager.off('cachedGnssLocationsChange'); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('satelliteStatusChange') + +on(type: 'satelliteStatusChange', callback: Callback<SatelliteStatusInfo>): void; + +Registers a listener for GNSS satellite status change events. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to return GNSS satellite status changes.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var gnssStatusCb = (satelliteStatusInfo) => { + console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); + } + + try { + geoLocationManager.on('satelliteStatusChange', gnssStatusCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('satelliteStatusChange') + +off(type: 'satelliteStatusChange', callback?: Callback<SatelliteStatusInfo>): void; + +Unregisters the listener for GNSS satellite status change events. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **satelliteStatusChange** indicates a GNSS satellite status change event.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var gnssStatusCb = (satelliteStatusInfo) => { + console.log('satelliteStatusChange: ' + JSON.stringify(satelliteStatusInfo)); + } + try { + geoLocationManager.on('satelliteStatusChange', gnssStatusCb); + geoLocationManager.off('satelliteStatusChange', gnssStatusCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('nmeaMessage') + +on(type: 'nmeaMessage', callback: Callback<string>): void; + +Registers a listener for GNSS NMEA message change events. + +**Permission required**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.| + | callback | Callback<string> | Yes| Callback used to return GNSS NMEA message changes.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var nmeaCb = (str) => { + console.log('nmeaMessage: ' + JSON.stringify(str)); + } + + try { + geoLocationManager.on('nmeaMessage', nmeaCb ); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('nmeaMessage') + +off(type: 'nmeaMessage', callback?: Callback<string>): void; + +Unregisters the listener for GNSS NMEA message change events. + +**Permission required**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **nmeaMessage** indicates a GNSS NMEA message change event.| + | callback | Callback<string> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var nmeaCb = (str) => { + console.log('nmeaMessage: ' + JSON.stringify(str)); + } + + try { + geoLocationManager.on('nmeaMessage', nmeaCb); + geoLocationManager.off('nmeaMessage', nmeaCb); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.on('gnssFenceStatusChange') + +on(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; + +Registers a listener for status change events of the specified geofence. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301600 | Failed to operate the geofence. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + action: "action1", + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG], + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + try { + geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + }); + ``` + + +## geoLocationManager.off('gnssFenceStatusChange') + +off(type: 'gnssFenceStatusChange', request: GeofenceRequest, want: WantAgent): void; + +Unregisters the listener for status change events of the specified geofence. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Geofence + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **gnssFenceStatusChange** indicates a geofence status change event.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| + | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301600 | Failed to operate the geofence. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + import wantAgent from '@ohos.wantAgent'; + + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility", + action: "action1", + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + var requestInfo = {'priority': 0x201, 'scenario': 0x301, "geofence": {"latitude": 121, "longitude": 26, "radius": 100, "expiration": 10000}}; + try { + geoLocationManager.on('gnssFenceStatusChange', requestInfo, wantAgentObj); + geoLocationManager.off('gnssFenceStatusChange', requestInfo, wantAgentObj); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + }); + ``` + + +## geoLocationManager.on('countryCodeChange') + +on(type: 'countryCodeChange', callback: Callback<CountryCode>): void; + +Registers a listener for country code change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.| + | callback | Callback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code change event.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + + try { + geoLocationManager.on('countryCodeChange', callback); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.off('countryCodeChange') + +off(type: 'countryCodeChange', callback?: Callback<CountryCode>): void; + +Unregisters the listener for country code change events. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value **countryCodeChange** indicates a country code change event.| + | callback | Callback<[CountryCode](#countrycode)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301500 | Failed to query the area information. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var callback = (code) => { + console.log('countryCodeChange: ' + JSON.stringify(code)); + } + + try { + geoLocationManager.on('countryCodeChange', callback); + geoLocationManager.off('countryCodeChange', callback); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void + +Obtains the current location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.| + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; + + try { + geoLocationManager.getCurrentLocation(requestInfo, locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(callback: AsyncCallback<Location>): void; + +Obtains the current location. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; + + try { + geoLocationManager.getCurrentLocation(locationChange); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.getCurrentLocation + +getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> + +Obtains the current location. This API uses a promise to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> | [Location](#location) | NA | Promise used to return the current location.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; + try { + geoLocationManager.getCurrentLocation(requestInfo).then((result) => { + console.log('current location: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCurrentLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getLastLocation + +getLastLocation(): Location + +Obtains the last location. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Location | [Location](#location) | NA | Location information.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 |Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var location = geoLocationManager.getLastLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.isLocationEnabled + +isLocationEnabled(): boolean + +Checks whether the location service is enabled. + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Result indicating whether the location service is enabled.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var locationEnabled = geoLocationManager.isLocationEnabled(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.requestEnableLocation + +requestEnableLocation(callback: AsyncCallback<boolean>): void + +Requests to enable the location service. This API uses an asynchronous callback to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301700 | No response to the request. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.requestEnableLocation((err, data) => { + if (err) { + console.log('requestEnableLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('requestEnableLocation: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.requestEnableLocation + +requestEnableLocation(): Promise<boolean> + +Requests to enable the location service. This API uses a promise to return the result. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> | boolean | NA | Promise used to return the result. The value **true** indicates that the user agrees to enable the location service, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301700 | No response to the request. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.requestEnableLocation().then((result) => { + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, requestEnableLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocation + +enableLocation(callback: AsyncCallback<void>): void; + +Enables the location service. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocation((err, data) => { + if (err) { + console.log('enableLocation: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocation + +enableLocation(): Promise<void> + +Enables the location service. This API uses a promise to return the result. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocation().then((result) => { + console.log('promise, enableLocation succeed'); + }) + .catch((error) => { + console.log('promise, enableLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.disableLocation + +disableLocation(): void; + +Disables the location service. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableLocation(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + + +## geoLocationManager.getAddressesFromLocation + +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. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301300 | Reverse geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocation: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocation: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocation + +getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; + +Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Reverse geocoding request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)> | NA | Promise used to return the reverse geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301300 | Reverse geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { + console.log('getAddressesFromLocation: ' + JSON.stringify(data)); + }) + .catch((error) => { + console.log('promise, getAddressesFromLocation: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocationName + +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. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301400 | Geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest, (err, data) => { + if (err) { + console.log('getAddressesFromLocationName: err=' + JSON.stringify(err)); + } + if (data) { + console.log('getAddressesFromLocationName: data=' + JSON.stringify(data)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getAddressesFromLocationName + +getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> + +Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | request | [GeoCodeRequest](#geocoderequest) | Yes| Geocoding request.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)> | NA | Promise used to return the geocoding result.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301400 | Geocoding query failed. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; + try { + geoLocationManager.getAddressesFromLocationName(geocodeRequest).then((result) => { + console.log('getAddressesFromLocationName: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getAddressesFromLocationName: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +## geoLocationManager.isGeocoderAvailable + +isGeocoderAvailable(): boolean; + +Obtains the (reverse) geocoding service status. + +**System capability**: SystemCapability.Location.Location.Geocoder + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Result indicating whether the (reverse) geocoding service is available.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var isAvailable = geoLocationManager.isGeocoderAvailable(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCachedGnssLocationsSize + +getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; + +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCachedGnssLocationsSize((err, size) => { + if (err) { + console.log('getCachedGnssLocationsSize: err=' + JSON.stringify(err)); + } + if (size) { + console.log('getCachedGnssLocationsSize: size=' + JSON.stringify(size)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCachedGnssLocationsSize + +getCachedGnssLocationsSize(): Promise<number>; + +Obtains the number of cached GNSS locations. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<number> | number | NA | Promise used to return the number of cached GNSS locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCachedGnssLocationsSize().then((result) => { + console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCachedGnssLocationsSize: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.flushCachedGnssLocations + +flushCachedGnssLocations(callback: AsyncCallback<void>): void; + +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<void> | Yes| Callback used to return the error message.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.flushCachedGnssLocations((err, result) => { + if (err) { + console.log('flushCachedGnssLocations: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.flushCachedGnssLocations + +flushCachedGnssLocations(): Promise<void>; + +Obtains all cached GNSS locations and clears the GNSS cache queue. + +**Permission required**: ohos.permission.APPROXIMATELY_LOCATION + +**System capability**: SystemCapability.Location.Location.Gnss + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off. | +|3301200 | Failed to obtain the geographical location. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.flushCachedGnssLocations().then((result) => { + console.log('promise, flushCachedGnssLocations success'); + }) + .catch((error) => { + console.log('promise, flushCachedGnssLocations: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.sendCommand + +sendCommand(command: LocationCommand, callback: AsyncCallback<void>): void; + +Sends an extended command to the location subsystem. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| + | callback | AsyncCallback<void> | Yes| Callback used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + try { + geoLocationManager.sendCommand(requestInfo, (err, result) => { + if (err) { + console.log('sendCommand: err=' + JSON.stringify(err)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.sendCommand + +sendCommand(command: LocationCommand): Promise<void>; + +Sends an extended command to the location subsystem. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<void> | void | NA | Promise used to return the error code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + var requestInfo = {'scenario': 0x301, 'command': "command_1"}; + try { + geoLocationManager.sendCommand(requestInfo).then((result) => { + console.log('promise, sendCommand success'); + }) + .catch((error) => { + console.log('promise, sendCommand: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(callback: AsyncCallback<CountryCode>): void; + +Obtains the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[CountryCode](#countrycode)> | Yes| Callback used to return the country code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCountryCode((err, result) => { + if (err) { + console.log('getCountryCode: err=' + JSON.stringify(err)); + } + if (result) { + console.log('getCountryCode: result=' + JSON.stringify(result)); + } + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.getCountryCode + +getCountryCode(): Promise<CountryCode>; + +Obtains the current country code. + +**System capability**: SystemCapability.Location.Location.Core + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[CountryCode](#countrycode)> | [CountryCode](#countrycode) | NA | Callback used to return the country code.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301500 | Failed to query the area information.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.getCountryCode() + .then((result) => { + console.log('promise, getCountryCode: result=' + JSON.stringify(result)); + }) + .catch((error) => { + console.log('promise, getCountryCode: error=' + JSON.stringify(error)); + }); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableLocationMock + +enableLocationMock(): void; + +Enables the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableLocationMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.disableLocationMock + +disableLocationMock(): void; + +Disables the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableLocationMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setMockedLocations + +setMockedLocations(config: LocationMockConfig): void; + +Sets the mock location information. The mock locations will be reported at the interval specified in this API. + +**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](#locationmockconfig) | Yes| Mock location information, including the interval for reporting the mock locations and the array of the mock locations.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | +|3301100 | The location switch is off.| + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + 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}; + try { + geoLocationManager.setMockedLocations(config); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.enableReverseGeocodingMock + +enableReverseGeocodingMock(): void; + +Enables the mock reverse geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.enableReverseGeocodingMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.disableReverseGeocodingMock + +disableReverseGeocodingMock(): void; + +Disables the mock geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.disableReverseGeocodingMock(); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setReverseGeocodingMockInfo + +setReverseGeocodingMockInfo(mockInfos: Array<ReverseGeocodingMockInfo>): void; + +Sets information of the mock reverse geocoding function, including the mapping between a location and geographic name. If the location is contained in the configurations during reverse geocoding query, the corresponding geographic 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](#reversegeocodingmockinfo)> | Yes| Array of information of the mock reverse geocoding function, including a location and a geographic name.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + 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}}, + ]; + try { + geoLocationManager.setReverseGeocodingMockInfo(mockInfos); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.isLocationPrivacyConfirmed + +isLocationPrivacyConfirmed(type: LocationPrivacyType): boolean; + +Checks whether a user agrees with the privacy statement of the location service. This API can only be called by system applications. + +**System API**: This is a system API and cannot be called by third-party applications. + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype)| Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.| + +**Return value** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | boolean | boolean | NA | Result indicating whether the user agrees with the privacy statement.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + var isConfirmed = geoLocationManager.isLocationPrivacyConfirmed(1); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## geoLocationManager.setLocationPrivacyConfirmStatus + +setLocationPrivacyConfirmStatus(type: LocationPrivacyType, isConfirmed: boolean): void; + +Sets the user confirmation status for the privacy statement of the location service. This API can only be called by system applications. + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | type | [LocationPrivacyType](#locationprivacytype) | Yes| Privacy statement type, for example, privacy statement displayed in the startup wizard or privacy statement displayed when the location service is enabled.| + | isConfirmed | boolean | Yes| Whether the user agrees with the privacy statement.| + +**Error codes** + +For details about the following error codes, see [Location Error Codes](../errorcodes/errorcode-geoLocationManager.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +|3301000 | Location service is unavailable. | + +**Example** + + ```ts + import geoLocationManager from '@ohos.geoLocationManager'; + try { + geoLocationManager.setLocationPrivacyConfirmStatus(1, true); + } catch (err) { + console.error("errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + + +## LocationRequestPriority + +Sets the priority of the location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| 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. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| 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.| + + +## ReverseGeoCodeRequest + +Defines a reverse geocoding request. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| + + +## GeoCodeRequest + +Defines a geocoding request. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| +| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.| +| minLongitude | number | Yes| Yes| Minimum longitude.| +| maxLatitude | number | Yes| Yes| Maximum latitude.| +| maxLongitude | number | Yes| Yes| Maximum longitude.| + + +## GeoAddress + +Defines a geographic location. + +**System capability**: SystemCapability.Location.Location.Geocoder + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| No | Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| No | Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| +| locale | string | Yes| No | Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName | string | Yes| No | Landmark of the location.| +| countryCode | string | Yes| No | Country code.| +| countryName | string| Yes| No| Country name.| +| administrativeArea | string | Yes| No| Administrative region name.| +| subAdministrativeArea | string | Yes| No| Sub-administrative region name.| +| locality | string | Yes| No| Locality information.| +| subLocality | string | Yes| No| Sub-locality information.| +| roadName | string | Yes| No|Road name.| +| subRoadName | string | Yes| No| Auxiliary road information.| +| premises | string| Yes| No|House information.| +| postalCode | string | Yes| No| Postal code.| +| phoneNumber | string | Yes| No| Phone number.| +| addressUrl | string | Yes| No| Website URL.| +| descriptions | Array<string> | Yes| No| Additional descriptions.| +| descriptionsSize | number | Yes| No| Total number of additional descriptions.| +| isFromMock | Boolean | Yes| No| Whether the geographic name is from the mock reverse geocoding function.| + + +## LocationRequest + +Defines a location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| timeInterval | number | Yes| Yes| Time interval at which location information is reported.| +| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.| +| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| + + +## CurrentLocationRequest + +Defines the current location request. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| +| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.| + + +## SatelliteStatusInfo + +Defines the satellite status information. + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| No| Number of satellites.| +| satelliteIds | Array<number> | Yes| No| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| No| Altitude information.| +| azimuths | Array<number> | Yes| No| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| No| Carrier frequency.| + + +## CachedGnssLocationsRequest + +Represents a request for reporting cached GNSS locations. + +**System capability**: SystemCapability.Location.Location.Gnss + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| + + +## Geofence + +Defines a GNSS geofence. Currently, only circular geofences are supported. + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| Yes|Latitude information.| +| longitude | number | Yes|Yes| Longitude information.| +| radius | number | Yes|Yes| Radius of a circular geofence.| +| expiration | number | Yes|Yes| Expiration period of a geofence, in milliseconds.| + + +## GeofenceRequest + +Represents a GNSS geofencing request. + +**System capability**: SystemCapability.Location.Location.Geofence + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.| + + +## LocationPrivacyType + +Defines the privacy statement type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| OTHERS | 0 | Other scenarios.| +| STARTUP | 1 | Privacy statement displayed in the startup wizard.| +| CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| + + +## LocationCommand + +Defines an extended command. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| command | string | Yes| Yes | Extended command, in the string format.| + + +## Location + +Defines a location. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number| Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number| Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| +| altitude | number | Yes| No| Location altitude, in meters.| +| accuracy | number | Yes| No| Location accuracy, in meters.| +| speed | number | Yes| No|Speed, in m/s.| +| timeStamp | number | Yes| No| Location timestamp in the UTC format.| +| direction | number | Yes| No| Direction information.| +| timeSinceBoot | number | Yes| No| Location timestamp since boot.| +| additions | Array<string> | Yes| No| Additional description.| +| additionSize | number | Yes| No| Number of additional descriptions.| +| isFromMock | Boolean | Yes| No| Whether the location information is from the mock location function.| + + +## ReverseGeocodingMockInfo + +Represents information of the mock reverse geocoding function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| location | [ReverseGeoCodeRequest](#reversegeocoderequest) | Yes| Yes| Latitude and longitude information.| +| geoAddress | [GeoAddress](#geoaddress) | Yes| Yes|Geographic name.| + + +## LocationMockConfig + +Represents the information of the mock location function. + +**System capability**: SystemCapability.Location.Location.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| timeInterval | number | Yes| Yes| Interval at which mock locations are reported, in seconds.| +| locations | Array<Location> | Yes| Yes| Array of mocked locations.| + + +## CountryCode + +Represents country code information. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| country | string | Yes| No| Country code.| +| type | [CountryCodeType](#countrycodetype) | Yes| No| Country code source.| + + +## CountryCodeType + +Represents the country code source type. + +**System capability**: SystemCapability.Location.Location.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| COUNTRY_CODE_FROM_LOCALE | 1 | Country code obtained from the language configuration of the globalization module.| +| COUNTRY_CODE_FROM_SIM | 2 | Country code obtained from the SIM card.| +| COUNTRY_CODE_FROM_LOCATION | 3 | Country code obtained using the reverse geocoding function based on the user's location information.| +| COUNTRY_CODE_FROM_NETWORK | 4 | Country code obtained from the cellular network registration information.| diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md index 92118167ad603189eac98eae73e156a794542f99..86b62bd76ff14cdd0aaa46d60f532b2b52220e4d 100644 --- a/en/application-dev/reference/apis/js-apis-geolocation.md +++ b/en/application-dev/reference/apis/js-apis-geolocation.md @@ -1,24 +1,57 @@ -# Geolocation +# @ohos.geolocation (Geolocation) -Location services provide basic functions such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. +The **geolocation** module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead. + +## Applying for Permissions + +Before using basic location capabilities, check whether your application has been granted the permission to access the device location information. If not, your application needs to obtain the permission from the user as described below. + +The system provides the following location permissions: +- ohos.permission.LOCATION + +- ohos.permission.APPROXIMATELY_LOCATION + +- ohos.permission.LOCATION_IN_BACKGROUND + +If your application needs to access the device location information, it must first apply for required permissions. Specifically speaking: + +- API versions earlier than 9: Apply for **ohos.permission.LOCATION**. + +- API version 9 and later: Apply for **ohos.permission.APPROXIMATELY\_LOCATION**, or apply for **ohos.permission.APPROXIMATELY\_LOCATION** and **ohos.permission.LOCATION**. Note that **ohos.permission.LOCATION** cannot be applied for separately. + +| API Version| Location Permission| Permission Application Result| Location Accuracy| +| -------- | -------- | -------- | -------- | +| Earlier than 9| ohos.permission.LOCATION | Success| Location accurate to meters| +| 9 and later| ohos.permission.LOCATION | Failure| No location obtained| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION | Success| Location accurate to 5 kilometers| +| 9 and later| ohos.permission.APPROXIMATELY_LOCATION and ohos.permission.LOCATION| Success| Location accurate to meters| + +If your application needs to access the device location information when running in the background, it must be configured to be able to run in 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. + +You can declare the required permission in your application's configuration file. For details, see [Access Control (Permission) Development](../../security/accesstoken-guidelines.md). ## Modules to Import -```js +```ts import geolocation from '@ohos.geolocation'; ``` -## geolocation.on('locationChange') +## geolocation.on('locationChange')(deprecated) on(type: 'locationChange', request: LocationRequest, callback: Callback<Location>): void -Registers a listener for location changes with a location request initiated. +Registers a listener for location changes with a location request initiated. The location result is reported through [LocationRequest](#locationrequest). + +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationchange). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -27,13 +60,14 @@ Registers a listener for location changes with a location request initiated. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| - | request | LocationRequest | Yes| Location request.| + | request | [LocationRequest](#locationrequest) | Yes| Location request.| | callback | Callback<[Location](#location)> | Yes| Callback used to return the location change event.| + **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { @@ -43,13 +77,16 @@ Registers a listener for location changes with a location request initiated. ``` -## geolocation.off('locationChange') +## geolocation.off('locationChange')(deprecated) off(type: 'locationChange', callback?: Callback<Location>): void Unregisters the listener for location changes with the corresponding location request deleted. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationchange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -58,12 +95,12 @@ Unregisters the listener for location changes with the corresponding location re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationChange** indicates a location change event.| - | callback | Callback<[Location](#location)> | No| Callback used to return the location change event.| + | callback | Callback<[Location](#location)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300, 'timeInterval': 0, 'distanceInterval': 0, 'maxAccuracy': 0}; var locationChange = (location) => { @@ -74,13 +111,16 @@ Unregisters the listener for location changes with the corresponding location re ``` -## geolocation.on('locationServiceState') +## geolocation.on('locationServiceState')(deprecated) on(type: 'locationServiceState', callback: Callback<boolean>): void Registers a listener for location service status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanageronlocationenabledchange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -93,8 +133,8 @@ Registers a listener for location service status change events. **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: ' + JSON.stringify(state)); @@ -103,13 +143,16 @@ Registers a listener for location service status change events. ``` -## geolocation.off('locationServiceState') +## geolocation.off('locationServiceState')(deprecated) off(type: 'locationServiceState', callback?: Callback<boolean>): void; Unregisters the listener for location service status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('locationEnabledChange')](js-apis-geoLocationManager.md#geolocationmanagerofflocationenabledchange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -118,12 +161,12 @@ Unregisters the listener for location service status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **locationServiceState** indicates a location service status change event.| - | callback | Callback<boolean> | No| Callback used to return the location service status change event.| + | callback | Callback<boolean> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var locationServiceState = (state) => { console.log('locationServiceState: state: ' + JSON.stringify(state)); @@ -133,13 +176,17 @@ Unregisters the listener for location service status change events. ``` -## geolocation.on('cachedGnssLocationsReporting')8+ +## geolocation.on('cachedGnssLocationsReporting')(deprecated) on(type: 'cachedGnssLocationsReporting', request: CachedGnssLocationsRequest, callback: Callback<Array<Location>>): void; Registers a listener for cached GNSS location reports. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroncachedgnsslocationschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -148,13 +195,13 @@ Registers a listener for cached GNSS location reports. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| - | request | CachedGnssLocationsRequest | Yes| Request for reporting cached GNSS location.| - | callback | Callback<boolean> | Yes| Callback used to return cached GNSS locations.| + | request | [CachedGnssLocationsRequest](#cachedgnsslocationsrequest) | Yes| Request for reporting cached GNSS location.| + | callback | Callback<Array<[Location](#location)>> | Yes| Callback used to return cached GNSS locations.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); @@ -164,13 +211,17 @@ Registers a listener for cached GNSS location reports. ``` -## geolocation.off('cachedGnssLocationsReporting')8+ +## geolocation.off('cachedGnssLocationsReporting')(deprecated) off(type: 'cachedGnssLocationsReporting', callback?: Callback<Array<Location>>): void; Unregisters the listener for cached GNSS location reports. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('cachedGnssLocationsChange')](js-apis-geoLocationManager.md#geolocationmanageroffcachedgnsslocationschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -179,12 +230,12 @@ Unregisters the listener for cached GNSS location reports. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **cachedGnssLocationsReporting** indicates reporting of cached GNSS locations.| - | callback | Callback<boolean> | No| Callback used to return cached GNSS locations.| + | callback | Callback<Array<[Location](#location)>> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var cachedLocationsCb = (locations) => { console.log('cachedGnssLocationsReporting: locations: ' + JSON.stringify(locations)); @@ -195,13 +246,17 @@ Unregisters the listener for cached GNSS location reports. ``` -## geolocation.on('gnssStatusChange')8+ +## geolocation.on('gnssStatusChange')(deprecated) on(type: 'gnssStatusChange', callback: Callback<SatelliteStatusInfo>): void; Registers a listener for GNSS satellite status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageronsatellitestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -210,12 +265,12 @@ Registers a listener for GNSS satellite status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| - | callback | Callback<SatelliteStatusInfo> | Yes| Callback used to return GNSS satellite status changes.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | Yes| Callback used to return GNSS satellite status changes.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); @@ -224,13 +279,17 @@ Registers a listener for GNSS satellite status change events. ``` -## geolocation.off('gnssStatusChange')8+ +## geolocation.off('gnssStatusChange')(deprecated) off(type: 'gnssStatusChange', callback?: Callback<SatelliteStatusInfo>): void; Unregisters the listener for GNSS satellite status change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('satelliteStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffsatellitestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -239,11 +298,11 @@ Unregisters the listener for GNSS satellite status change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **gnssStatusChange** indicates a GNSS satellite status change.| - | callback | Callback<SatelliteStatusInfo> | No| Callback used to return GNSS satellite status changes.| + | callback | Callback<[SatelliteStatusInfo](#satellitestatusinfo)> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var gnssStatusCb = (satelliteStatusInfo) => { console.log('gnssStatusChange: ' + JSON.stringify(satelliteStatusInfo)); @@ -253,13 +312,17 @@ Unregisters the listener for GNSS satellite status change events. ``` -## geolocation.on('nmeaMessageChange')8+ +## geolocation.on('nmeaMessageChange')(deprecated) on(type: 'nmeaMessageChange', callback: Callback<string>): void; Registers a listener for GNSS NMEA message change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageronnmeamessage). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -272,8 +335,8 @@ Registers a listener for GNSS NMEA message change events. **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); @@ -282,13 +345,17 @@ Registers a listener for GNSS NMEA message change events. ``` -## geolocation.off('nmeaMessageChange')8+ +## geolocation.off('nmeaMessageChange')(deprecated) off(type: 'nmeaMessageChange', callback?: Callback<string>): void; Unregisters the listener for GNSS NMEA message change events. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('nmeaMessage')](js-apis-geoLocationManager.md#geolocationmanageroffnmeamessage). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -297,12 +364,12 @@ Unregisters the listener for GNSS NMEA message change events. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **nmeaMessageChange** indicates a GNSS NMEA message change.| - | callback | Callback<string> | No| Callback used to return GNSS NMEA message changes.| + | callback | Callback<string> | No| Callback to unregister. If this parameter is not specified, all callbacks of the specified event type are unregistered.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var nmeaCb = (str) => { console.log('nmeaMessageChange: ' + JSON.stringify(str)); @@ -312,13 +379,17 @@ Unregisters the listener for GNSS NMEA message change events. ``` -## geolocation.on('fenceStatusChange')8+ +## geolocation.on('fenceStatusChange')(deprecated) on(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Registers a listener for status change events of the specified geofence. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.on('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanagerongnssfencestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence @@ -327,13 +398,13 @@ Registers a listener for status change events of the specified geofence. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| - | request | GeofenceRequest | Yes| Geofencing request.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -357,13 +428,17 @@ Registers a listener for status change events of the specified geofence. ``` -## geolocation.off('fenceStatusChange')8+ +## geolocation.off('fenceStatusChange')(deprecated) off(type: 'fenceStatusChange', request: GeofenceRequest, want: WantAgent): void; Unregisters the listener for status change events of the specified geofence. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.off('gnssFenceStatusChange')](js-apis-geoLocationManager.md#geolocationmanageroffgnssfencestatuschange). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence @@ -372,12 +447,12 @@ Unregisters the listener for status change events of the specified geofence. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | type | string | Yes| Event type. The value **fenceStatusChange** indicates a geofence status change.| - | request | GeofenceRequest | Yes| Geofencing request.| + | request | [GeofenceRequest](#geofencerequest) | Yes| Geofencing request.| | want | WantAgent | Yes| **WantAgent** used to return geofence (entrance or exit) events.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; import wantAgent from '@ohos.wantAgent'; @@ -402,14 +477,16 @@ Unregisters the listener for status change events of the specified geofence. ``` -## geolocation.getCurrentLocation +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request: CurrentLocationRequest, callback: AsyncCallback<Location>): void - Obtains the current location. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -417,12 +494,12 @@ Obtains the current location. This API uses an asynchronous callback to return t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | request | [CurrentLocationRequest](#currentlocationrequest) | No| Location request.| + | request | [CurrentLocationRequest](#currentlocationrequest) | Yes| Location request.| | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; var locationChange = (err, location) => { @@ -434,18 +511,55 @@ Obtains the current location. This API uses an asynchronous callback to return t } }; geolocation.getCurrentLocation(requestInfo, locationChange); + ``` + + +## geolocation.getCurrentLocation(deprecated) + +getCurrentLocation(callback: AsyncCallback<Location>): void + + +Obtains the current location. This API uses an asynchronous callback to return the result. + +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation). + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Location.Location.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[Location](#location)> | Yes| Callback used to return the current location.| + +**Example** + + ```ts + import geolocation from '@ohos.geolocation'; + var locationChange = (err, location) => { + if (err) { + console.log('locationChanger: err=' + JSON.stringify(err)); + } + if (location) { + console.log('locationChanger: location=' + JSON.stringify(location)); + } + }; geolocation.getCurrentLocation(locationChange); ``` -## geolocation.getCurrentLocation +## geolocation.getCurrentLocation(deprecated) getCurrentLocation(request?: CurrentLocationRequest): Promise<Location> - Obtains the current location. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCurrentLocation](js-apis-geoLocationManager.md#geolocationmanagergetcurrentlocation-2). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -457,14 +571,14 @@ Obtains the current location. This API uses a promise to return the result. **Return value** - | Name| Description| - | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the current location.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> |[Location](#location)|NA| Promise used to return the current location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'priority': 0x203, 'scenario': 0x300,'maxAccuracy': 0}; geolocation.getCurrentLocation(requestInfo).then((result) => { @@ -473,13 +587,16 @@ Obtains the current location. This API uses a promise to return the result. ``` -## geolocation.getLastLocation +## geolocation.getLastLocation(deprecated) getLastLocation(callback: AsyncCallback<Location>): void Obtains the previous location. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -491,8 +608,8 @@ Obtains the previous location. This API uses an asynchronous callback to return **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getLastLocation((err, data) => { if (err) { @@ -505,26 +622,29 @@ Obtains the previous location. This API uses an asynchronous callback to return ``` -## geolocation.getLastLocation +## geolocation.getLastLocation(deprecated) getLastLocation(): Promise<Location> Obtains the previous location. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getLastLocation](js-apis-geoLocationManager.md#geolocationmanagergetlastlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<[Location](#location)> | Promise used to return the previous location.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<[Location](#location)> | [Location](#location)|NA|Promise used to return the previous location.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getLastLocation().then((result) => { console.log('getLastLocation: result: ' + JSON.stringify(result)); @@ -532,14 +652,16 @@ Obtains the previous location. This API uses a promise to return the result. ``` -## geolocation.isLocationEnabled +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(callback: AsyncCallback<boolean>): void - Checks whether the location service is enabled. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -550,8 +672,8 @@ Checks whether the location service is enabled. This API uses an asynchronous ca | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled((err, data) => { if (err) { @@ -564,25 +686,28 @@ Checks whether the location service is enabled. This API uses an asynchronous ca ``` -## geolocation.isLocationEnabled +## geolocation.isLocationEnabled(deprecated) isLocationEnabled(): Promise<boolean> Checks whether the location service is enabled. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isLocationEnabled](js-apis-geoLocationManager.md#geolocationmanagerislocationenabled). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> | boolean|NA|Promise used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isLocationEnabled().then((result) => { console.log('promise, isLocationEnabled: ' + JSON.stringify(result)); @@ -590,14 +715,16 @@ Checks whether the location service is enabled. This API uses a promise to retur ``` -## geolocation.requestEnableLocation +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(callback: AsyncCallback<boolean>): void - Requests to enable the location service. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -608,8 +735,8 @@ Requests to enable the location service. This API uses an asynchronous callback | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.requestEnableLocation((err, data) => { if (err) { @@ -622,159 +749,45 @@ Requests to enable the location service. This API uses an asynchronous callback ``` -## geolocation.requestEnableLocation +## geolocation.requestEnableLocation(deprecated) requestEnableLocation(): Promise<boolean> Requests to enable the location service. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.requestEnableLocation](js-apis-geoLocationManager.md#geolocationmanagerrequestenablelocation-1). -**System capability**: SystemCapability.Location.Location.Core - -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.requestEnableLocation().then((result) => { - console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); - }); - ``` - - -## geolocation.enableLocation - -enableLocation(callback: AsyncCallback<boolean>): void; - -Enables the location service. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.enableLocation((err, data) => { - if (err) { - console.log('enableLocation: err=' + JSON.stringify(err)); - } - if (data) { - console.log('enableLocation: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.enableLocation - -enableLocation(): Promise<boolean> - -Enables the location service. This API uses a promise to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.enableLocation().then((result) => { - console.log('promise, enableLocation: ' + JSON.stringify(result)); - }); - ``` - -## geolocation.disableLocation - -disableLocation(callback: AsyncCallback<boolean>): void; - -Disables the location service. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core - -**Parameters** - | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the location service status.| + | Promise<boolean> | boolean|NA|Promise used to return the location service status.| **Example** - - ```js - import geolocation from '@ohos.geolocation'; - geolocation.disableLocation((err, data) => { - if (err) { - console.log('disableLocation: err=' + JSON.stringify(err)); - } - if (data) { - console.log('disableLocation: data=' + JSON.stringify(data)); - } - }); - ``` - - -## geolocation.disableLocation - -disableLocation(): Promise<boolean> - -Disables the location service. This API uses a promise to return the result. - -**System API**: This is a system API and cannot be called by third-party applications. - -**Permission required**: ohos.permission.MANAGE_SECURE_SETTINGS - -**System capability**: SystemCapability.Location.Location.Core -**Return value** - - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the location service status.| - -**Example** - - ```js + ```ts import geolocation from '@ohos.geolocation'; - geolocation.disableLocation().then((result) => { - console.log('promise, disableLocation: ' + JSON.stringify(result)); + geolocation.requestEnableLocation().then((result) => { + console.log('promise, requestEnableLocation: ' + JSON.stringify(result)); }); ``` -## geolocation.isGeoServiceAvailable + +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(callback: AsyncCallback<boolean>): void Checks whether the (reverse) geocoding service is available. This API uses an asynchronous callback to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -785,8 +798,8 @@ Checks whether the (reverse) geocoding service is available. This API uses an as | callback | AsyncCallback<boolean> | Yes| Callback used to return the (reverse) geocoding service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable((err, data) => { if (err) { @@ -799,25 +812,28 @@ Checks whether the (reverse) geocoding service is available. This API uses an as ``` -## geolocation.isGeoServiceAvailable +## geolocation.isGeoServiceAvailable(deprecated) isGeoServiceAvailable(): Promise<boolean> Checks whether the (reverse) geocoding service is available. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.isGeocoderAvailable](js-apis-geoLocationManager.md#geolocationmanagerisgeocoderavailable). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the (reverse) geocoding service status.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Promise used to return the (reverse) geocoding service status.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.isGeoServiceAvailable().then((result) => { console.log('promise, isGeoServiceAvailable: ' + JSON.stringify(result)); @@ -825,13 +841,16 @@ Checks whether the (reverse) geocoding service is available. This API uses a pro ``` -## geolocation.getAddressesFromLocation +## geolocation.getAddressesFromLocation(deprecated) 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. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -843,8 +862,8 @@ Converts coordinates into geographic description through reverse geocoding. This | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the reverse geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest, (err, data) => { @@ -858,13 +877,16 @@ Converts coordinates into geographic description through reverse geocoding. This ``` -## geolocation.getAddressesFromLocation +## geolocation.getAddressesFromLocation(deprecated) getAddressesFromLocation(request: ReverseGeoCodeRequest): Promise<Array<GeoAddress>>; Converts coordinates into geographic description through reverse geocoding. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocation](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocation-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -876,13 +898,13 @@ Converts coordinates into geographic description through reverse geocoding. This **Return value** - | Name| Description| - | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Promise used to return the reverse geocoding result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|Promise used to return the reverse geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var reverseGeocodeRequest = {"latitude": 31.12, "longitude": 121.11, "maxItems": 1}; geolocation.getAddressesFromLocation(reverseGeocodeRequest).then((data) => { @@ -891,13 +913,16 @@ Converts coordinates into geographic description through reverse geocoding. This ``` -## geolocation.getAddressesFromLocationName +## geolocation.getAddressesFromLocationName(deprecated) 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. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -909,8 +934,8 @@ Converts geographic description into coordinates through geocoding. This API use | callback | AsyncCallback<Array<[GeoAddress](#geoaddress)>> | Yes| Callback used to return the geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest, (err, data) => { @@ -924,13 +949,16 @@ Converts geographic description into coordinates through geocoding. This API use ``` -## geolocation.getAddressesFromLocationName +## geolocation.getAddressesFromLocationName(deprecated) getAddressesFromLocationName(request: GeoCodeRequest): Promise<Array<GeoAddress>> Converts geographic description into coordinates through geocoding. This API uses a promise to return the result. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getAddressesFromLocationName](js-apis-geoLocationManager.md#geolocationmanagergetaddressesfromlocationname-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geocoder @@ -942,13 +970,13 @@ Converts geographic description into coordinates through geocoding. This API use **Return value** - | Name| Description| - | -------- | -------- | - | Promise<Array<[GeoAddress](#geoaddress)>> | Callback used to return the geocoding result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<Array<[GeoAddress](#geoaddress)>> | Array<[GeoAddress](#geoaddress)>|NA|Promise used to return the geocoding result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var geocodeRequest = {"description": "No. xx, xx Road, Pudong District, Shanghai", "maxItems": 1}; geolocation.getAddressesFromLocationName(geocodeRequest).then((result) => { @@ -957,13 +985,17 @@ Converts geographic description into coordinates through geocoding. This API use ``` -## geolocation.getCachedGnssLocationsSize8+ +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(callback: AsyncCallback<number>): void; Obtains the number of cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -974,8 +1006,8 @@ Obtains the number of cached GNSS locations. | callback | AsyncCallback<number> | Yes| Callback used to return the number of cached GNSS locations. | **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize((err, size) => { if (err) { @@ -988,25 +1020,29 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.getCachedGnssLocationsSize8+ +## geolocation.getCachedGnssLocationsSize(deprecated) getCachedGnssLocationsSize(): Promise<number>; Obtains the number of cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.getCachedGnssLocationsSize](js-apis-geoLocationManager.md#geolocationmanagergetcachedgnsslocationssize-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss **Return value** - | Name| Description| - | -------- | -------- | - | Promise<number> | Promise used to return the number of cached GNSS locations.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<number> | number|NA|Promise used to return the number of cached GNSS locations.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.getCachedGnssLocationsSize().then((result) => { console.log('promise, getCachedGnssLocationsSize: ' + JSON.stringify(result)); @@ -1014,13 +1050,17 @@ Obtains the number of cached GNSS locations. ``` -## geolocation.flushCachedGnssLocations8+ +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(callback: AsyncCallback<boolean>): void; Obtains all cached GNSS locations and clears the GNSS cache queue. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss @@ -1031,8 +1071,8 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations((err, result) => { if (err) { @@ -1045,25 +1085,29 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.flushCachedGnssLocations8+ +## geolocation.flushCachedGnssLocations(deprecated) flushCachedGnssLocations(): Promise<boolean>; Obtains all cached GNSS locations and clears the GNSS cache queue. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.flushCachedGnssLocations](js-apis-geoLocationManager.md#geolocationmanagerflushcachedgnsslocations-1). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the operation result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Promise used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; geolocation.flushCachedGnssLocations().then((result) => { console.log('promise, flushCachedGnssLocations: ' + JSON.stringify(result)); @@ -1071,13 +1115,17 @@ Obtains all cached GNSS locations and clears the GNSS cache queue. ``` -## geolocation.sendCommand8+ +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand, callback: AsyncCallback<boolean>): void; -Sends an extended command to the location subsystem. This API can only be called by system applications. +Sends an extended command to the location subsystem. + +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -1085,12 +1133,12 @@ Sends an extended command to the location subsystem. This API can only be called | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes| Extended command (string) to be sent.| + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| | callback | AsyncCallback<boolean> | Yes| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo, (err, result) => { @@ -1104,13 +1152,17 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## geolocation.sendCommand8+ +## geolocation.sendCommand(deprecated) sendCommand(command: LocationCommand): Promise<boolean>; -Sends an extended command to the location subsystem. This API can only be called by system applications. +Sends an extended command to the location subsystem. + +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.sendCommand](js-apis-geoLocationManager.md#geolocationmanagersendcommand). -**Permission required**: ohos.permission.LOCATION +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core @@ -1118,17 +1170,17 @@ Sends an extended command to the location subsystem. This API can only be called | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | command | LocationCommand | Yes| Extended command (string) to be sent.| + | command | [LocationCommand](#locationcommand) | Yes| Extended command (string) to be sent.| **Return value** - | Name| Description| - | -------- | -------- | - | Promise<boolean> | Callback used to return the operation result.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | Promise<boolean> |boolean|NA| Callback used to return the operation result.| **Example** - - ```js + + ```ts import geolocation from '@ohos.geolocation'; var requestInfo = {'scenario': 0x301, 'command': "command_1"}; geolocation.sendCommand(requestInfo).then((result) => { @@ -1137,15 +1189,18 @@ Sends an extended command to the location subsystem. This API can only be called ``` -## LocationRequestPriority +## LocationRequestPriority(deprecated) Sets the priority of the location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestPriority](js-apis-geoLocationManager.md#locationrequestpriority). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | UNSET | 0x200 | Priority unspecified.| | ACCURACY | 0x201 | Location accuracy.| @@ -1153,15 +1208,18 @@ Sets the priority of the location request. | FIRST_FIX | 0x203 | Fast location. Use this option if you want to obtain a location as fast as possible.| -## LocationRequestScenario +## LocationRequestScenario(deprecated) Sets the scenario of the location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequestScenario](js-apis-geoLocationManager.md#locationrequestscenario). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | UNSET | 0x300 | Scenario unspecified.| | NAVIGATION | 0x301 | Navigation.| @@ -1171,15 +1229,18 @@ Sets the priority of the location request. | 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 +## GeoLocationErrorCode(deprecated) Enumerates error codes of the location service. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | INPUT_PARAMS_ERROR7+ | 101 | Incorrect input parameters.| | REVERSE_GEOCODE_ERROR7+ | 102 | Failed to call the reverse geocoding API.| @@ -1190,213 +1251,255 @@ Enumerates error codes of the location service. | LOCATION_REQUEST_TIMEOUT_ERROR7+ | 107 | Failed to obtain the location within the specified time.| -## ReverseGeoCodeRequest +## ReverseGeoCodeRequest(deprecated) Defines a reverse geocoding request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.ReverseGeoCodeRequest](js-apis-geoLocationManager.md#reversegeocoderequest). + +**Required permissions**: 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.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| latitude | number | Yes| Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude | number | Yes| Yes| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| -## GeoCodeRequest +## GeoCodeRequest(deprecated) Defines a geocoding request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoCodeRequest](js-apis-geoLocationManager.md#geocoderequest). + +**Required permissions**: 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.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| locale | string | Yes| Yes| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| description | string | Yes| Yes| Location description, for example, **No. xx, xx Road, Pudong New District, Shanghai**.| +| maxItems | number | Yes| Yes| Maximum number of location records to be returned.| +| minLatitude | number | Yes| Yes| Minimum latitude. This parameter is used with **minLongitude**, **maxLatitude**, and **maxLongitude** to specify the latitude and longitude ranges.| +| minLongitude | number | Yes| Yes| Minimum longitude.| +| maxLatitude | number | Yes| Yes| Maximum latitude.| +| maxLongitude | number | Yes| Yes| Maximum longitude.| -## GeoAddress +## GeoAddress(deprecated) Defines a geographic location. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeoAddress](js-apis-geoLocationManager.md#geoaddress). + +**Required permissions**: 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.| - - -## LocationRequest +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude7+ | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| +| locale7+ | string | Yes| No| Language used for the location description. **zh** indicates Chinese, and **en** indicates English.| +| placeName7+ | string | Yes| No| Landmark of the location.| +| countryCode7+ | string | Yes| No| Country code.| +| countryName7+ | string | Yes| No| Country name.| +| administrativeArea7+ | string | Yes| No| Administrative region name.| +| subAdministrativeArea7+ | string | Yes| No| Sub-administrative region name.| +| locality7+ | string | Yes| No| Locality information.| +| subLocality7+ | string | Yes| No| Sub-locality information.| +| roadName7+ | string | Yes| No| Road name.| +| subRoadName7+ | string | Yes| No| Auxiliary road information.| +| premises7+ | string | Yes| No| House information.| +| postalCode7+ | string | Yes| No| Postal code.| +| phoneNumber7+ | string | Yes| No| Phone number.| +| addressUrl7+ | string | Yes| No| Website URL.| +| descriptions7+ | Array<string> | Yes| No| Additional descriptions.| +| descriptionsSize7+ | number | Yes| No| Total number of additional descriptions.| + + +## LocationRequest(deprecated) Defines a location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationRequest](js-apis-geoLocationManager.md#locationrequest). + +**Required permissions**: 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.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| timeInterval | number | Yes| Yes| Time interval at which location information is reported.| +| distanceInterval | number | Yes| Yes| Distance interval at which location information is reported.| +| maxAccuracy | number | Yes| Yes| Location accuracy. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| -## CurrentLocationRequest +## CurrentLocationRequest(deprecated) Defines the current location request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CurrentLocationRequest](js-apis-geoLocationManager.md#currentlocationrequest). + +**Required permissions**: 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.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes| Priority of the location request.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes| Scenario of the location request.| +| maxAccuracy | number | Yes| Yes| Location accuracy, in meters. This parameter is valid only when the precise location function is enabled, and is invalid when the approximate location function is enabled.| +| timeoutMs | number | Yes| Yes| Timeout duration, in milliseconds. The minimum value is **1000**.| -## SatelliteStatusInfo8+ +## SatelliteStatusInfo(deprecated) Defines the satellite status information. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.SatelliteStatusInfo](js-apis-geoLocationManager.md#satellitestatusinfo). + +**Required permissions**: 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.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| satellitesNumber | number | Yes| No| Number of satellites.| +| satelliteIds | Array<number> | Yes| No| Array of satellite IDs.| +| carrierToNoiseDensitys | Array<number> | Yes| No| Carrier-to-noise density ratio, that is, **cn0**.| +| altitudes | Array<number> | Yes| No| Altitude information.| +| azimuths | Array<number> | Yes| No| Azimuth information.| +| carrierFrequencies | Array<number> | Yes| No| Carrier frequency.| -## CachedGnssLocationsRequest8+ +## CachedGnssLocationsRequest(deprecated) Represents a request for reporting cached GNSS locations. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.CachedGnssLocationsRequest](js-apis-geoLocationManager.md#cachedgnsslocationsrequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Gnss -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| reportingPeriodSec | number | Yes| Interval for reporting the cached GNSS locations, in milliseconds.| -| wakeUpCacheQueueFull | boolean | Yes| **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| reportingPeriodSec | number | Yes| Yes| Interval for reporting the cached GNSS locations, in milliseconds.| +| wakeUpCacheQueueFull | boolean | Yes| Yes | **true**: reports the cached GNSS locations to the application when the cache queue is full.
**false**: discards the cached GNSS locations when the cache queue is full.| -## Geofence8+ +## Geofence(deprecated) Defines a GNSS geofence. Currently, only circular geofences are supported. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Geofence](js-apis-geoLocationManager.md#geofence). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude | number | Yes| Latitude information.| -| longitude | number | Yes| Longitude information.| -| radius | number | Yes| Radius of a circular geofence.| -| expiration | number | Yes| Expiration period of a geofence, in milliseconds.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude | number | Yes| Yes | Latitude information.| +| longitude | number | Yes| Yes | Longitude information.| +| radius | number | Yes| Yes | Radius of a circular geofence.| +| expiration | number | Yes| Yes | Expiration period of a geofence, in milliseconds.| -## GeofenceRequest8+ +## GeofenceRequest(deprecated) Represents a GNSS geofencing request. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.GeofenceRequest](js-apis-geoLocationManager.md#geofencerequest). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Geofence -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| priority | LocationRequestPriority | Yes| Priority of the location information.| -| scenario | LocationRequestScenario | Yes| Location scenario.| -| geofence | Geofence | Yes| Geofence information.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| priority | [LocationRequestPriority](#locationrequestpriority) | Yes| Yes | Priority of the location information.| +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| geofence | [Geofence](#geofence)| Yes| Yes | Geofence information.| -## LocationPrivacyType8+ +## LocationPrivacyType(deprecated) Defines the privacy statement type. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationPrivacyType](js-apis-geoLocationManager.md#locationprivacytype). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | OTHERS | 0 | Other scenarios.| | STARTUP | 1 | Privacy statement displayed in the startup wizard.| | CORE_LOCATION | 2 | Privacy statement displayed when enabling the location service.| -## LocationCommand8+ +## LocationCommand(deprecated) Defines an extended command. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is supported since API version 8. +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.LocationCommand](js-apis-geoLocationManager.md#locationcommand). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| scenario | LocationRequestScenario | Yes| Location scenario.| -| command | string | Yes| Extended command, in the string format.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| scenario | [LocationRequestScenario](#locationrequestscenario) | Yes| Yes | Location scenario.| +| command | string | Yes| Yes | Extended command, in the string format.| -## Location +## Location(deprecated) Defines a location. -**Permission required**: ohos.permission.LOCATION +> **NOTE** +> This API is deprecated since API version 9. You are advised to use [geoLocationManager.Location](js-apis-geoLocationManager.md#location). + +**Required permissions**: ohos.permission.LOCATION **System capability**: SystemCapability.Location.Location.Core -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| latitude7+ | number | Yes| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| -| longitude7+ | number | Yes| Longitude information. A positive value indicates east longitude , and a negative value indicates west longitude .| -| altitude7+ | number | Yes| Location altitude, in meters.| -| accuracy7+ | number | Yes| Location accuracy, in meters.| -| speed7+ | number | Yes| Speed, in m/s.| -| timeStamp7+ | number | Yes| Location timestamp in the UTC format.| -| direction7+ | number | Yes| Direction information.| -| timeSinceBoot7+ | number | Yes| Location timestamp since boot.| -| additions7+ | Array<string> | No| Additional information.| -| additionSize7+ | number | No| Number of additional descriptions.| +| Name| Type| Readable|Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| latitude7+ | number | Yes| No| Latitude information. A positive value indicates north latitude, and a negative value indicates south latitude.| +| longitude7+ | number | Yes| No| Longitude information. A positive value indicates east longitude, and a negative value indicates west longitude.| +| altitude7+ | number | Yes| No| Location altitude, in meters.| +| accuracy7+ | number | Yes| No| Location accuracy, in meters.| +| speed7+ | number | Yes| No| Speed, in m/s.| +| timeStamp7+ | number | Yes| No| Location timestamp in the UTC format.| +| direction7+ | number | Yes| No| Direction information.| +| timeSinceBoot7+ | number | Yes| No| Location timestamp since boot.| +| additions7+ | Array<string> | Yes| No| Additional description.| +| additionSize7+ | number | Yes| No| Number of additional descriptions.| diff --git a/en/application-dev/reference/apis/js-apis-hashmap.md b/en/application-dev/reference/apis/js-apis-hashmap.md index f3deddcc499cfa9cb3b32c5b3951664dfa3d44cb..d39dbd1e6649359d5e6433fe11b0a2d68febf953 100644 --- a/en/application-dev/reference/apis/js-apis-hashmap.md +++ b/en/application-dev/reference/apis/js-apis-hashmap.md @@ -1,7 +1,6 @@ -# Nonlinear Container HashMap +# @ohos.util.HashMap (Nonlinear Container HashMap) > **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. **HashMap** is a map implemented based on the array, linked list, and red-black tree. It provides efficient data query, insertion, and removal. The elements in a **HashMap** instance are mappings of key-value pairs. Each key must be unique and have only one value. @@ -43,7 +42,7 @@ A constructor used to create a **HashMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -53,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashMap = new HashMap(); -try { - let hashMap2 = HashMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -77,7 +71,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -88,11 +82,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const hashMap = new HashMap(); let result = hashMap.isEmpty(); -try { - hashMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -118,7 +107,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -131,11 +120,6 @@ let hashMap = new HashMap(); let result = hashMap.hasKey("squirrel"); hashMap.set("squirrel", 123); let result1 = hashMap.hasKey("squirrel"); -try { - hashMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -161,7 +145,7 @@ Checks whether this container contains the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -174,11 +158,6 @@ let hashMap = new HashMap(); let result = hashMap.hasValue(123); hashMap.set("squirrel", 123); let result1 = hashMap.hasValue(123); -try { - hashMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -204,7 +183,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -217,11 +196,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.get("sparrow"); -try { - hashMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -241,7 +215,7 @@ Adds all elements in a **HashMap** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -255,11 +229,6 @@ hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let newHashMap = new HashMap(); hashMap.setAll(newHashMap); -try { - hashMap.setAll.bind({}, newHashMap)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -286,7 +255,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -297,11 +266,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashMap = new HashMap(); let result = hashMap.set("squirrel", 123); -try { - hashMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -327,7 +291,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -340,11 +304,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); let result = hashMap.remove("sparrow"); -try { - hashMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -358,7 +317,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -371,11 +330,6 @@ let hashMap = new HashMap(); hashMap.set("squirrel", 123); hashMap.set("sparrow", 356); hashMap.clear(); -try { - hashMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -395,7 +349,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -413,11 +367,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -437,7 +386,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -455,11 +404,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -486,7 +430,7 @@ Replaces an element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -498,17 +442,12 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let hashMap = new HashMap(); hashMap.set("sparrow", 123); let result = hashMap.replace("sparrow", 357); -try { - hashMap.replace.bind({}, "sparrow", 357)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: HashMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -518,7 +457,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -530,7 +469,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -545,13 +484,6 @@ hashMap.set("gull", 357); hashMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - hashMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -571,7 +503,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -590,11 +522,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -614,7 +541,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -640,9 +567,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-hashset.md b/en/application-dev/reference/apis/js-apis-hashset.md index 09cd4c914ad0c512f65f7ad05c1552ef6b29f90a..f2ece05248321395e2ca3f651ff32a462503d5c4 100644 --- a/en/application-dev/reference/apis/js-apis-hashset.md +++ b/en/application-dev/reference/apis/js-apis-hashset.md @@ -1,7 +1,6 @@ -# Nonlinear Container HashSet +# @ohos.util.HashSet (Nonlinear Container HashSet) > **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. **HashSet** is implemented based on [HashMap](js-apis-hashmap.md). In **HashSet**, only the **value** object is processed. @@ -51,7 +50,7 @@ A constructor used to create a **HashSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -61,11 +60,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashSet = new HashSet(); -try { - let hashSet2 = HashSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -85,7 +79,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -96,11 +90,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const hashSet = new HashSet(); let result = hashSet.isEmpty(); -try { - hashSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -126,7 +115,7 @@ Checks whether this container contains the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -139,11 +128,6 @@ let hashSet = new HashSet(); let result = hashSet.has("squirrel"); hashSet.add("squirrel"); let result1 = hashSet.has("squirrel"); -try { - hashSet.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -169,7 +153,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -180,11 +164,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let hashSet = new HashSet(); let result = hashSet.add("squirrel"); -try { - hashSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -210,7 +189,7 @@ Removes an element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -223,11 +202,6 @@ let hashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); let result = hashSet.remove("sparrow"); -try { - hashSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -241,7 +215,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -254,11 +228,6 @@ let hashSet = new HashSet(); hashSet.add("squirrel"); hashSet.add("sparrow"); hashSet.clear(); -try { - hashSet.remove.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -278,7 +247,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -296,17 +265,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - hashSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: HashSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -316,7 +280,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -324,11 +288,11 @@ callbackfn | -------- | -------- | -------- | -------- | | value | T | No| Value of the element that is currently traversed.| | key | T | No| Key of the element that is currently traversed (same as **value**).| -| set | HashSet<T> | No| Instance that invokes the **forEach** method.| +| set | HashSet<T> | No| Instance that invokes the **forEach** API.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -343,13 +307,6 @@ hashSet.add("squirrel"); hashSet.forEach((value, key) => { console.log("value:" + value, key); }); -try { - hashSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -368,7 +325,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -387,11 +344,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - hashSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -411,7 +363,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -436,9 +388,4 @@ while(temp != undefined) { console.log("value: " + temp); temp = iter.next().value; } -try { - hashSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index aefc93a933ecdf42a0d270134d81f17c8a5788af..260c8c541809f723cee63a3cf7f7ce9374ff886d 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -1,10 +1,10 @@ -# HiAppEvent +# @ohos.hiAppEvent (Application Event Logging) -This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. +The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. > **NOTE** -> -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [`@ohos.hiviewdfx.hiAppEvent`](js-apis-hiviewdfx-hiappevent.md) instead. +> - 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 @@ -17,13 +17,9 @@ import hiAppEvent from '@ohos.hiAppEvent'; Before using application event logging, you need to understand the requirements for related parameters. -**Event Domain** - -An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). - **Event Name** -An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start with an underscore (\_). +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (_). **Event Type** @@ -33,7 +29,7 @@ An event type is an enumerated value of [EventType](#eventtype). An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: -- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It cannot start or end with an underscore (\_). +- A parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a lowercase letter and cannot end with an underscore (\_). - The parameter value is a string, number, boolean, or array. - When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. - When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. @@ -47,20 +43,10 @@ Event callback can be a callback or promise that carries the return value obtain - If the return value is greater than **0**, invalid parameters are present in the event, and the event will be written to the event file after the invalid parameters are ignored. - If the return value is smaller than **0**, the event parameter verification fails, and the event will not be written to the event file. -**Subscription Callback** - -A subscription callback carries the subscription data obtained by invoking the watcher API. The input parameters are defined as follows: - -- **curRow**: number of events. -- **curSize**: event data size, in bytes. -- **holder**: event data holder, which can be used for processing subscription events. - -## hiAppEvent.write(deprecated) +## hiAppEvent.write write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback<void>): void -> **NOTE**
This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9) instead. - Writes event information to the event file of the current day. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.HiviewDFX.HiAppEvent @@ -72,7 +58,7 @@ Writes event information to the event file of the current day. This API uses an | eventName | string | Yes | Event name. | | eventType | [EventType](#eventtype) | Yes | Event type. | | keyValues | object | Yes | Event parameters. | -| callback | AsyncCallback<void> | No | Event callback.| +| callback | AsyncCallback<void> | Yes | Event callback.| **Example** @@ -90,12 +76,10 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str ``` -## hiAppEvent.write(deprecated) +## hiAppEvent.write write(eventName: string, eventType: EventType, keyValues: object): Promise<void> -> **NOTE**
This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9-1) instead. - Writes event information to the event file of the current day. This API uses a promise to return the result. **System capability**: SystemCapability.HiviewDFX.HiAppEvent @@ -127,97 +111,6 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str }); ``` -## hiAppEvent.write9+ - -write(info: [AppEventInfo](#appeventinfo9), callback: AsyncCallback<void>): void - -Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ------------------------------ | ---- | -------------- | -| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.| -| callback | AsyncCallback<void> | No | Event callback.| - -**Example** - -```js -hiAppEvent.write({ - domain: "test_domain", - name: "test_event", - eventType: hiAppEvent.EventType.FAULT, - params: { - int_data: 100, - str_data: "strValue" - } -}, (err, value) => { - if (err) { - // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. - console.error(`failed to write event because ${err.code}`); - return; - } - - // Event writing success - console.log(`success to write event: ${value}`); -}); -``` - -## hiAppEvent.write9+ - -write(info: [AppEventInfo](#appeventinfo9)): Promise<void> - -Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses a promise to return the result. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Parameters** - -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | -------------- | -| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.| - -**Return value** - -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.| - -**Example** - -```js -hiAppEvent.write({ - domain: "test_domain", - name: "test_event", - eventType: hiAppEvent.EventType.FAULT, - params: { - int_data: 100, - str_data: "strValue" - } -}).then((value) => { - // Event writing success - console.log(`success to write event: ${value}`); -}).catch((err) => { - // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. - console.error(`failed to write event because ${err.code}`); -}); -``` - -## AppEventInfo9+ - -Defines parameters for an **AppEventInfo** object. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ---------- | -| domain | string | Yes | Event domain.| -| name | string | Yes | Event name.| -| eventType | [EventType](#eventtype) | Yes | Event type.| -| params | object | Yes | Event parameters.| - ## hiAppEvent.configure configure(config: ConfigOption): boolean @@ -258,230 +151,11 @@ Provides the configuration items for application event logging. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------------------------------------ | | disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.| | maxStorage | string | No | Maximum size of the event file storage directory. The default value is 10M. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.| -## hiAppEvent.addWatcher9+ - -addWatcher(watcher: [Watcher](#watcher9)): [AppEventPackageHolder](#appeventpackageholder9) - -Adds an event watcher. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | -------------------- | ---- | ---------------- | -| watcher | [Watcher](#watcher9) | Yes | Event watcher.| - -**Return value** - -| Type | Description | -| ------------------------------------------------ | ------------------------------------ | -| [AppEventPackageHolder](#appeventpackageholder9) | Subscription data holder. If the subscription fails, **null** will be returned.| - -**Example** - -```js -// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered. -hiAppEvent.addWatcher({ - name: "watcher1", - appEventFilters: [ - { - domain: "domain_test1", - eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR] - } - ], - triggerCondition: { - row: 10, - size: 1000, - timeOut: 1 - }, - onTrigger: function (curRow, curSize, holder) { - if (holder == null) { - console.error("holder is null"); - return; - } - let eventPkg = null; - while ((eventPkg = holder.takeNext()) != null) { - console.info("eventPkg.packageId=" + eventPkg.packageId); - console.info("eventPkg.row=" + eventPkg.row); - console.info("eventPkg.size=" + eventPkg.size); - for (const eventInfo of eventPkg.data) { - console.info("eventPkg.data=" + eventInfo); - } - } - } -}); - -// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder. -let holder = hiAppEvent.addWatcher({ - name: "watcher2", -}); -if (holder != null) { - let eventPkg = null; - while ((eventPkg = holder.takeNext()) != null) { - console.info("eventPkg.packageId=" + eventPkg.packageId); - console.info("eventPkg.row=" + eventPkg.row); - console.info("eventPkg.size=" + eventPkg.size); - for (const eventInfo of eventPkg.data) { - console.info("eventPkg.data=" + eventInfo); - } - } -} -``` - -## hiAppEvent.removeWatcher9+ - -removeWatcher(watcher: [Watcher](#watcher9)): void - -Removes an event watcher. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | -------------------- | ---- | ---------------- | -| watcher | [Watcher](#watcher9) | Yes | Event watcher.| - -**Example** - -```js -// 1. Define a watcher. -let watcher = { - name: "watcher1", -} - -// 2. Add the watcher to subscribe to application events. -hiAppEvent.addWatcher(watcher); - -// 3. Remove the watcher to unsubscribe from application events. -hiAppEvent.removeWatcher(watcher); -``` - -## Watcher9+ - -Defines parameters for a **Watcher** object. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -| Name | Type | Mandatory| Description | -| ---------------- | ------------------------------------------------------------ | ---- | -------------------------------- | -| name | string | Yes | Unique watcher name.| -| triggerCondition | [TriggerCondition](#triggercondition9) | No | Subscription callback trigger condition. | -| appEventFilters | [AppEventFilter](#appeventfilter9)[] | No | Application event filter criteria. | -| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder9)) => void | No | Subscription callback. | - -## TriggerCondition9+ - -Defines parameters for a **TriggerCondition** object. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -| Name | Type| Mandatory| Description | -| ------- | -------- | ---- | -------------------------------------- | -| row | number | No | Number of events. | -| size | number | No | Event data size, in bytes.| -| timeOut | number | No | Timeout interval, in unit of 30s. | - -## AppEventFilter9+ - -Defines parameters for an **AppEventFilter** object. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -| Name | Type | Mandatory| Description | -| ---------- | ------------------------- | ---- | ------------------------ | -| domain | string | Yes | Event domain. | -| eventTypes | [EventType](#eventtype)[] | No | Event types.| - -## AppEventPackageHolder9+ - -Defines a subscription data holder for processing subscription events. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -### constructor9+ - -constructor(watcherName: string); - -A constructor used to create a **holder** object. It is called automatically when a **Watcher** object is added. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Example** - -```js -let holder = hiAppEvent.addWatcher({ - name: "watcher", -}); -``` - -### setSize9+ - -setSize(size: number): void - -Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Example** - -```js -let holder = hiAppEvent.addWatcher({ - name: "watcher", -}); -holder.setSize(1000); -``` - -### takeNext9+ - -takeNext(): [AppEventPackage](#appeventpackage9) - -Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Example** - -```js -let holder = hiAppEvent.addWatcher({ - name: "watcher", -}); -let eventPkg = holder.takeNext(); -``` - -## AppEventPackage9+ - -Defines parameters for an **AppEventPackage** object. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -| Name | Type| Description | -| --------- | -------- | ------------------------------ | -| packageId | number | Event package ID, which is named from **0** in ascending order. | -| row | number | Number of events in the event package. | -| size | number | Data size of the event package, in bytes.| -| data | string[] | Event data in the event package. | - -## hiAppEvent.clearData9+ - -clearData(): void - -Clears local logging data. - -**System capability**: SystemCapability.HiviewDFX.HiAppEvent - -**Example** - -```js -hiAppEvent.clearData(); -``` - ## EventType @@ -489,12 +163,12 @@ Enumerates event types. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Default Value| Description | -| --------- | ------ | -------------- | -| FAULT | 1 | Fault event.| -| STATISTIC | 2 | Statistical event.| -| SECURITY | 3 | Security event.| -| BEHAVIOR | 4 | Behavior event.| +| Name | Value | Description | +| --------- | ---- | -------------- | +| FAULT | 1 | Fault event.| +| STATISTIC | 2 | Statistical event.| +| SECURITY | 3 | Security event.| +| BEHAVIOR | 4 | Behavior event.| ## Event @@ -503,11 +177,11 @@ Provides constants that define the names of all predefined events. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Type| Readable| Writable| Description | -| ------------------------- | -------- | ---- | ---- | -------------------- | -| USER_LOGIN | string | Yes | No | User login event. | -| USER_LOGOUT | string | Yes | No | User logout event. | -| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------ | ---- | ---- | -------------------- | +| USER_LOGIN | string | Yes | No | User login event. | +| USER_LOGOUT | string | Yes | No | User logout event. | +| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| ## Param @@ -516,8 +190,8 @@ Provides constants that define the names of all predefined event parameters. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Type| Readable| Writable| Description | -| ------------------------------- | -------- | ---- | ---- | ------------------ | -| USER_ID | string | Yes | No | Custom user ID. | -| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | -| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| +| Name | Type | Readable| Writable| Description | +| ------------------------------- | ------ | ---- | ---- | ------------------ | +| USER_ID | string | Yes | No | Custom user ID. | +| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md index ec2833f49fca4f4f570ac45f25cdefaa5741702e..3a5687e9ee0b31e29450d72ad7f618a128b30050 100644 --- a/en/application-dev/reference/apis/js-apis-hichecker.md +++ b/en/application-dev/reference/apis/js-apis-hichecker.md @@ -1,6 +1,6 @@ -# HiChecker +# @ohos.hichecker (HiChecker) -HiChecker is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. +The **hichecker** module is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them. > **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. @@ -27,8 +27,104 @@ Provides the constants of all rule types. | RULE_CHECK_ABILITY_CONNECTION_LEAK | bigint | Caution rule, which is programmed to detect whether ability leakage has occurred. | +## hichecker.addCheckRule9+ + +## hichecker.addRule +addCheckRule(rule: bigint): void + +Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. + +**System capability**: SystemCapability.HiviewDFX.HiChecker + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| rule | bigint | Yes | Rule to be added.| + +**Example** + +```js +try { + // Add a rule. + hichecker.addCheckRule(hichecker.RULE_CAUTION_PRINT_LOG);} + // Add multiple rules. + hichecker.addCheckRule( + hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); +catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); +} +``` + +## hichecker.removeCheckRule9+ + +removeCheckRule(rule: bigint): void + +Removes one or more rules. The removed rules will become ineffective. + +**System capability**: SystemCapability.HiviewDFX.HiChecker + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| rule | bigint | Yes | Rule to be removed.| + +**Example** + +```js +try { + // Remove a rule. + hichecker.removeCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); + // Remove multiple rules. + hichecker.removeCheckRule( + hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); +catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); +} +``` + +## hichecker.containsCheckRule9+ + +containsCheckRule(rule: bigint): boolean + +Checks whether the specified rule exists in the collection of added rules. If the rule is of the thread level, this operation is performed only on the current thread. + +**System capability**: SystemCapability.HiviewDFX.HiChecker + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| rule | bigint | Yes | Rule to be checked.| + +**Return value** + +| Type | Description | +| ------- | ---------------------------------------------------------- | +| boolean | Returns **true** if the rule exists in the collection of added rules; returns **false** otherwise.| + +**Example** + +```js +try { + // Add a rule. + hichecker.addCheckRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); + + // Check whether the added rule exists in the collection of added rules. + hichecker.containsCheckRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); // return true; + hichecker.containsCheckRule(hichecker.RULE_CAUTION_PRINT_LOG); // return false; +catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); +} +``` + +## hichecker.addRule(deprecated) + ## hichecker.addRule +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hichecker.addCheckRule](#hicheckeraddcheckrule9) instead. + addRule(rule: bigint): void Adds one or more rules. HiChecker detects unexpected operations or gives feedback based on the added rules. @@ -52,10 +148,12 @@ hichecker.addRule( hichecker.RULE_CAUTION_PRINT_LOG | hichecker.RULE_CAUTION_TRIGGER_CRASH); ``` -## hichecker.removeRule +## hichecker.removeRule(deprecated) removeRule(rule: bigint): void +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hichecker.removeCheckRule](#hicheckerremovecheckrule9) instead. + Removes one or more rules. The removed rules will become ineffective. **System capability**: SystemCapability.HiviewDFX.HiChecker @@ -101,10 +199,12 @@ hichecker.addRule(hichecker.RULE_THREAD_CHECK_SLOW_PROCESS); hichecker.getRule(); // return 1n; ``` -## hichecker.contains +## hichecker.contains(deprecated) contains(rule: bigint): boolean +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hichecker.containsCheckRule](#hicheckercontainscheckrule9) instead. + Checks whether the specified rule exists in the collection of added rules. If the rule is of the thread level, this operation is performed only on the current thread. **System capability**: SystemCapability.HiviewDFX.HiChecker diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md index 53af9c42a3aa2d8cddf8d38290f7a29c30f8f9d6..189d855e894451790976eee2c3816cf17ae950b9 100644 --- a/en/application-dev/reference/apis/js-apis-hidebug.md +++ b/en/application-dev/reference/apis/js-apis-hidebug.md @@ -1,10 +1,10 @@ -# HiDebug +# @ohos.hidebug (HiDebug) -> **NOTE** -> +The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. + +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -You can run the hidebug command to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data. ## Modules to Import @@ -17,7 +17,7 @@ import hidebug from '@ohos.hidebug'; getNativeHeapSize(): bigint -Obtains the total size of the heap memory of this application. +Obtains the total heap memory size of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. @@ -25,9 +25,9 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. **Return value** -| Type | Description | +| Type | Description | | ------ | --------------------------- | -| bigint | Total size of the heap memory of this application, in kB.| +| bigint | Total heap memory size of the application, in KB.| **Example** @@ -40,17 +40,17 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. getNativeHeapAllocatedSize(): bigint -Obtains the size of the allocated heap memory of this application. +Obtains the allocated heap memory size of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | --------------------------------- | -| bigint | Size of the allocated heap memory of this application, in kB.| +| bigint | Allocated heap memory of the application, in KB.| **Example** @@ -63,18 +63,17 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. getNativeHeapFreeSize(): bigint -Obtains the size of the free heap memory of this application. +Obtains the free heap memory size of this application. This API is defined but not implemented in OpenHarmony 3.1 Release. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | ------------------------------- | -| bigint | Size of the free heap memory of this application, in kB.| - +| bigint | Free heap memory size of the application, in KB.| **Example** ```js @@ -86,16 +85,15 @@ This API is defined but not implemented in OpenHarmony 3.1 Release. getPss(): bigint -Obtains the size of the used physical memory of this process. +Obtains the size of the physical memory actually used by the application process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | ------------------------- | -| bigint | Used physical memory of this process, in kB.| - +| bigint | Size of the physical memory actually used by the application process, in KB.| **Example** ```js @@ -107,15 +105,15 @@ Obtains the size of the used physical memory of this process. getSharedDirty(): bigint -Obtains the size of the shared dirty memory of this process. +Obtains the size of the shared dirty memory of a process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | -------------------------- | -| bigint | Size of the shared dirty memory of this process, in kB.| +| bigint | Size of the shared dirty memory of the process, in KB.| **Example** @@ -127,15 +125,15 @@ Obtains the size of the shared dirty memory of this process. getPrivateDirty(): bigint -Obtains the size of the private dirty memory of this process. +Obtains the size of the private dirty memory of a process. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | -------------------------- | -| bigint | Size of the private dirty memory of this process, in kB.| +| bigint | Size of the private dirty memory of the process, in KB.| **Example** @@ -147,17 +145,17 @@ Obtains the size of the private dirty memory of this process. getCpuUsage(): number -Obtains the CPU usage of this process. +Obtains the CPU usage of a process. For example, if the CPU usage is **50%**, **0.5** is returned. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug - **Return value** + | Type | Description | | ------ | -------------------------- | -| number | CPU usage of this process.| +| number | CPU usage of the process.| **Example** @@ -165,11 +163,13 @@ For example, if the CPU usage is **50%**, **0.5** is returned. let cpuUsage = hidebug.getCpuUsage(); ``` -## hidebug.startProfiling +## hidebug.startProfiling(deprecated) startProfiling(filename : string) : void -Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead. + +Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -191,11 +191,13 @@ hidebug.stopProfiling(); -## hidebug.stopProfiling +## hidebug.stopProfiling(deprecated) stopProfiling() : void -Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the following sequences is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead. + +Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -209,17 +211,19 @@ hidebug.startProfiling("cpuprofiler-20220216"); hidebug.stopProfiling(); ``` -## hidebug.dumpHeapData +## hidebug.dumpHeapData(deprecated) dumpHeapData(filename : string) : void -Exports data from the specified heap file. +> **NOTE**
This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead. + +Exports the heap data. **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | | filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.| @@ -231,11 +235,11 @@ hidebug.dumpHeapData("heap-20220216"); ## hidebug.getServiceDump9+ -getServiceDump(serviceid : number) : string +getServiceDump(serviceid : number, fd : number, args : Array\) : void -Obtains information on the specified system service. +Obtains system service information. -This is a system API and cannot be called by third-party applications. +**Required permissions**: ohos.permission.DUMP **System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -243,16 +247,116 @@ This is a system API and cannot be called by third-party applications. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| serviceid | number | Yes | ID of the system service. | +| serviceid | number | Yes | Obtains the system service information based on the specified service ID.| +| fd | number | Yes | File descriptor to which data is written by the API.| +| args | Array\ | Yes | Parameter list corresponding to the **Dump** API of the system service.| -**Return value** -| Type | Description | -| ------ | -------------------------- | -| string | Absolute path of the file that contains the service information to dump. | **Example** ```js -let serviceId = 10; -let pathName = hidebug.getServiceDump(serviceId); +import fileio from '@ohos.fileio' +import hidebug from '@ohos.hidebug' +import featureAbility from '@ohos.ability.featureAbility' + +let context = featureAbility.getContext(); +context.getFilesDir().then((data) => { + var path = data + "/serviceInfo.txt" + console.info("output path: " + path) + let fd = fileio.openSync(path, 0o102, 0o666) + var serviceId = 10 + var args = new Array("allInfo") + try { + hidebug.getServiceDump(serviceId, fd, args) + } catch (error) { + console.info(error.code) + console.info(error.message) + } + fileio.closeSync(fd); +}) +``` + +## hidebug.startJsCpuProfiling9+ + +startJsCpuProfiling(filename : string) : void + +Starts the profiling method. `startJsCpuProfiling()` and `stopJsCpuProfiling()` are called in pairs. `startJsCpuProfiling()` always occurs before `stopJsCpuProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. + +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.| + +**Example** + +```js +import hidebug from '@ohos.hidebug' + +try { + hidebug.startJsCpuProfiling("cpu_profiling"); + ... + hidebug.stopJsCpuProfiling(); +} catch (error) { + console.info(error.code) + console.info(error.message) +} +``` + +## hidebug.stopJsCpuProfiling9+ + +stopJsCpuProfiling() : void + +Stops the profiling method. `startJsCpuProfiling()` and `stopJsCpuProfiling()` are called in pairs. `startJsCpuProfiling()` always occurs before `stopJsCpuProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`. + +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.| + +**Example** + +```js +import hidebug from '@ohos.hidebug' + +try { + hidebug.startJsCpuProfiling("cpu_profiling"); + ... + hidebug.stopJsCpuProfiling(); +} catch (error) { + console.info(error.code) + console.info(error.message) +} +``` + +## hidebug.dumpJsHeapData9+ + +dumpJsHeapData(filename : string) : void + +Exports the heap data. + +**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.| + +**Example** + +```js +import hidebug from '@ohos.hidebug' + +try { + hidebug.dumpJsHeapData("heapData"); +} catch (error) { + console.info(error.code) + console.info(error.message) +} ``` diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md index c01d3ce2f21c64cca00b453a3d3a6448b84fc22f..54355b12b723cf9cad06f5a4064568d5d772bea5 100644 --- a/en/application-dev/reference/apis/js-apis-hilog.md +++ b/en/application-dev/reference/apis/js-apis-hilog.md @@ -1,6 +1,6 @@ -# HiLog +# @ohos.hilog (HiLog) -The HiLog subsystem allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. +The **hilog** module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs. > **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. @@ -45,7 +45,7 @@ Enumerates the log levels. **System capability**: SystemCapability.HiviewDFX.HiLog -| Name | Default Value| Description | +| Name | Value| Description | | ----- | ------ | ------------------------------------------------------------ | | DEBUG | 3 | Log level used to record more detailed process information than INFO logs to help developers analyze service processes and locate faults.| | INFO | 4 | Log level used to record key service process nodes and exceptions that occur during service running,
for example, no network signal or login failure.
These logs should be recorded by the dominant module in the service to avoid repeated logging conducted by multiple invoked modules or low-level functions.| diff --git a/en/application-dev/reference/apis/js-apis-hisysevent.md b/en/application-dev/reference/apis/js-apis-hisysevent.md index 553ff5a9925a30f262acb49bb69cd4e95c7bd95b..b61207a81a9be58f9b8b405535e118757218529e 100644 --- a/en/application-dev/reference/apis/js-apis-hisysevent.md +++ b/en/application-dev/reference/apis/js-apis-hisysevent.md @@ -1,10 +1,10 @@ -# System Event Logging +# @ohos.hiSysEvent (System Event Logging) -Provides system event logging APIs for system HAP applications. +The **hiSysEvent** module provides the system event logging functions, such as configuring trace points, subscribing to system events, and querying system events written to the event file. > **NOTE** > - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - The APIs of this module are system APIs. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -19,7 +19,7 @@ Enumerates event types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name | Default Value | Description | +| Name| Value| Description| | -------- | -------- | -------- | | FAULT | 1 | Error event.| | STATISTIC | 2 | Statistic event.| @@ -32,7 +32,7 @@ Defines a system event. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -50,11 +50,26 @@ Writes event information to the event file. This API uses an asynchronous callba **Parameters** -| Name | Type | Mandatory | Description | +| Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | ------------------------------------------------------------ | | info | [SysEventInfo](#syseventinfo) | Yes| System event information.| | callback | AsyncCallback<void> | Yes| Callback used to process the received return value.
- Value **0**: The event verification is successful, and the event will be written to the event file asynchronously.
- A value greater than **0**: Invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
- A value smaller than **0**: The event parameter verification fails, and the event will not be written to the event file.| +**Error codes** + +For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md). + +| ID| Error Message| +| ------- | ----------------------------------------------------------------- | +| 11200001 | Invalid event domain. | +| 11200002 | Invalid event name. | +| 11200003 | Abnormal environment. | +| 11200004 | Length of the event is over limit. | +| 11200051 | Invalid event parameter. | +| 11200052 | Size of the event parameter of the string type is over limit. | +| 11200053 | Count of event parameters is over limit. | +| 11200054 | Count of event parameter of the array type is over limit. | + **Example** ```js @@ -91,16 +106,31 @@ Writes event information to the event file. This API uses a promise to return th **Parameters** -| Name | Type | Mandatory | Description| +| Name | Type | Mandatory| Description| | --------- | ----------------------- | ---- | --------------- | | info | [SysEventInfo](#syseventinfo) | Yes | System event information.| **Return value** -| Type | Description | +| Type | Description | | ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise used to return the result. Depending on whether event writing is successful, you can use the **then()** or **catch()** method to process the callback.| +**Error codes** + +For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md). + +| ID| Error Message| +| -------- | ---------------------------------------------------------------- | +| 11200001 | Invalid event domain. | +| 11200002 | Invalid event name. | +| 11200003 | Abnormal environment. | +| 11200004 | Length of the event is over limit. | +| 11200051 | Invalid event parameter. | +| 11200052 | Size of the event parameter of the string type is over limit. | +| 11200053 | Count of event parameters is over limit. | +| 11200054 | Count of event parameter of the array type is over limit. | + **Example** ```js @@ -138,7 +168,7 @@ Enumerates matching rule types. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name | Default Value | Description | +| Name| Value| Description| | -------- | -------- | -------- | | WHOLE_WORD | 1 | Whole word matching.| | PREFIX | 2 | Prefix matching.| @@ -146,11 +176,11 @@ Enumerates matching rule types. ## WatchRule -Defines rules for event subscription. +Defines event subscription rules. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| | name | string | Yes| Event name.| @@ -163,15 +193,15 @@ Defines a watcher for event subscription. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| rules | [WatchRule](#watchrule)[] | Yes| Array of matching rules for event subscription.| +| rules | [WatchRule](#watchrule)[] | Yes| Array of matching event subscription rules.| | onEvent | function | Yes| Callback for event subscription: (info: [SysEventInfo](#syseventinfo)) => void| | onServiceDied | function | Yes| Callback for disabling of event subscription: () => void| ## hiSysEvent.addWatcher -addWatcher(watcher: Watcher): number +addWatcher(watcher: Watcher): void Adds a watcher for event subscription. @@ -181,10 +211,19 @@ Adds a watcher for event subscription. **Parameters** -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| +**Error codes** + +For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md). + +| ID| Error Message| +| -------- | ----------------------------------- | +| 11200101 | Count of watchers is over limit. | +| 11200102 | Count of watch rules is over limit. | + **Example** ```js @@ -213,7 +252,7 @@ try { ## hiSysEvent.removeWatcher -removeWatcher(wathcer: Watcher): number +removeWatcher(watcher: Watcher): void Removes a watcher used for event subscription. @@ -223,10 +262,18 @@ Removes a watcher used for event subscription. **Parameters** -| Name| Type | Mandatory | Description | -| ------ | ------------- | ---- | ------------------------ | +| Name| Type | Mandatory| Description | +| ------ | ------------- | ---- | ------------------------- | | watcher | [Watcher](#watcher) | Yes| Watcher for event subscription.| +**Error codes** + +For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md). + +| ID| Error Message| +| -------- | --------------------------- | +| 11200201 | The watcher does not exist. | + **Example** ```js @@ -256,26 +303,26 @@ try { ## QueryArg -Defines arguments for event query. +Defines arguments for an event query. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| beginTime | number | Yes| Start time (13-digit timestamp) for event query.| -| endTime | number | Yes| End time (13-digit timestamp) for event query.| +| beginTime | number | Yes| Start time (13-digit timestamp) for the event query.| +| endTime | number | Yes| End time (13-digit timestamp) for the event query.| | maxEvents | number | Yes| Maximum number of events that can be queried.| ## QueryRule -Defines rules for event query. +Defines event query rules. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | domain | string | Yes| Event domain.| -| names | string[] | Yes| Array of event names.| +| names | string[] | Yes| Array of event names. A **QueryRule** object contains multiple system event names.| ## Querier @@ -283,14 +330,14 @@ Defines an event query instance. **System capability**: SystemCapability.HiviewDFX.HiSysEvent -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| onQuery | function | Yes| Callback of queried events: (infos: [SysEventInfo](#syseventinfo)[]) => void| -| onComplete | function | Yes| Callback of query result statistics: (reason: number, total: number) => void| +| onQuery | function | Yes| Callback used to return the queried system events: (infos: [SysEventInfo](#syseventinfo)[]) => void.| +| onComplete | function | Yes| Callback used to return the query result statistics: (reason: number, total: number) => void| ## hiSysEvent.query -query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): number +query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): void Queries system events. @@ -300,12 +347,23 @@ Queries system events. **Parameters** -| Name| Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | ------ | ----------------------------- | ---- | ------------------------ | | queryArg | [QueryArg](#queryarg) | Yes | Arguments for event query.| | rules | [QueryRule](#queryrule)[] | Yes | Array of event query rules.| | querier | [Querier](#querier) | Yes | Event query instance.| +**Error codes** + +For details about the error codes, see [HiSysEvent Error Codes](../errorcodes/errorcode-hisysevent.md). + +| ID| Error Message| +| -------- | ------------------------------------------- | +| 11200301 | Count of query rules is over limit. | +| 11200302 | Invalid query rule. | +| 11200303 | Count of concurrent queriers is over limit. | +| 11200304 | Query frequency is over limit. | + **Example** ```js diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md index 198615d8bf57c3749b527eb7fcc7fccdcaeb9fe1..b72b026ce908bbde85e385f46212d32e4a7fd61b 100644 --- a/en/application-dev/reference/apis/js-apis-hitracechain.md +++ b/en/application-dev/reference/apis/js-apis-hitracechain.md @@ -1,8 +1,8 @@ -# Distributed Call Chain Tracing +# @ohos.hiTraceChain (Distributed Call Chain Tracing) -This module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points. +The **hiTraceChain** module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -18,7 +18,7 @@ Enumerates trace flag types. **System capability**: SystemCapability.HiviewDFX.HiTrace -| Name | Default Value | Description | +| Name | Value | Description | | -------- | -------- | -------- | | DEFAULT | 0 | Default flag. | | INCLUDE_ASYNC | 1 | Asynchronous call flag. By default, only synchronous calls are traced. If this flag is set, both synchronous and asynchronous calls will be traced. | @@ -35,7 +35,7 @@ Enumerates trace point types. **System capability**: SystemCapability.HiviewDFX.HiTrace -| Name| Default Value | Description | +| Name| Value | Description | | -------- | -------- | -------- | | CS | 0 | Client Send (CS) trace point. | | CR | 1 | Client Receive (CS) trace point. | @@ -49,7 +49,7 @@ Enumerates communication modes. **System capability**: SystemCapability.HiviewDFX.HiTrace -| Name| Default Value | Description | +| Name| Value | Description | | -------- | -------- | -------- | | DEFAULT | 0 | Default communication mode. | | THREAD | 1 | Inter-thread communication. | @@ -84,7 +84,7 @@ Starts call chain tracing. This API works in synchronous manner. | name | string | Yes| Traced service name. | | flags | number | No| Trace flag combination. For details, see [HiTraceFlag](#hitraceflag). | -**Return Value** +**Return value** | Type | Description | | -------- | -------- | @@ -126,7 +126,7 @@ Obtains the trace ID. This API works in synchronous manner. **System capability**: SystemCapability.HiviewDFX.HiTrace -**Return Value** +**Return value** | Type | Description | | -------- | -------- | @@ -187,7 +187,7 @@ Creates a trace span. This API works in synchronous manner. **System capability**: SystemCapability.HiviewDFX.HiTrace -**Return Value** +**Return value** | Type | Description | | -------- | -------- | @@ -240,7 +240,7 @@ Checks whether a **HiTraceId** instance is valid. This API works in synchronous | -------- | -------- | -------- | -------- | | id | [HiTraceId](#hitraceid) | Yes| **HiTraceId** instance. | -**Return Value** +**Return value** | Type | Description | | -------- | -------- | @@ -268,7 +268,7 @@ Checks whether the specified trace flag in the **HiTraceId** instance is enabled | id | [HiTraceId](#hitraceid) | Yes | **HiTraceId** instance. | | flag | [HiTraceFlag](#hitraceflag) | Yes | Specified trace flag. | -**Return Value** +**Return value** | Type | Description | | -------- | -------- | diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index 04a9db2a0e7bc00cb9ff8a017eb6e39c47d97f30..af19e063a728abd4feb7d7238051d94ca49c2459 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -1,9 +1,8 @@ -# Performance Tracing +# @ohos.hiTraceMeter (Performance Tracing) -The Performance Tracing module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. +The **hiTraceMeter** module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md new file mode 100644 index 0000000000000000000000000000000000000000..86e09db17bda0e6efa68bbeeb973a26f4a4ff467 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -0,0 +1,473 @@ +# @ohos.hiviewdfx.hiAppEvent (Application Event Logging) + +The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration. + +> **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 hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'; +``` + +## hiAppEvent.write + +write(info: [AppEventInfo](#appeventinfo), callback: AsyncCallback<void>): void + +Writes events to the event file of the current day through [AppEventInfo](#appeventinfo) objects. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo) | Yes | Application event object.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md). + +| ID| Error Message | +| -------- | --------------------------------------------- | +| 11100001 | Function is disabled. | +| 11101001 | Invalid event domain. | +| 11101002 | Invalid event name. | +| 11101003 | Invalid number of event parameters. | +| 11101004 | Invalid string length of the event parameter. | +| 11101005 | Invalid event parameter name. | +| 11101006 | Invalid array length of the event parameter. | + +**Example** + +```js +hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" + } +}, (err) => { + if (err) { + console.error(`code: ${err.code}, message: ${err.message}`); + return; + } + console.log(`success to write event`); +}); +``` + +## hiAppEvent.write + +write(info: [AppEventInfo](#appeventinfo)): Promise<void> + +Writes events to the event file of the current day through [AppEventInfo](#appeventinfo) objects. This API uses a promise to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo) | Yes | Application event object.| + +**Return value** + +| Type | Description | +| ------------------- | ------------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md). + +| ID| Error Message | +| -------- | --------------------------------------------- | +| 11100001 | Function is disabled. | +| 11101001 | Invalid event domain. | +| 11101002 | Invalid event name. | +| 11101003 | Invalid number of event parameters. | +| 11101004 | Invalid string length of the event parameter. | +| 11101005 | Invalid event parameter name. | +| 11101006 | Invalid array length of the event parameter. | + +**Example** + +```js +hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" + } +}).then(() => { + console.log(`success to write event`); +}).catch((err) => { + console.error(`code: ${err.code}, message: ${err.message}`); +}); +``` + +## AppEventInfo + +Defines parameters for an **AppEventInfo** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------- | +| domain | string | Yes | Event domain.| +| name | string | Yes | Event name.| +| eventType | [EventType](#eventtype) | Yes | Event type.| +| params | object | Yes | Event parameters.| + +## hiAppEvent.configure + +configure(config: [ConfigOption](configoption)): void + +Configures the application event logging function, such as setting the event logging switch and maximum size of the directory that stores the event logging files. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | ------------------------ | +| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.| + +**Error codes** + +For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 11103001 | Invalid max storage quota value. | + +**Example** + +```js +// Disable the event logging function. +hiAppEvent.configure({ + disable: true +}); + +// Set the maximum size of the file storage directory to 100 MB. +hiAppEvent.configure({ + maxStorage: '100M' +}); +``` + +## ConfigOption + +Configures options for application event logging. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------- | ------- | ---- | ------------------------------------------------------------ | +| disable | boolean | No | Whether to enable the event logging function. The default value is **false**. The value **true** means to disable the event logging function, and the value **false** means the opposite.| +| maxStorage | string | No | Maximum size of the directory that stores event logging files. The default value is **10M**.
If the directory size exceeds the specified quota when application event logging is performed, event logging files in the directory will be cleared one by one based on the generation time to ensure that directory size does not exceed the quota.| + +## hiAppEvent.addWatcher + +addWatcher(watcher: [Watcher](#watcher)): [AppEventPackageHolder](#appeventpackageholder) + +Adds a watcher to subscribe to application events. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher) | Yes | Watcher for application events.| + +**Return value** + +| Type | Description | +| ------------------------------------------------ | ------------------------------------ | +| [AppEventPackageHolder](#appeventpackageholder) | Subscription data holder. If the subscription fails, **null** will be returned.| + +**Error codes** + +For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 11102001 | Invalid watcher name. | +| 11102002 | Invalid filtering event domain. | +| 11102003 | Invalid row value. | +| 11102004 | Invalid size value. | +| 11102005 | Invalid timeout value. | + +**Example** + +```js +// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered. +hiAppEvent.addWatcher({ + name: "watcher1", + appEventFilters: [ + { + domain: "test_domain", + eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR] + } + ], + triggerCondition: { + row: 10, + size: 1000, + timeOut: 1 + }, + onTrigger: function (curRow, curSize, holder) { + if (holder == null) { + console.error("holder is null"); + return; + } + let eventPkg = null; + while ((eventPkg = holder.takeNext()) != null) { + console.info(`eventPkg.packageId=${eventPkg.packageId}`); + console.info(`eventPkg.row=${eventPkg.row}`); + console.info(`eventPkg.size=${eventPkg.size}`); + for (const eventInfo of eventPkg.data) { + console.info(`eventPkg.data=${eventInfo}`); + } + } + } +}); + +// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder. +let holder = hiAppEvent.addWatcher({ + name: "watcher2", +}); +if (holder != null) { + let eventPkg = null; + while ((eventPkg = holder.takeNext()) != null) { + console.info(`eventPkg.packageId=${eventPkg.packageId}`); + console.info(`eventPkg.row=${eventPkg.row}`); + console.info(`eventPkg.size=${eventPkg.size}`); + for (const eventInfo of eventPkg.data) { + console.info(`eventPkg.data=${eventInfo}`); + } + } +} +``` + +## hiAppEvent.removeWatcher + +removeWatcher(watcher: [Watcher](#watcher)): void + +Removes a watcher to unsubscribe from application events. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher) | Yes | Watcher for application events.| + +**Error codes** + +For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md). + +| ID| Error Message | +| -------- | --------------------- | +| 11102001 | Invalid watcher name. | + +**Example** + +```js +// 1. Define a watcher for application events. +let watcher = { + name: "watcher1", +} + +// 2. Add the watcher to subscribe to application events. +hiAppEvent.addWatcher(watcher); + +// 3. Remove the watcher to unsubscribe from application events. +hiAppEvent.removeWatcher(watcher); +``` + +## Watcher + +Defines parameters for a **Watcher** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Unique name of the watcher. | +| triggerCondition | [TriggerCondition](#triggercondition) | No | Subscription callback triggering condition. This parameter takes effect only when it is passed together with the callback. | +| appEventFilters | [AppEventFilter](#appeventfilter)[] | No | Subscription filtering condition. This parameter is passed only when subscription events need to be filtered. | +| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder)) => void | No | Subscription callback, which takes effect only when it is passed together with the callback triggering condition. The input arguments are described as follows:
**curRow**: total number of subscription events when the callback is triggered.
**curSize**: total size of subscribed events when the callback is triggered, in bytes.
**holder**: subscription data holder, which can be used to process subscribed events.| + +## TriggerCondition + +Defines callback triggering conditions. Subscription callback is triggered when any condition is met. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | -------------------------------------- | +| row | number | No | Number of events. | +| size | number | No | Event data size, in bytes.| +| timeOut | number | No | Timeout interval, in unit of 30s. | + +## AppEventFilter + +Defines parameters for an **AppEventFilter** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------------------ | +| domain | string | Yes | Event domain. | +| eventTypes | [EventType](#eventtype)[] | No | Event types.| + +## AppEventPackageHolder + +Defines a subscription data holder for processing subscription events. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +### constructor + +constructor(watcherName: string) + +Constructor of the **Watcher** class. When a watcher is added, the system automatically calls this API to create a subscription data holder object for the watcher and returns the holder object to the application. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------- | ---- | ------------------------ | +| watcherName | string | Yes | Watcher name.| + +**Example** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +``` + +### setSize + +setSize(size: number): void + +Sets the threshold for the data size of the application event package obtained each time. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------------- | +| size | number | Yes | Data size threshold, in bytes. The default value is **512*1024**.| + +**Error codes** + +For details about the error codes, see [Application Event Logging Error Codes](../errorcodes/errorcode-hiappevent.md). + +| ID| Error Message | +| -------- | ------------------- | +| 11104001 | Invalid size value. | + +**Example** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +holder.setSize(1000); +``` + +### takeNext + +takeNext(): [AppEventPackage](#appeventpackage) + +Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +let eventPkg = holder.takeNext(); +``` + +## AppEventPackage + +Defines parameters for an **AppEventPackage** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| --------- | -------- | ---- | ------------------------------ | +| packageId | number | Yes | Event package ID, which is named from **0** in ascending order. | +| row | number | Yes | Number of events in the event package. | +| size | number | Yes | Event size of the event package, in bytes.| +| data | string[] | Yes | Event data in the event package. | + +## hiAppEvent.clearData + +clearData(): void + +Clears local application event logging data. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +hiAppEvent.clearData(); +``` + + +## EventType + +Enumerates event types. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Value | Description | +| --------- | ---- | -------------- | +| FAULT | 1 | Fault event.| +| STATISTIC | 2 | Statistical event.| +| SECURITY | 3 | Security event.| +| BEHAVIOR | 4 | Behavior event.| + + +## Event + +Provides constants that define the names of all predefined events. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Readable| Writable| Description | +| ------------------------- | ------ | ---- | ---- | -------------------- | +| USER_LOGIN | string | Yes | No | User login event. | +| USER_LOGOUT | string | Yes | No | User logout event. | +| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| + + +## Param + +Provides constants that define the names of all predefined event parameters. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Readable| Writable| Description | +| ------------------------------- | ------ | ---- | ---- | ------------------ | +| USER_ID | string | Yes | No | Custom user ID. | +| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| diff --git a/en/application-dev/reference/apis/js-apis-http.md b/en/application-dev/reference/apis/js-apis-http.md index 294ed0fa79032d4e47e6c9c999183811d272acd3..3735792dd3f5ce66569fbebf3a1036019e7457ed 100644 --- a/en/application-dev/reference/apis/js-apis-http.md +++ b/en/application-dev/reference/apis/js-apis-http.md @@ -1,11 +1,9 @@ -# Data Request +# @ohos.net.http (Data Request) -This module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. +The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**. ->**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. -> +> **NOTE**
+> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -18,9 +16,9 @@ import http from '@ohos.net.http'; ```js import http from '@ohos.net.http'; -// Each HttpRequest corresponds to an HttpRequestTask object and cannot be reused. +// Each httpRequest corresponds to an HTTP request task and cannot be reused. let httpRequest = http.createHttp(); -// Subscribe to the HTTP response header, which is returned earlier than httpRequest. Whether to subscribe to the HTTP response header is up to your decision. +// This API is used to listen for the HTTP Response Header event, which is returned earlier than the result of the HTTP request. It is up to you whether to listen for HTTP Response Header events. // on('headerReceive', AsyncCallback) is replaced by on('headersReceive', Callback) since API version 8. httpRequest.on('headersReceive', (header) => { console.info('header: ' + JSON.stringify(header)); @@ -38,14 +36,18 @@ httpRequest.request( extraData: { "data": "data to send", }, - connectTimeout: 60000, // Optional. The default value is 60000, in ms. + expectDataType: http.HttpDataType.STRING, // Optional. This field specifies the type of the return data. + usingCache: true, // Optional. The default value is true. + priority: 1, // Optional. The default value is 1. + connectTimeout: 60000 // Optional. The default value is 60000, in ms. readTimeout: 60000, // Optional. The default value is 60000, in ms. + usingProtocol: http.HttpProtocol.HTTP1_1, // Optional. The default protocol type is automatically specified by the system. }, (err, data) => { if (!err) { - // data.result contains the HTTP response. Parse the response based on service requirements. + // data.result carries the HTTP response. Parse the response based on service requirements. console.info('Result:' + data.result); console.info('code:' + data.responseCode); - // data.header contains the HTTP response header. Parse the content based on service requirements. + // data.header carries the HTTP response header. Parse the content based on service requirements. console.info('header:' + JSON.stringify(data.header)); console.info('cookies:' + data.cookies); // 8+ } else { @@ -68,7 +70,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req **Return value** | Type | Description | -| :---------- | :----------------------------------------------------------- | +| ---------- | ----------------------------------------------------------- | | HttpRequest | An **HttpRequest** object, which contains the **request**, **destroy**, **on**, or **off** method.| **Example** @@ -78,10 +80,9 @@ import http from '@ohos.net.http'; let httpRequest = http.createHttp(); ``` - ## HttpRequest -HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. +Defines an HTTP request task. Before invoking APIs provided by **HttpRequest**, you must call [createHttp\(\)](#httpcreatehttp) to create an **HttpRequestTask** object. ### request @@ -89,7 +90,7 @@ request\(url: string, callback: AsyncCallback\\):void Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -121,7 +122,7 @@ request\(url: string, options: HttpRequestOptions, callback: AsyncCallback Initiates an HTTP request to a given URL. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -174,12 +174,12 @@ Initiates an HTTP request to a given URL. This API uses a promise to return the | Name | Type | Mandatory| Description | | ------- | ------------------ | ---- | ----------------------------------------------- | | url | string | Yes | URL for initiating an HTTP request. | -| options | HttpRequestOptions | Yes | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| +| options | HttpRequestOptions | No | Request options. For details, see [HttpRequestOptions](#httprequestoptions).| **Return value** | Type | Description | -| :------------------------------------- | :-------------------------------- | +| ------------------------------------- | -------------------------------- | | Promise<[HttpResponse](#httpresponse)> | Promise used to return the result.| @@ -226,7 +226,7 @@ on\(type: 'headerReceive', callback: AsyncCallback\): void Registers an observer for HTTP Response Header events. ->![](public_sys-resources/icon-note.gif) **NOTE** +>**NOTE** >This API has been deprecated. You are advised to use [on\('headersReceive'\)8+](#onheadersreceive8) instead. **System capability**: SystemCapability.Communication.NetStack @@ -250,14 +250,13 @@ httpRequest.on('headerReceive', (err, data) => { }); ``` - ### off\('headerReceive'\) off\(type: 'headerReceive', callback?: AsyncCallback\): void Unregisters the observer for HTTP Response Header events. ->![](public_sys-resources/icon-note.gif) **NOTE** +>**NOTE** > >1. This API has been deprecated. You are advised to use [off\('headersReceive'\)8+](#offheadersreceive8) instead. > @@ -301,14 +300,13 @@ httpRequest.on('headersReceive', (header) => { }); ``` - ### off\('headersReceive'\)8+ off\(type: 'headersReceive', callback?: Callback\): void Unregisters the observer for HTTP Response Header events. ->![](public_sys-resources/icon-note.gif) **NOTE** +>**NOTE** >You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -358,10 +356,14 @@ Specifies the type and value range of the optional parameters in the HTTP reques | Name | Type | Mandatory| Description | | -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | | method | [RequestMethod](#requestmethod) | No | Request method. | -| extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.8+ | +| extraData | string \| Object \| ArrayBuffer6+ | No | Additional data of the request.
- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.
- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.6+
- To pass in a string object, you first need to encode the object on your own.6+ | +| expectDataType9+ | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.| +| usingCache9+ | boolean | No | Whether to use the cache. The default value is **true**. | +| priority9+ | number | No | Priority. The value range is \[1,1000]. The default value is **1**. | | header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. | | readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. | | connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. | +| usingProtocol9+ | [HttpProtocol](#httpprotocol9) | No | Protocol. The default value is automatically specified by the system. | ## RequestMethod @@ -370,15 +372,15 @@ Defines an HTTP request method. **System capability**: SystemCapability.Communication.NetStack | Name | Value | Description | -| :------ | ------- | :------------------ | -| OPTIONS | OPTIONS | OPTIONS method.| -| GET | GET | GET method. | -| HEAD | HEAD | HEAD method. | -| POST | POST | POST method. | -| PUT | PUT | PUT method. | -| DELETE | DELETE | DELETE method. | -| TRACE | TRACE | TRACE method. | -| CONNECT | CONNECT | CONNECT method.| +| ------ | ------- | ------------------ | +| OPTIONS | "OPTIONS" | OPTIONS method.| +| GET | "GET" | GET method. | +| HEAD | "HEAD" | HEAD method. | +| POST | "POST" | POST method. | +| PUT | "PUT" | PUT method. | +| DELETE | "DELETE" | DELETE method. | +| TRACE | "TRACE" | TRACE method. | +| CONNECT | "CONNECT" | CONNECT method.| ## ResponseCode @@ -388,7 +390,7 @@ Enumerates the response codes for an HTTP request. | Name | Value | Description | | ----------------- | ---- | ------------------------------------------------------------ | -| OK | 200 | Request succeeded. The request has been processed successfully. This return code is generally used for GET and POST requests. | +| OK | 200 | The request is successful. The request has been processed successfully. This return code is generally used for GET and POST requests. | | CREATED | 201 | "Created." The request has been successfully sent and a new resource is created. | | ACCEPTED | 202 | "Accepted." The request has been accepted, but the processing has not been completed. | | NOT_AUTHORITATIVE | 203 | "Non-Authoritative Information." The request is successful. | @@ -433,17 +435,171 @@ Defines the response to an HTTP request. | Name | Type | Mandatory| Description | | -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | result | string \| Object \| ArrayBuffer6+ | Yes | Response content returned based on **Content-type** in the response header:
- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.
- application/octet-stream: ArrayBuffer
- Others: string| +| resultType9+ | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. | | responseCode | [ResponseCode](#responsecode) \| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**. For details, see [Error Codes](#error-codes).| | header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:
- Content-Type: header['Content-Type'];
- Status-Line: header['Status-Line'];
- Date: header.Date/header['Date'];
- Server: header.Server/header['Server'];| | cookies8+ | Array\ | Yes | Cookies returned by the server. | +## http.createHttpResponseCache9+ + +createHttpResponseCache(cacheSize?: number): HttpResponseCache + +Creates a default object to store responses to HTTP access requests. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| cacheSize | number | No| Cache size. The maximum value is 10\*1024\*1024 (10 MB). By default, the maximum value is used.| + +**Return value** + +| Type | Description | +| ---------- | ----------------------------------------------------------- | +| [HttpResponseCache](#httpresponsecache9) | Object that stores the response to the HTTP request.| + +**Example** + +```js +import http from '@ohos.net.http'; +let httpResponseCache = http.createHttpResponseCache(); +``` + +## HttpResponseCache9+ + +Defines an object that stores the response to an HTTP request. + +### flush9+ + +flush(callback: AsyncCallback\): void + +Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +httpResponseCache.flush(err => { + if (err) { + console.log('flush fail'); + return; + } + console.log('flush success'); +}); +``` + +### flush9+ + +flush(): Promise\ + +Flushes data in the cache to the file system so that the cached data can be accessed in the next HTTP request. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\> | Promise used to return the result.| + +**Example** + +```js +httpResponseCache.flush().then(() => { + console.log('flush success'); +}).catch(err => { + console.log('flush fail'); +}); +``` + +### delete9+ + +delete(callback: AsyncCallback\): void + +Disables the cache and deletes the data in it. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +httpResponseCache.delete(err => { + if (err) { + console.log('delete fail'); + return; + } + console.log('delete success'); +}); +``` +### delete9+ + +delete(): Promise\ + +Disables the cache and deletes the data in it. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| --------------------------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Example** + +```js +httpResponseCache.delete().then(() => { + console.log('delete success'); +}).catch(err => { + console.log('delete fail'); +}); +``` + ## Error Codes | Error Code| Description | | ------ | ------------------------------------------------------------ | -| -1 | Incorrect parameters. | -| 3 | Incorrect URL format. | -| 4 | Built-in request function, protocol, or option not found during build. | -| 5 | Unable to resolve the proxy. | -| 6 | Unable to resolve the host. | -| 7 | Unable to connect to the proxy or host. | +| -1 | Incorrect parameter. Check whether the number and type of parameters are correct. | +| 3 | Incorrect URL format. Check whether the format and syntax of the URL are correct. | +| 4 | Built-in request function, protocol, or option not found during build. If a function or option is not enabled or explicitly disabled, you need to rebuild a libcurl in order to access its functions. | +| 5 | Unable to resolve the proxy because of a failure to resolve the specified proxy server. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. | +| 6 | Unable to resolve the host because of a failure to resolve the specified remote host. You are advised perform the following: 1. Check whether the URL is correct. 2. Check whether the network connection is normal and whether the network can communicate with external networks. 3. Check whether the network access permission is available. | +| 7 | Unable to connect to the proxy or host. You are advised perform the following: 1. Check whether the port number is correct. 2. Check whether the HTTP proxy is enabled on the local host. | + +## HttpDataType9+ + +Enumerates HTTP data types. + +**System capability**: SystemCapability.Communication.NetStack + +| Name| Value| Description | +| ------------------ | -- | ----------- | +| STRING | 0 | String type.| +| OBJECT | 1 | Object type. | +| ARRAY_BUFFER | 2 | Binary array type.| + +## HttpProtocol9+ + +Enumerates HTTP protocol versions. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Description | +| -------- | ----------- | +| HTTP1_1 | HTTP1.1 | +| HTTP2 | HTTP2 | diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index e990ecf8126054b0de5ad52308c4f83843782d97..cda33f5434360fe5ca3f21f9f2c0a04ad5b50474 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -1,18 +1,18 @@ -# Internationalization – I18N +# @ohos.i18n (Internationalization) - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. -The [Intl](js-apis-intl.md) module provides basic I18N capabilities through the standard I18N APIs defined in ECMA 402. It works with the I18N module to provide a complete suite of I18N capabilities. +The **i18n** module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. +The [intl](js-apis-intl.md) module provides basic i18n capabilities through the standard i18n APIs defined in ECMA 402. It works with the i18n module to provide a complete suite of i18n capabilities. > **NOTE** > - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. > -> - This module provides system-related or enhanced I18N capabilities, such as locale management, phone number formatting, and calendar, through supplementary I18N APIs that are not defined in ECMA 402. For details about the basic I18N capabilities, see [Intl](js-apis-intl.md). +> - This module provides system-related or enhanced i18n capabilities, such as locale management, phone number formatting, and calendar, through supplementary i18n APIs that are not defined in ECMA 402. For details about the basic i18n capabilities, see [intl](js-apis-intl.md). ## Modules to Import ```js -import i18n from '@ohos.i18n'; +import I18n from '@ohos.i18n'; ``` @@ -42,16 +42,16 @@ Obtains the localized script for the specified country. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayCountry = i18n.System.getDisplayCountry("zh-CN", "en-GB"); + let displayCountry = I18n.System.getDisplayCountry("zh-CN", "en-GB"); // displayCountry = "China" } catch(error) { console.error(`call System.getDisplayCountry failed, error code: ${error.code}, message: ${error.message}.`) } @@ -81,16 +81,16 @@ Obtains the localized script for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var displayLanguage = i18n.System.getDisplayLanguage("zh", "en-GB"); + let displayLanguage = I18n.System.getDisplayLanguage("zh", "en-GB"); // displayLanguage = Chinese } catch(error) { console.error(`call System.getDisplayLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -112,16 +112,16 @@ Obtains the list of system languages. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguages = i18n.System.getSystemLanguages(); + let systemLanguages = I18n.System.getSystemLanguages(); // [ "en-Latn-US", "zh-Hans" ] } catch(error) { console.error(`call System.getSystemLanguages failed, error code: ${error.code}, message: ${error.message}.`) } @@ -137,9 +137,9 @@ Obtains the list of countries and regions supported for the specified language. **Parameters** -| Name | Type | Description | -| -------- | ------ | ----- | -| language | string | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Return value** @@ -149,16 +149,16 @@ Obtains the list of countries and regions supported for the specified language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemCountries = i18n.System.getSystemCountries('zh'); + let systemCountries = I18n.System.getSystemCountries('zh'); // systemCountries = [ "ZW", "YT", "YE", ..., "ER", "CN", "DE" ], 240 countries or regions in total } catch(error) { console.error(`call System.getSystemCountries failed, error code: ${error.code}, message: ${error.message}.`) } @@ -187,16 +187,16 @@ Checks whether the system language matches the specified region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var res = i18n.System.isSuggested('zh', 'CN'); + let res = I18n.System.isSuggested('zh', 'CN'); // res = true } catch(error) { console.error(`call System.isSuggested failed, error code: ${error.code}, message: ${error.message}.`) } @@ -218,16 +218,16 @@ Obtains the system language. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLanguage = i18n.System.getSystemLanguage(); + let systemLanguage = I18n.System.getSystemLanguage(); // systemLanguage indicates the current system language. } catch(error) { console.error(`call System.getSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -239,7 +239,7 @@ static setSystemLanguage(language: string): void Sets the system language. Currently, this API does not support real-time updating of the system language. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -247,22 +247,22 @@ This is a system API. **Parameters** -| Name | Type | Description | -| -------- | ------ | ----- | -| language | string | Language ID.| +| Name | Type | Mandatory | Description | +| -------- | ------ | ---- | ----- | +| language | string | Yes | Language ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLanguage('zh'); + I18n.System.setSystemLanguage('zh'); // Set the current system language to zh. } catch(error) { console.error(`call System.setSystemLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -284,16 +284,16 @@ Obtains the system region. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemRegion = i18n.System.getSystemRegion(); + let systemRegion = I18n.System.getSystemRegion(); // Obtain the current system region. } catch(error) { console.error(`call System.getSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) } @@ -305,7 +305,7 @@ static setSystemRegion(region: string): void Sets the system region. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -313,22 +313,22 @@ This is a system API. **Parameters** -| Name | Type | Description | -| ------ | ------ | ----- | -| region | string | Region ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ----- | +| region | string | Yes | Region ID.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemRegion('CN'); + I18n.System.setSystemRegion('CN'); // Set the current system region to CN. } catch(error) { console.error(`call System.setSystemRegion failed, error code: ${error.code}, message: ${error.message}.`) } @@ -350,16 +350,16 @@ Obtains the system locale. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var systemLocale = i18n.System.getSystemLocale(); + let systemLocale = I18n.System.getSystemLocale(); // Obtain the current system locale. } catch(error) { console.error(`call System.getSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) } @@ -371,7 +371,7 @@ static setSystemLocale(locale: string): void Sets the system locale. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -379,22 +379,22 @@ This is a system API. **Parameters** -| Name | Type | Description | -| ------ | ------ | --------------- | -| locale | string | System locale ID, for example, **zh-CN**.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | --------------- | +| locale | string | Yes | System locale ID, for example, **zh-CN**.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - i18n.System.setSystemLocale('zh-CN'); + I18n.System.setSystemLocale('zh-CN'); // Set the current system locale to zh-CN. } catch(error) { console.error(`call System.setSystemLocale failed, error code: ${error.code}, message: ${error.message}.`) } @@ -416,16 +416,16 @@ Checks whether the 24-hour clock is used. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var is24HourClock = i18n.System.is24HourClock(); + let is24HourClock = I18n.System.is24HourClock(); // Check whether the 24-hour clock is enabled. } catch(error) { console.error(`call System.is24HourClock failed, error code: ${error.code}, message: ${error.message}.`) } @@ -437,7 +437,7 @@ static set24HourClock(option: boolean): void Sets the 24-hour clock. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -451,17 +451,17 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Set the system time to the 24-hour clock. try { - i18n.System.set24HourClock(true); + I18n.System.set24HourClock(true); } catch(error) { console.error(`call System.set24HourClock failed, error code: ${error.code}, message: ${error.message}.`) } @@ -473,7 +473,7 @@ static addPreferredLanguage(language: string, index?: number): void Adds a preferred language to the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -488,19 +488,19 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; + let language = 'zh-CN'; + let index = 0; try { - i18n.System.addPreferredLanguage(language, index); + I18n.System.addPreferredLanguage(language, index); // Add zh-CN to the first place in the preferred language list. } catch(error) { console.error(`call System.addPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -512,7 +512,7 @@ static removePreferredLanguage(index: number): void Deletes a preferred language from the specified position on the preferred language list. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -526,18 +526,18 @@ This is a system API. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; + let index = 0; try { - i18n.System.removePreferredLanguage(index); + I18n.System.removePreferredLanguage(index); } catch(error) { console.error(`call System.removePreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -547,7 +547,7 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. **System capability**: SystemCapability.Global.I18n @@ -555,20 +555,20 @@ Obtains the list of preferred languages. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var preferredLanguageList = i18n.System.getPreferredLanguageList(); + let preferredLanguageList = I18n.System.getPreferredLanguageList(); // Obtain the current preferred language list. } catch(error) { console.error(`call System.getPreferredLanguageList failed, error code: ${error.code}, message: ${error.message}.`) } @@ -590,16 +590,16 @@ Obtains the first language in the preferred language list. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var firstPreferredLanguage = i18n.System.getFirstPreferredLanguage(); + let firstPreferredLanguage = I18n.System.getFirstPreferredLanguage(); // Obtain the first language in the preferred language list. } catch(error) { console.error(`call System.getFirstPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -621,16 +621,16 @@ Obtains the preferred language of an application. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```js try { - var appPreferredLanguage = i18n.System.getAppPreferredLanguage(); + let appPreferredLanguage = I18n.System.getAppPreferredLanguage(); // Obtain the preferred language of an application. } catch(error) { console.error(`call System.getAppPreferredLanguage failed, error code: ${error.code}, message: ${error.message}.`) } @@ -640,9 +640,9 @@ For details about the error codes, see [I18N Error Codes](../errorcodes/errorcod static setUsingLocalDigit(flag: boolean): void -Sets whether to turn on the local digit switch. +Sets whether to enable the local digit switch. -This is a system API. +**System API**: This is a system API. **Permission required**: ohos.permission.UPDATE_CONFIGURATION @@ -652,20 +652,20 @@ This is a system API. | Name | Type | Mandatory | Description | | ---- | ------- | ---- | ------------------------------- | -| flag | boolean | Yes | Whether to turn on the local digit switch. The value **true** means to turn on the local digit switch, and the value **false** indicates the opposite.| +| flag | boolean | Yes | Whether to enable the local digit switch. The value **true** means to enable the local digit switch, and the value **false** indicates the opposite.| **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - i18n.System.setUsingLocalDigit(true); + I18n.System.setUsingLocalDigit(true); // Enable the local digit switch. } catch(error) { console.error(`call System.setUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) } @@ -687,23 +687,23 @@ Checks whether the local digit switch is turned on. **Error codes** -For details about the error codes, see [I18N Error Codes](../errorcodes/errorcode-i18n.md). +For details about the error codes, see [i18n Error Codes](../errorcodes/errorcode-i18n.md). -| ID| Error Message| -| -------- | ---------------------------------------- | -| 890001 | Unspported para value. | +| ID | Error Message | +| ------ | ---------------------- | +| 890001 | Unspported para value. | **Example** ```ts try { - var status = i18n.System.getUsingLocalDigit(); + let status = I18n.System.getUsingLocalDigit(); // Check whether the local digit switch is enabled. } catch(error) { console.error(`call System.getUsingLocalDigit failed, error code: ${error.code}, message: ${error.message}.`) } ``` -## i18n.isRTL7+ +## I18n.isRTL7+ isRTL(locale: string): boolean @@ -713,9 +713,9 @@ Checks whether the localized script for the specified language is displayed from **Parameters** -| Name | Type | Description | -| ------ | ------ | ------- | -| locale | string | Locale ID.| +| Name | Type | Mandatory | Description | +| ------ | ------ | ---- | ------- | +| locale | string | Yes | Locale ID.| **Return value** @@ -730,7 +730,7 @@ Checks whether the localized script for the specified language is displayed from ``` -## i18n.getCalendar8+ +## I18n.getCalendar8+ getCalendar(locale: string, type? : string): Calendar @@ -753,7 +753,7 @@ Obtains a **Calendar** object. **Example** ```js - i18n.getCalendar("zh-Hans", "gregory"); + I18n.getCalendar("zh-Hans", "chinese"); // Obtain the Calendar object for the Chinese lunar calendar. ``` @@ -776,8 +776,8 @@ Sets the date for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - var date = new Date(2021, 10, 7, 8, 0, 0, 0); + let calendar = I18n.getCalendar("en-US", "gregory"); + let date = new Date(2021, 10, 7, 8, 0, 0, 0); calendar.setTime(date); ``` @@ -798,7 +798,7 @@ Sets the date and time for this **Calendar** object. The value is represented by **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); + let calendar = I18n.getCalendar("en-US", "gregory"); calendar.setTime(10540800000); ``` @@ -824,7 +824,7 @@ Sets the year, month, day, hour, minute, and second for this **Calendar** object **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 ``` @@ -845,7 +845,7 @@ Sets the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); ``` @@ -866,9 +866,9 @@ Obtains the time zone of this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setTimeZone("Asia/Shanghai"); - calendar.getTimeZone(); // Asia/Shanghai" + let timezone = calendar.getTimeZone(); // timezone = "Asia/Shanghai" ``` @@ -888,8 +888,8 @@ Obtains the start day of a week for this **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("en-US", "gregory"); - calendar.getFirstDayOfWeek(); + let calendar = I18n.getCalendar("en-US", "gregory"); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 1 ``` @@ -905,12 +905,13 @@ Sets the start day of a week for this **Calendar** object. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | --------------------- | -| value | number | No | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| +| value | number | Yes | Start day of a week. The value **1** indicates Sunday, and the value **7** indicates Saturday.| **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.setFirstDayOfWeek(0); + let calendar = I18n.getCalendar("zh-Hans"); + calendar.setFirstDayOfWeek(3); + let firstDayOfWeek = calendar.getFirstDayOfWeek(); // firstDayOfWeek = 3 ``` @@ -930,8 +931,8 @@ Obtains the minimum number of days in the first week of a year. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); - calendar.getMinimalDaysInFirstWeek(); + let calendar = I18n.getCalendar("zh-Hans"); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 1 ``` @@ -947,12 +948,13 @@ Sets the minimum number of days in the first week of a year. | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ------------ | -| value | number | No | Minimum number of days in the first week of a year.| +| value | number | Yes | Minimum number of days in the first week of a year.| **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.setMinimalDaysInFirstWeek(3); + let minimalDaysInFirstWeek = calendar.getMinimalDaysInFirstWeek(); // minimalDaysInFirstWeek = 3 ``` @@ -978,9 +980,9 @@ Obtains the value of the specified field in the **Calendar** object. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 10, 1, 8, 0, 0); // set time to 2021.10.1 08:00:00 - calendar.get("hour_of_day"); // 8 + let hourOfDay = calendar.get("hour_of_day"); // hourOfDay = 8 ``` @@ -1006,8 +1008,8 @@ Obtains the **Calendar** object name displayed for the specified locale. **Example** ```js - var calendar = i18n.getCalendar("en-US", "buddhist"); - calendar.getDisplayName("zh"); // Obtain the name of the Buddhist calendar in zh. + let calendar = I18n.getCalendar("en-US", "buddhist"); + let calendarName = calendar.getDisplayName("zh"); // calendarName = "Buddhist Calendar" ``` @@ -1033,10 +1035,10 @@ Checks whether the specified date in this **Calendar** object is a weekend. **Example** ```js - var calendar = i18n.getCalendar("zh-Hans"); + let calendar = I18n.getCalendar("zh-Hans"); calendar.set(2021, 11, 11, 8, 0, 0); // set time to 2021.11.11 08:00:00 calendar.isWeekend(); // false - var date = new Date(2011, 11, 6, 9, 0, 0); + let date = new Date(2011, 11, 6, 9, 0, 0); calendar.isWeekend(date); // true ``` @@ -1057,11 +1059,11 @@ Creates a **PhoneNumberFormat** object. | Name | Type | Mandatory | Description | | ------- | ---------------------------------------- | ---- | ---------------- | | country | string | Yes | Country or region to which the phone number to be formatted belongs.| -| options | [PhoneNumberFormatOptions](#phonenumberformatoptions9) | No | Options of the **PhoneNumberFormat** object. | +| options | [PhoneNumberFormatOptions](#phonenumberformatoptions8) | No | Options of the **PhoneNumberFormat** object. | **Example** ```js - var phoneNumberFormat= new i18n.PhoneNumberFormat("CN", {"type": "E164"}); + let phoneNumberFormat= new I18n.PhoneNumberFormat("CN", {"type": "E164"}); ``` @@ -1087,8 +1089,8 @@ Checks whether the format of the specified phone number is valid. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.isValidNumber("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let isValidNumber = phonenumberfmt.isValidNumber("15812312312"); // isValidNumber = true ``` @@ -1114,8 +1116,8 @@ Formats a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.format("15812312312"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let formattedPhoneNumber = phonenumberfmt.format("15812312312"); // formattedPhoneNumber = "158 1231 2312" ``` @@ -1142,18 +1144,18 @@ Obtains the home location of a phone number. **Example** ```js - var phonenumberfmt = new i18n.PhoneNumberFormat("CN"); - phonenumberfmt.getLocationName("15812312345", "zh-CN"); + let phonenumberfmt = new I18n.PhoneNumberFormat("CN"); + let locationName = phonenumberfmt.getLocationName("15812312345", "zh-CN"); // locationName = "Zhanjiang, Guangdong Province" ``` -## PhoneNumberFormatOptions9+ +## PhoneNumberFormatOptions8+ Defines the options for this PhoneNumberFormat object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | | type | string | Yes | Yes | Format type of a phone number. The available options are as follows: E164, INTERNATIONAL, NATIONAL, and RFC3966.| @@ -1164,7 +1166,7 @@ Defines the measurement unit information. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | unit | string | Yes | Yes | Name of the measurement unit, for example, **meter**, **inch**, or **cup**.| | measureSystem | string | Yes | Yes | Measurement system. The value can be **SI**, **US**, or **UK**.| @@ -1192,7 +1194,7 @@ Creates an **IndexUtil** object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); + let indexUtil= I18n.getInstance("zh-CN"); ``` @@ -1215,8 +1217,10 @@ Obtains the index list for this **locale** object. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); - var indexList = indexUtil.getIndexList(); + let indexUtil = I18n.getInstance("zh-CN"); + // indexList = [ "...", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", + // "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "..." ] + let indexList = indexUtil.getIndexList(); ``` @@ -1236,7 +1240,7 @@ Adds the index of the new **locale** object to the index list. **Example** ```js - var indexUtil = i18n.getInstance("zh-CN"); + let indexUtil = I18n.getInstance("zh-CN"); indexUtil.addLocale("en-US"); ``` @@ -1263,12 +1267,12 @@ Obtains the index of a text object. **Example** ```js - var indexUtil= i18n.getInstance("zh-CN"); - indexUtil.getIndex("hi"); // Return hi. + let indexUtil= I18n.getInstance("zh-CN"); + let index = indexUtil.getIndex("hi"); // index = "H" ``` -## i18n.getLineInstance8+ +## I18n.getLineInstance8+ getLineInstance(locale: string): BreakIterator @@ -1290,7 +1294,7 @@ Obtains a [BreakIterator](#breakiterator8) object for text segmentation. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); ``` @@ -1313,8 +1317,8 @@ Sets the text to be processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); - iterator.setLineBreakText("Apple is my favorite fruit."); + let iterator = I18n.getLineInstance("en"); + iterator.setLineBreakText("Apple is my favorite fruit ."); // Set a short sentence as the text to be processed by the BreakIterator object. ``` @@ -1334,9 +1338,9 @@ Obtains the text being processed by the [BreakIterator](#breakiterator8) object. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.getLineBreakText(); // Apple is my favorite fruit. + let breakText = iterator.getLineBreakText(); // breakText = "Apple is my favorite fruit." ``` @@ -1356,9 +1360,9 @@ Obtains the position of the [BreakIterator](#breakiterator8) object in the text **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.current(); // 0 + let currentPos = iterator.current(); // currentPos = 0 ``` @@ -1378,9 +1382,9 @@ Puts the [BreakIterator](#breakiterator8) object to the first text boundary, whi **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = i18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 + let firstPos = iterator.first(); // firstPos = 0 ``` @@ -1400,9 +1404,9 @@ Puts the [BreakIterator](#breakiterator8) object to the last text boundary, whic **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.last(); // 27 + let lastPos = iterator.last(); // lastPos = 27 ``` @@ -1428,11 +1432,11 @@ Moves the [BreakIterator](#breakiterator8) object backward by the specified numb **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(); // 6 - iterator.next(10); // -1 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(); // pos = 6 + pos = iterator.next(10); // pos = -1 ``` @@ -1452,11 +1456,11 @@ Moves the [BreakIterator](#breakiterator8) object to the previous text boundary. **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.first(); // 0 - iterator.next(3); // 12 - iterator.previous(); // 9 + let pos = iterator.first(); // pos = 0 + pos = iterator.next(3); // pos = 12 + pos = iterator.previous(); // pos = 9 ``` @@ -1482,11 +1486,11 @@ Moves the [BreakIterator](#breakiterator8) object to the text boundary after the **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.following(0); // 6 - iterator.following(100); // -1 - iterator.current(); // 27 + let pos = iterator.following(0); // pos = 6 + pos = iterator.following(100); // pos = -1 + pos = iterator.current(); // pos = 27 ``` @@ -1512,14 +1516,14 @@ Checks whether the position specified by the offset is a text boundary. If **tru **Example** ```js - var iterator = i18n.getLineInstance("en"); + let iterator = I18n.getLineInstance("en"); iterator.setLineBreakText("Apple is my favorite fruit."); - iterator.isBoundary(0); // true; - iterator.isBoundary(5); // false; + let isBoundary = iterator.isBoundary(0); // isBoundary = true; + isBoundary = iterator.isBoundary(5); // isBoundary = false; ``` -## i18n.getTimeZone7+ +## I18n.getTimeZone7+ getTimeZone(zoneID?: string): TimeZone @@ -1541,7 +1545,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone ID. **Example** ```js - var timezone = i18n.getTimeZone(); + let timezone = I18n.getTimeZone(); ``` @@ -1564,8 +1568,8 @@ Obtains the ID of the specified **TimeZone** object. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getID(); + let timezone = I18n.getTimeZone(); + let timezoneID = timezone.getID(); // timezoneID = "Asia/Shanghai" ``` @@ -1573,7 +1577,7 @@ Obtains the ID of the specified **TimeZone** object. getDisplayName(locale?: string, isDST?: boolean): string -Obtains the representation of a **TimeZone** object in the specified locale. +Obtains the localized representation of the time zone. **System capability**: SystemCapability.Global.I18n @@ -1592,8 +1596,8 @@ Obtains the representation of a **TimeZone** object in the specified locale. **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getDisplayName("zh-CN", false); + let timezone = I18n.getTimeZone(); + let timezoneName = timezone.getDisplayName("zh-CN", false); // timezoneName = "China Standard Time" ``` @@ -1613,8 +1617,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getRawOffset(); + let timezone = I18n.getTimeZone(); + let offset = timezone.getRawOffset(); // offset = 28800000 ``` @@ -1634,8 +1638,8 @@ Obtains the offset between the time zone represented by a **TimeZone** object an **Example** ```js - var timezone = i18n.getTimeZone(); - timezone.getOffset(1234567890); + let timezone = I18n.getTimeZone(); + let offset = timezone.getOffset(1234567890); // offset = 28800000 ``` @@ -1655,7 +1659,8 @@ Obtains the list of time zone IDs supported by the system. **Example** ```ts - var ids = i18n.TimeZone.getAvailableIDs(); + // ids = ["America/Adak", "America/Anchorage", "America/Bogota", "America/Denver", "America/Los_Angeles", "America/Montevideo", "America/Santiago", "America/Sao_Paulo", "Asia/Ashgabat", "Asia/Hovd", "Asia/Jerusalem", "Asia/Magadan", "Asia/Omsk", "Asia/Shanghai", "Asia/Tokyo", "Asia/Yerevan", "Atlantic/Cape_Verde", "Australia/Lord_Howe", "Europe/Dublin", "Europe/London", "Europe/Moscow", "Pacific/Auckland", "Pacific/Easter", "Pacific/Pago-Pago"], 24 time zones supported in total + let ids = I18n.TimeZone.getAvailableIDs(); ``` @@ -1675,7 +1680,8 @@ Obtains the list of time zone city IDs supported by the system. **Example** ```ts - var cityIDs = i18n.TimeZone.getAvailableZoneCityIDs(); + // cityIDs = ["Auckland", "Magadan", "Lord Howe Island", "Tokyo", "Shanghai", "Hovd", "Omsk", "Ashgabat", "Yerevan", "Moscow", "Tel Aviv", "Dublin", "London", "Praia", "Montevideo", "Brasília", "Santiago", "Bogotá", "Easter Island", "Salt Lake City", "Los Angeles", "Anchorage", "Adak", "Pago Pago"], 24 time zone cities supported in total + let cityIDs = I18n.TimeZone.getAvailableZoneCityIDs(); ``` @@ -1683,7 +1689,7 @@ Obtains the list of time zone city IDs supported by the system. static getCityDisplayName(cityID: string, locale: string): string -Obtains the localized display of a time zone city in the specified locale. +Obtains the localized representation of a time zone city in the specified locale. **System capability**: SystemCapability.Global.I18n @@ -1702,7 +1708,7 @@ Obtains the localized display of a time zone city in the specified locale. **Example** ```ts - var displayName = i18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); + let displayName = I18n.TimeZone.getCityDisplayName("Shanghai", "zh-CN"); // displayName = "Shanghai (China)" ``` @@ -1728,7 +1734,7 @@ Obtains the **TimeZone** object corresponding to the specified time zone city ID **Example** ```ts - var timezone = i18n.TimeZone.getTimezoneFromCity("Shanghai"); + let timezone = I18n.TimeZone.getTimezoneFromCity("Shanghai"); ``` @@ -1751,7 +1757,9 @@ Obtains a list of IDs supported by the **Transliterator** object. **Example** ```ts - i18n.Transliterator.getAvailableIDs(); + // ids = ["ASCII-Latin", "Accents-Any", "Amharic-Latin/BGN", ...], 671 IDs supported in total + // Each ID consists of two parts separated by a hyphen (-). The format is source-destination. + let ids = I18n.Transliterator.getAvailableIDs(); ``` @@ -1777,7 +1785,7 @@ Creates a **Transliterator** object. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); ``` @@ -1803,8 +1811,8 @@ Converts the input string from the source format to the target format. **Example** ```ts - var transliterator = i18n.Transliterator.getInstance("Any-Latn"); - transliterator.transform ("China"); + let transliterator = I18n.Transliterator.getInstance("Any-Latn"); + let res = transliterator.transform("China"); // res = "zhōng guó" ``` @@ -1833,7 +1841,7 @@ Checks whether the input character string is composed of digits. **Example** ```js - var isdigit = i18n.Unicode.isDigit("1"); // Return true. + let isdigit = I18n.Unicode.isDigit("1"); // isdigit = true ``` @@ -1859,7 +1867,7 @@ Checks whether the input character is a space. **Example** ```js - var isspacechar = i18n.Unicode.isSpaceChar("a"); // Return false. + let isspacechar = I18n.Unicode.isSpaceChar("a"); // isspacechar = false ``` @@ -1885,7 +1893,7 @@ Checks whether the input character is a white space. **Example** ```js - var iswhitespace = i18n.Unicode.isWhitespace("a"); // Return false. + let iswhitespace = I18n.Unicode.isWhitespace("a"); // iswhitespace = false ``` @@ -1911,7 +1919,7 @@ Checks whether the input character is of the right to left (RTL) language. **Example** ```js - var isrtl = i18n.Unicode.isRTL("a"); // Return false. + let isrtl = I18n.Unicode.isRTL("a"); // isrtl = false ``` @@ -1937,7 +1945,7 @@ Checks whether the input character is an ideographic character. **Example** ```js - var isideograph = i18n.Unicode.isIdeograph("a"); // Return false. + let isideograph = I18n.Unicode.isIdeograph("a"); // isideograph = false ``` @@ -1963,7 +1971,7 @@ Checks whether the input character is a letter. **Example** ```js - var isletter = i18n.Unicode.isLetter("a"); // Return true. + let isletter = I18n.Unicode.isLetter("a"); // isletter = true ``` @@ -1989,7 +1997,7 @@ Checks whether the input character is a lowercase letter. **Example** ```js - var islowercase = i18n.Unicode.isLowerCase("a"); // Return true. + let islowercase = I18n.Unicode.isLowerCase("a"); // islowercase = true ``` @@ -2015,7 +2023,7 @@ Checks whether the input character is an uppercase letter. **Example** ```js - var isuppercase = i18n.Unicode.isUpperCase("a"); // Return false. + let isuppercase = I18n.Unicode.isUpperCase("a"); // isuppercase = false ``` @@ -2041,7 +2049,7 @@ Obtains the type of the input character string. **Example** ```js - var type = i18n.Unicode.getType("a"); + let type = I18n.Unicode.getType("a"); // type = "U_LOWERCASE_LETTER" ``` @@ -2074,7 +2082,7 @@ Converts one measurement unit into another and formats the unit based on the spe **Example** ```js - i18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); + let res = I18n.I18NUtil.unitConvert({unit: "cup", measureSystem: "US"}, {unit: "liter", measureSystem: "SI"}, 1000, "en-US", "long"); // res = 236.588 liters ``` @@ -2100,11 +2108,11 @@ Obtains the sequence of the year, month, and day in the specified locale. **Example** ```js - i18n.I18NUtil.getDateOrder("zh-CN"); + let order = I18n.I18NUtil.getDateOrder("zh-CN"); // order = "y-L-d" ``` -## i18n.getDisplayCountry(deprecated) +## I18n.getDisplayCountry(deprecated) getDisplayCountry(country: string, locale: string, sentenceCase?: boolean): string @@ -2130,12 +2138,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayCountry("zh-CN", "en-GB", true); - i18n.getDisplayCountry("zh-CN", "en-GB"); + let countryName = I18n.getDisplayCountry("zh-CN", "en-GB", true); // countryName = true + countryName = I18n.getDisplayCountry("zh-CN", "en-GB"); // countryName = true ``` -## i18n.getDisplayLanguage(deprecated) +## I18n.getDisplayLanguage(deprecated) getDisplayLanguage(language: string, locale: string, sentenceCase?: boolean): string @@ -2161,12 +2169,12 @@ This API is deprecated since API version 9. You are advised to use [System.getDi **Example** ```js - i18n.getDisplayLanguage("zh", "en-GB", true); - i18n.getDisplayLanguage("zh", "en-GB"); + let languageName = I18n.getDisplayLanguage("zh", "en-GB", true); // languageName = "Chinese" + languageName = I18n.getDisplayLanguage("zh", "en-GB"); // languageName = "Chinese" ``` -## i18n.getSystemLanguage(deprecated) +## I18n.getSystemLanguage(deprecated) getSystemLanguage(): string @@ -2184,11 +2192,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLanguage(); + let systemLanguage = I18n.getSystemLanguage(); // Obtain the current system language. ``` -## i18n.getSystemRegion(deprecated) +## I18n.getSystemRegion(deprecated) getSystemRegion(): string @@ -2206,11 +2214,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemRegion(); + let region = I18n.getSystemRegion(); // Obtain the current system region. ``` -## i18n.getSystemLocale(deprecated) +## I18n.getSystemLocale(deprecated) getSystemLocale(): string @@ -2228,11 +2236,11 @@ This API is deprecated since API version 9. You are advised to use [System.getSy **Example** ```js - i18n.getSystemLocale(); + let locale = I18n.getSystemLocale (); // Obtain the system locale. ``` -## i18n.is24HourClock(deprecated) +## I18n.is24HourClock(deprecated) is24HourClock(): boolean @@ -2250,11 +2258,11 @@ This API is deprecated since API version 9. You are advised to use [System.is24H **Example** ```js - var is24HourClock = i18n.is24HourClock(); + let is24HourClock = I18n.is24HourClock(); ``` -## i18n.set24HourClock(deprecated) +## I18n.set24HourClock(deprecated) set24HourClock(option: boolean): boolean @@ -2281,11 +2289,11 @@ This API is deprecated since API version 9. You are advised to use [System.set24 **Example** ```js // Set the system time to the 24-hour clock. - var success = i18n.set24HourClock(true); + let success = I18n.set24HourClock(true); ``` -## i18n.addPreferredLanguage(deprecated) +## I18n.addPreferredLanguage(deprecated) addPreferredLanguage(language: string, index?: number): boolean @@ -2313,13 +2321,13 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Add zh-CN to the preferred language list. - var language = 'zh-CN'; - var index = 0; - var success = i18n.addPreferredLanguage(language, index); + let language = 'zh-CN'; + let index = 0; + let success = I18n.addPreferredLanguage(language, index); ``` -## i18n.removePreferredLanguage(deprecated) +## I18n.removePreferredLanguage(deprecated) removePreferredLanguage(index: number): boolean @@ -2346,16 +2354,16 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js // Delete the first preferred language from the preferred language list. - var index = 0; - var success = i18n.removePreferredLanguage(index); + let index = 0; + let success = I18n.removePreferredLanguage(index); ``` -## i18n.getPreferredLanguageList(deprecated) +## I18n.getPreferredLanguageList(deprecated) getPreferredLanguageList(): Array<string> -Obtains the list of preferred languages. +Obtains the preferred language list. This API is supported since API version 8 and is deprecated since API version 9. You are advised to use [System.getPreferredLanguageList](#getpreferredlanguagelist9) instead. @@ -2365,15 +2373,15 @@ This API is supported since API version 8 and is deprecated since API version 9. | Type | Description | | ------------------- | --------- | -| Array<string> | List of preferred languages.| +| Array<string> | Preferred language list.| **Example** ```js - var preferredLanguageList = i18n.getPreferredLanguageList(); + let preferredLanguageList = I18n.getPreferredLanguageList(); // Obtain the preferred language list. ``` -## i18n.getFirstPreferredLanguage(deprecated) +## I18n.getFirstPreferredLanguage(deprecated) getFirstPreferredLanguage(): string @@ -2391,7 +2399,7 @@ This API is supported since API version 8 and is deprecated since API version 9. **Example** ```js - var firstPreferredLanguage = i18n.getFirstPreferredLanguage(); + let firstPreferredLanguage = I18n.getFirstPreferredLanguage(); ``` diff --git a/en/application-dev/reference/apis/js-apis-image.md b/en/application-dev/reference/apis/js-apis-image.md index 1bf548153ad9837dc60e7a655852a33987b22871..16b144f78ec85198dfc570336fcf021a9bc86028 100644 --- a/en/application-dev/reference/apis/js-apis-image.md +++ b/en/application-dev/reference/apis/js-apis-image.md @@ -1,4 +1,4 @@ -# Image Processing +# @ohos.multimedia.image (Image Processing) The **Image** module provides APIs for image processing. You can use the APIs to create a **PixelMap** object with specified properties or read image pixel data (even in an area). @@ -22,7 +22,7 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ------------------------------------------------ | ---- | ---------------------------------------------------------------- | | colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties, including the alpha type, size, scale mode, pixel format, and editable.| @@ -57,7 +57,7 @@ Creates a **PixelMap** object with the default BGRA_8888 format and pixel proper **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | -------------------------- | | colors | ArrayBuffer | Yes | Color array in BGRA_8888 format. | | options | [InitializationOptions](#initializationoptions8) | Yes | Pixel properties. | @@ -907,7 +907,7 @@ Releases this **PixelMap** object. This API uses an asynchronous callback to ret **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------ | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1077,9 +1077,9 @@ const data = new ArrayBuffer(112); const imageSourceApi = image.createImageSource(data); ``` -## image.createIncrementalSource9+ +## image.CreateIncrementalSource9+ -createIncrementalSource(buf: ArrayBuffer): ImageSource +CreateIncrementalSource(buf: ArrayBuffer): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1101,12 +1101,12 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); // 96 is the size of the pixel map buffer to create. The value is calculated as follows: height x width x 4. -const imageSourceIncrementalSApi = image.createIncrementalSource(buf); +const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); ``` -## image.createIncrementalSource9+ +## image.CreateIncrementalSource9+ -createIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource +CreateIncrementalSource(buf: ArrayBuffer, options?: SourceOptions): ImageSource Creates an **ImageSource** instance in incremental mode based on the buffers. @@ -1129,7 +1129,7 @@ Creates an **ImageSource** instance in incremental mode based on the buffers. ```js const buf = new ArrayBuffer(96); // 96 is the size of the pixel map buffer to create. The value is calculated as follows: height x width x 4. -const imageSourceIncrementalSApi = image.createIncrementalSource(buf); +const imageSourceIncrementalSApi = image.CreateIncrementalSource(buf); ``` ## ImageSource @@ -1181,7 +1181,7 @@ Obtains information about this image. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ---------------------------------------- | | callback | AsyncCallback<[ImageInfo](#imageinfo)> | Yes | Callback used to return the image information.| @@ -1203,7 +1203,7 @@ Obtains information about an image with the specified index. This API uses a pro **Parameters** -| Name | Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ----- | ------ | ---- | ------------------------------------- | | index | number | No | Index of the image. If this parameter is not set, the default value **0** is used.| @@ -1234,7 +1234,7 @@ Obtains the value of a property with the specified index in this image. This API **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ---------------------------------------------------- | ---- | ------------------------------------ | | key | string | Yes | Name of the property. | | options | [GetImagePropertyOptions](#getimagepropertyoptions7) | No | Image properties, including the image index and default property value.| @@ -1372,12 +1372,12 @@ Updates incremental data. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ----------- | ---- | ------------ | | buf | ArrayBuffer | Yes | Incremental data. | | isFinished | boolean | Yes | Whether the update is complete.| -| value | number | No | Offset for data reading. | -| length | number | No | Array length. | +| value | number | Yes | Offset for data reading. | +| length | number | Yes | Array length. | **Return value** @@ -1405,12 +1405,12 @@ Updates incremental data. This API uses an asynchronous callback to return the r **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------------------- | ---- | -------------------- | | buf | ArrayBuffer | Yes | Incremental data. | | isFinished | boolean | Yes | Whether the update is complete. | -| value | number | No | Offset for data reading. | -| length | number | No | Array length. | +| value | number | Yes | Offset for data reading. | +| length | number | Yes | Array length. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1434,7 +1434,7 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------- | ------------------------------------ | ---- | ---------- | | options | [DecodingOptions](#decodingoptions7) | No | Image decoding parameters.| @@ -1486,7 +1486,7 @@ Creates a **PixelMap** object based on image decoding parameters. This API uses **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | -------------------------- | | options | [DecodingOptions](#decodingoptions7) | Yes | Image decoding parameters. | | callback | AsyncCallback<[PixelMap](#pixelmap7)> | Yes | Callback used to return the **PixelMap** object.| @@ -1518,7 +1518,7 @@ Releases this **ImageSource** instance. This API uses an asynchronous callback t **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------------- | | callback | AsyncCallback\ | Yes | Callback invoked for instance release. If the operation fails, an error message is returned.| @@ -1768,11 +1768,11 @@ Creates an **ImageReceiver** instance by specifying the image width, height, for **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | -| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). (Currently, the value of this parameter is agreed between the user and camera. In the future, there may be other application scenarios. The receiver is used only for transfer. Currently, only **ImageFormat:JPEG** is supported.) | +| format | number | Yes | Image format, which is a constant of [ImageFormat](#imageformat9). (Only ImageFormat:JPEG and 4 are supported.) | | capacity | number | Yes | Maximum number of images that can be accessed at the same time.| **Return value** @@ -1813,7 +1813,7 @@ Obtains a surface ID for the camera or other components. This API uses an asynch **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the surface ID.| @@ -1913,7 +1913,7 @@ Reads the next image from the **ImageReceiver** instance. This API uses an async **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | -------------------------- | | callback | AsyncCallback<[Image](#image9)> | Yes | Callback used to return the next image.| @@ -1963,7 +1963,7 @@ Listens for image arrival events. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------------------------------------ | | type | string | Yes | Type of event to listen for. The value is fixed at **imageArrival**, which is triggered when an image is received.| | callback | AsyncCallback\ | Yes | Callback invoked for the event. | @@ -1984,7 +1984,7 @@ Releases this **ImageReceiver** instance. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2028,7 +2028,7 @@ Creates an **ImageCreator** instance by specifying the image width, height, form **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------- | | width | number | Yes | Default image width. | | height | number | Yes | Default image height. | @@ -2071,7 +2071,7 @@ Obtains an image buffer from the idle queue and writes image data into it. This **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | ---------------------------------------| ---- | -------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the drawn image.| @@ -2080,9 +2080,9 @@ Obtains an image buffer from the idle queue and writes image data into it. This ```js creator.dequeueImage((err, img) => { if (err) { - console.info('dequeueImage succeeded.'); + console.info('dequeueImage failed.'); } - console.info('dequeueImage failed.'); + console.info('dequeueImage succeeded.'); }); ``` @@ -2120,7 +2120,7 @@ Places the drawn image in the dirty queue. This API uses an asynchronous callbac **Parameters** -| Name | Type | Mandatory| Description | +| 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.| @@ -2128,12 +2128,25 @@ Places the drawn image in the dirty queue. This API uses an asynchronous callbac **Example** ```js -creator.queueImage(img, (err) => { - if (err) { - console.info('dequeueImage failed: ' + err); - } - console.info('dequeueImage succeeded'); +creator.dequeueImage().then(img => { + // Draw the image. + img.getComponent(4).then(component => { + var bufferArr = new Uint8Array(component.byteBuffer); + for (var i = 0; i < bufferArr.length; i += 4) { + bufferArr[i] = 0; //B + bufferArr[i + 1] = 0; //G + bufferArr[i + 2] = 255; //R + bufferArr[i + 3] = 255; //A + } + }) + creator.queueImage(img, (err) => { + if (err) { + console.info('queueImage failed: ' + err); + } + console.info('queueImage succeeded'); + }) }) + ``` ### queueImage9+ @@ -2159,11 +2172,24 @@ Places the drawn image in the dirty queue. This API uses a promise to return the **Example** ```js -creator.queueImage(img).then(() => { - console.info('dequeueImage succeeded.'); -}).catch(error => { - console.info('dequeueImage failed: ' + error); +creator.dequeueImage().then(img => { + // Draw the image. + img.getComponent(4).then(component => { + var bufferArr = new Uint8Array(component.byteBuffer); + for (var i = 0; i < bufferArr.length; i += 4) { + bufferArr[i] = 0; //B + bufferArr[i + 1] = 0; //G + bufferArr[i + 2] = 255; //R + bufferArr[i + 3] = 255; //A + } + }) + creator.queueImage(img).then(() => { + console.info('queueImage succeeded.'); + }).catch(error => { + console.info('queueImage failed: ' + error); + }) }) + ``` ### on9+ @@ -2176,7 +2202,7 @@ Listens for image release events. This API uses an asynchronous callback to retu **Parameters** -| Name | Type | Mandatory| Description | +| 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.| @@ -2264,7 +2290,7 @@ Obtains the component buffer from the **Image** instance based on the color comp **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | --------------------------------------- | ---- | -------------------- | | componentType | [ComponentType](#componenttype9) | Yes | Color component type of the image. | | callback | AsyncCallback<[Component](#component9)> | Yes | Callback used to return the component buffer.| @@ -2291,7 +2317,7 @@ Obtains the component buffer from the **Image** instance based on the color comp **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ------------- | -------------------------------- | ---- | ---------------- | | componentType | [ComponentType](#componenttype9) | Yes | Color component type of the image.| @@ -2319,7 +2345,7 @@ The corresponding resources must be released before another image arrives. **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2398,7 +2424,7 @@ Enumerates the pixel formats of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | ---------------------- | ------ | ----------------- | | UNKNOWN | 0 | Unknown format. | | RGB_565 | 2 | RGB_565. | @@ -2416,7 +2442,7 @@ Enumerates the alpha types of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | -------- | ------ | ----------------------- | | UNKNOWN | 0 | Unknown alpha type. | | OPAQUE | 1 | There is no alpha or the image is opaque.| @@ -2429,7 +2455,7 @@ Enumerates the scale modes of images. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------- | ------ | -------------------------------------------------- | | CENTER_CROP | 1 | Scales the image so that it fills the requested bounds of the target and crops the extra.| | FIT_TARGET_SIZE | 0 | Reduces the image size to the dimensions of the target. | @@ -2519,7 +2545,7 @@ Describes the exchangeable image file format (EXIF) information of an image. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ----------------------- | ------------------------ | | BITS_PER_SAMPLE | "BitsPerSample" | Number of bits per pixel. | | ORIENTATION | "Orientation" | Image orientation. | @@ -2542,7 +2568,7 @@ Enumerates the image formats. **System capability**: SystemCapability.Multimedia.Image.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------ | ------ | -------------------- | | YCBCR_422_SP | 1000 | YCBCR422 semi-planar format.| | JPEG | 2000 | JPEG encoding format. | @@ -2553,7 +2579,7 @@ Enumerates the color component types of images. **System capability**: SystemCapability.Multimedia.Image.ImageReceiver -| Name | Default Value| Description | +| Name | Value | Description | | ----- | ------ | ----------- | | YUV_Y | 1 | Luminance component. | | YUV_U | 2 | Chrominance component. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md new file mode 100644 index 0000000000000000000000000000000000000000..54c8f0400be1f1e8b9f9b836098a94ace0c4f637 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-abilityResult.md @@ -0,0 +1,14 @@ +# AbilityResult + +The **AbilityResult** module defines the result code and data returned when an ability is terminated after being started. You can use [startAbilityForResult](js-apis-ability-context.md#abilitycontextstartabilityforresult) to obtain the **AbilityResult** object returned after the started ability is terminated. The startedability returns the **AbilityResult** object by calling [terminateSelfWithResult](js-apis-ability-context.md#abilitycontextterminateselfwithresult). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Readable | Writable | Type | Mandatory| Description | +| ----------- | -------- |-------- | -------------------- | ---- | ------------------------------------------------------------ | +| resultCode | Yes | Yes | number | Yes | Result code returned after the started ability is terminated. | +| want | Yes | Yes | [Want](./js-apis-app-ability-want.md) | No | Data returned after the started ability is terminated. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md new file mode 100644 index 0000000000000000000000000000000000000000..db0814fa146e09114eeb4fa635dfa78564ee595e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-connectOptions.md @@ -0,0 +1,11 @@ +# ConnectOptions + +**ConnectOptions** can be used as an input parameter to receive status changes during the connection to a background service. For example, it is used as an input parameter of [connectServiceExtensionAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextconnectserviceextensionability) to connect to a ServiceExtensionAbility. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory | Description | +| ------------ | -------- | ---- | ------------------------- | +| onConnect7+ | function | Yes | Callback invoked when a connection is set up. | +| onDisconnect7+ | function | Yes | Callback invoked when a connection is interrupted. | +| onFailed7+ | function | Yes | Callback invoked when a connection fails.| diff --git a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md similarity index 66% rename from en/application-dev/reference/apis/js-apis-dataAbilityHelper.md rename to en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md index 1d10f56aeb69e13d2f329bfc18f56127667ef930..d6b0c51051feb92f30495bdc552f84cae5e06018 100644 --- a/en/application-dev/reference/apis/js-apis-dataAbilityHelper.md +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityHelper.md @@ -1,5 +1,7 @@ # DataAbilityHelper +The **DataAbilityHelper** object is obtained through [acquireDataAbilityHelper](js-apis-ability-featureAbility.md#featureabilityacquiredataabilityhelper7). + > **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. @@ -8,17 +10,16 @@ ## Usage Import the following modules based on the actual situation before using the current module: -``` -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' -import ohos_data_rdb from '@ohos.data.rdb' +```ts +import ohos_data_ability from '@ohos.data.dataAbility'; +import ohos_data_rdb from '@ohos.data.rdb'; ``` ## DataAbilityHelper.openFile openFile(uri: string, mode: string, callback: AsyncCallback\): void -Opens a file with a specified URI. This API uses an asynchronous callback to return the result. +Opens a file with a specified URI. This API uses an asynchronous callback to return a file descriptor. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -27,22 +28,19 @@ Opens a file with a specified URI. This API uses an asynchronous callback to ret | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | ---------------------------------- | | uri | string | Yes | URI of the file to open. | -| mode | string | Yes | Mode for opening the file. The value can be **rwt**. | +| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. | | callback | AsyncCallback\ | Yes | Callback used to return the file descriptor.| **Example** -```javascript -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rwt"; -DAHelper.openFile( - "dataability:///com.example.DataAbility", - mode, - (err) => { - console.info("==========================>Called=======================>"); +var mode = "rw"; +DAHelper.openFile("dataability:///com.example.DataAbility", mode, (err, data) => { + console.info("openFile err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -50,7 +48,7 @@ DAHelper.openFile( openFile(uri: string, mode: string): Promise\ -Opens a file with a specified URI. This API uses a promise to return the result. +Opens a file with a specified URI. This API uses a promise to return a file descriptor. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -59,7 +57,7 @@ Opens a file with a specified URI. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------------ | | uri | string | Yes | URI of the file to open.| -| mode | string | Yes | Mode for opening the file. The value can be **rwt**. | +| mode | string | Yes | Mode for opening the file. The value **r** indicates read-only access, **w** indicates **write-only** access, and **rw** indicates read-write access. | **Return value** @@ -69,16 +67,14 @@ Opens a file with a specified URI. This API uses a promise to return the result. **Example** -```javascript -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var mode = "rwt"; -DAHelper.openFile( - "dataability:///com.example.DataAbility", - mode).then((data) => { - console.info("==========================>openFileCallback=======================>"); +var mode = "rw"; +DAHelper.openFile("dataability:///com.example.DataAbility", mode).then((data) => { + console.info("openFile data: " + JSON.stringify(data)); }); ``` @@ -86,7 +82,7 @@ DAHelper.openFile( on(type: 'dataChange', uri: string, callback: AsyncCallback\): void -Registers an observer to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Registers an observer to listen for changes in the data specified by a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -94,32 +90,32 @@ Registers an observer to observe data specified by a given URI. This API uses an | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Type of the event to observe. The value is **dataChange**. | +| type | string | Yes | The value **dataChange** means data changes. | | uri | string | Yes | URI of the data.| | callback | AsyncCallback\ | Yes | Callback invoked when the data is changed. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +```ts +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { - console.info("==========================>onChangeNotify=======================>"); + console.info("onChangeNotify call back"); }; -helper.on( +DAHelper.on( "dataChange", "dataability:///com.example.DataAbility", onChangeNotify -) +); ``` ## DataAbilityHelper.off off(type: 'dataChange', uri: string, callback?: AsyncCallback\): void -Deregisters the observer used to observe data specified by a given URI. This API uses an asynchronous callback to return the result. +Deregisters the observer that listens for changes in the data specified by a given URI. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -127,36 +123,36 @@ Deregisters the observer used to observe data specified by a given URI. This API | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Type of the event to observe. The value is **dataChange**. | +| type | string | Yes | The value **dataChange** means data changes. | | uri | string | Yes | URI of the data.| -| callback | AsyncCallback\ | No | Callback used to return the result. | +| callback | AsyncCallback\ | No | Callback of the listener to deregister. If the callback is set to **null**, all data change listeners are canceled. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +```ts +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); function onChangeNotify() { - console.info("==========================>onChangeNotify=======================>"); + console.info("onChangeNotify call back"); }; -helper.off( +DAHelper.off( "dataChange", "dataability:///com.example.DataAbility", -) -helper.off( + onChangeNotify +); +DAHelper.off( "dataChange", "dataability:///com.example.DataAbility", - onChangeNotify -) +); ``` ## DataAbilityHelper.getType getType(uri: string, callback: AsyncCallback\): void -Obtains the MIME type of the data specified by a given URI. This API uses an asynchronous callback to return the result. +Obtains the media resource type of the data specified by a given URI. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -165,19 +161,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses an asy | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------------------------- | | uri | string | Yes | URI of the data. | -| callback | AsyncCallback\ | Yes | Callback used to return the MIME type.| +| callback | AsyncCallback\ | Yes | Callback used to return the media resource type.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getType( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.getType("dataability:///com.example.DataAbility", (err, data) => { + console.info("getType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -185,7 +179,7 @@ DAHelper.getType( getType(uri: string): Promise\ -Obtains the MIME type of the data specified by a given URI. This API uses a promise to return the result. +Obtains the media resource type of the data specified by a given URI. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -199,19 +193,17 @@ Obtains the MIME type of the data specified by a given URI. This API uses a prom | Type | Description | | ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the MIME type.| +| Promise\ | Promise used to return the media resource type.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getType( - "dataability:///com.example.DataAbility" - ).then((data) => { - console.info("==========================>getTypeCallback=======================>"); +DAHelper.getType("dataability:///com.example.DataAbility").then((data) => { + console.info("getType data: " + JSON.stringify(data)); }); ``` @@ -219,7 +211,7 @@ DAHelper.getType( getFileTypes(uri: string, mimeTypeFilter: string, callback: AsyncCallback>): void -Obtains the supported MIME types of a specified file. This API uses an asynchronous callback to return the result. +Obtains the supported media resource types of a specified file. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -228,31 +220,26 @@ Obtains the supported MIME types of a specified file. This API uses an asynchron | Name | Type | Mandatory| Description | | -------------- | ------------------------------ | ---- | ---------------------------------- | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME type of the file. | -| callback | AsyncCallback\> | Yes | Callback used to return the supported MIME types.| +| mimeTypeFilter | string | Yes | Media resource type of the file to obtain. | +| callback | AsyncCallback\> | Yes | Callback used to return an array holding the media resource type.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getFileTypes( - "dataability:///com.example.DataAbility", - "image/*", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.getFileTypes( "dataability:///com.example.DataAbility", "image/*", (err, data) => { + console.info("getFileTypes err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` - - ## DataAbilityHelper.getFileTypes getFileTypes(uri: string, mimeTypeFilter: string): Promise\> -Obtains the supported MIME types of a specified file. This API uses a promise to return the result. +Obtains the supported media resource types of a specified file. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -261,26 +248,23 @@ Obtains the supported MIME types of a specified file. This API uses a promise to | Name | Type | Mandatory| Description | | -------------- | ------ | ---- | ---------------------------- | | uri | string | Yes | URI of the file. | -| mimeTypeFilter | string | Yes | MIME type of the file.| +| mimeTypeFilter | string | Yes | Media resource type of the file to obtain.| **Return value** | Type | Description | | ------------------------ | ------------------------ | -| Promise\> | Promise used to return the supported MIME types.| +| Promise\> | Promise used to return an array holding the media resource type.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.getFileTypes( - "dataability:///com.example.DataAbility", - "image/*" - ).then((data) => { - console.info("==========================>getFileTypesCallback=======================>"); +DAHelper.getFileTypes("dataability:///com.example.DataAbility", "image/*").then((data) => { + console.info("getFileTypes data: " + JSON.stringify(data)); }); ``` @@ -301,15 +285,13 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.normalizeUri( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.normalizeUri("dataability:///com.example.DataAbility", (err, data) => { + console.info("normalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -335,15 +317,13 @@ Converts the URI that refers to a Data ability into a normalized URI. This API u **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.normalizeUri( - "dataability:///com.example.DataAbility", - ).then((data) => { - console.info("==========================>normalizeUriCallback=======================>"); +DAHelper.normalizeUri("dataability:///com.example.DataAbility",).then((data) => { + console.info("normalizeUri data: " + JSON.stringify(data)); }); ``` @@ -359,25 +339,21 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------------------------------- | -| uri | string | Yes | URI object to normalize. | +| uri | string | Yes | URI object to denormalize. | | callback | AsyncCallback\ | Yes | Callback used to return the denormalized URI object.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.denormalizeUri( - "dataability:///com.example.DataAbility", - (err, data) => { - console.info("==========================>Called=======================>"); +DAHelper.denormalizeUri("dataability:///com.example.DataAbility", (err, data) => { + console.info("denormalizeUri err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` - - ## DataAbilityHelper.denormalizeUri denormalizeUri(uri: string): Promise\ @@ -400,15 +376,13 @@ Converts a normalized URI generated by **DataAbilityHelper.normalizeUri(uri: str **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.denormalizeUri( - "dataability:///com.example.DataAbility", - ).then((data) => { - console.info("==========================>denormalizeUriCallback=======================>"); +DAHelper.denormalizeUri("dataability:///com.example.DataAbility",).then((data) => { + console.info("denormalizeUri data: " + JSON.stringify(data)); }); ``` @@ -424,20 +398,18 @@ Notifies the registered observer of a change to the data specified by the URI. T | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| uri | string | Yes | URI of the data.| +| uri | string | Yes | URI of the data that changes.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -var helper = featureAbility.acquireDataAbilityHelper( +```ts +import featureAbility from '@ohos.ability.featureAbility'; +var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -helper.notifyChange( - "dataability:///com.example.DataAbility", - (err) => { - console.info("==========================>Called=======================>"); +DAHelper.notifyChange("dataability:///com.example.DataAbility", (err) => { + console.info("==========================>Called=======================>"); }); ``` @@ -453,7 +425,7 @@ Notifies the registered observer of a change to the data specified by the URI. T | Name| Type | Mandatory| Description | | ---- | ------ | ---- | ------------------------ | -| uri | string | Yes | URI of the data.| +| uri | string | Yes | URI of the data that changes.| **Return value** @@ -463,15 +435,13 @@ Notifies the registered observer of a change to the data specified by the URI. T **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -DAHelper.notifyChange( - "dataability:///com.example.DataAbility", - ).then(() => { - console.info("==========================>notifyChangeCallback=======================>"); +DAHelper.notifyChange("dataability:///com.example.DataAbility").then(() => { + console.info("================>notifyChangeCallback================>"); }); ``` @@ -493,8 +463,8 @@ Inserts a single data record into the database. This API uses an asynchronous ca **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -503,12 +473,9 @@ const valueBucket = { "age": 22, "salary": 200.5, "blobType": "u8", -} -DAHelper.insert( - "dataability:///com.example.DataAbility", - valueBucket, - (err, data) => { - console.info("==========================>Called=======================>"); +}; +DAHelper.insert("dataability:///com.example.DataAbility", valueBucket, (err, data) => { + console.info("insert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -535,8 +502,8 @@ Inserts a single data record into the database. This API uses a promise to retur **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -545,18 +512,15 @@ const valueBucket = { "age": 221, "salary": 20.5, "blobType": "u8", -} -DAHelper.insert( - "dataability:///com.example.DataAbility", - valueBucket - ).then((data) => { - console.info("==========================>insertCallback=======================>"); +}; +DAHelper.insert("dataability:///com.example.DataAbility", valueBucket).then((data) => { + console.info("insert data: " + JSON.stringify(data)); }); ``` ## DataAbilityHelper.batchInsert -batchInsert(uri: string, valuesBuckets: Array, callback: AsyncCallback\): void +batchInsert(uri: string, valuesBuckets: Array\, callback: AsyncCallback\): void Inserts multiple data records into the database. This API uses an asynchronous callback to return the result. @@ -567,24 +531,21 @@ Inserts multiple data records into the database. This API uses an asynchronous c | Name | Type | Mandatory| Description | | ------------ | ----------------------- | ---- | -------------------------------- | | uri | string | Yes | URI of the data to insert. | -| valuesBucket | Array | Yes | Data records to insert. | +| valuesBucket | Array\ | Yes | Data records to insert. | | callback | AsyncCallback\ | Yes | Callback used to return the number of inserted data records.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}) -DAHelper.batchInsert( - "dataability:///com.example.DataAbility", - cars, - (err, data) => { - console.info("==========================>Called=======================>"); + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); +DAHelper.batchInsert("dataability:///com.example.DataAbility", cars, (err, data) => { + console.info("batchInsert err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -601,7 +562,7 @@ Inserts multiple data records into the database. This API uses a promise to retu | Name | Type | Mandatory| Description | | ------------ | ----------------------- | ---- | ------------------------ | | uri | string | Yes | URI of the data to insert.| -| valuesBucket | Array | Yes | Data record to insert. | +| valuesBucket | Array | Yes | Data records to insert. | **Return value** @@ -611,19 +572,16 @@ Inserts multiple data records into the database. This API uses a promise to retu **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); var cars = new Array({"name": "roe11", "age": 21, "salary": 20.5, "blobType": "u8",}, {"name": "roe12", "age": 21, "salary": 20.5, "blobType": "u8",}, - {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}) -DAHelper.batchInsert( - "dataability:///com.example.DataAbility", - cars - ).then((data) => { - console.info("==========================>batchInsertCallback=======================>"); + {"name": "roe13", "age": 21, "salary": 20.5, "blobType": "u8",}); +DAHelper.batchInsert("dataability:///com.example.DataAbility", cars).then((data) => { + console.info("batchInsert data: " + JSON.stringify(data)); }); ``` @@ -640,23 +598,20 @@ Deletes one or more data records from the database. This API uses an asynchronou | Name | Type | Mandatory| Description | | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| valuesBucket | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| | callback | AsyncCallback\ | Yes | Callback used to return the number of deleted data records. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.delete( - "dataability:///com.example.DataAbility", - da, - (err, data) => { - console.info("==========================>Called=======================>"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.delete("dataability:///com.example.DataAbility", da, (err, data) => { + console.info("delete err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -673,7 +628,7 @@ Deletes one or more data records from the database. This API uses a promise to r | Name | Type | Mandatory| Description | | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to delete. | -| valuesBucket | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| predicates | dataAbility.DataAbilityPredicates | No | Filter criteria. You should define the processing logic when this parameter is **null**.| **Return value** @@ -683,18 +638,15 @@ Deletes one or more data records from the database. This API uses a promise to r **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.delete( - "dataability:///com.example.DataAbility", - da - ).then((data) => { - console.info("==========================>deleteCallback=======================>"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.delete("dataability:///com.example.DataAbility", da).then((data) => { + console.info("delete data: " + JSON.stringify(data)); }); ``` @@ -717,9 +669,9 @@ Updates data records in the database. This API uses an asynchronous callback to **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -728,14 +680,10 @@ const va = { "age": 21, "salary": 20.5, "blobType": "u8", -} -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.update( - "dataability:///com.example.DataAbility", - va, - da, - (err, data) => { - console.info("==========================>Called=======================>"); +}; +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.update("dataability:///com.example.DataAbility", va, da, (err, data) => { + console.info("update err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -753,7 +701,7 @@ Updates data records in the database. This API uses a promise to return the resu | ------------ | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to update. | | valuesBucket | rdb.ValuesBucket | Yes | New values. | -| predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| predicates | dataAbility.DataAbilityPredicates | No | Filter criteria. You should define the processing logic when this parameter is **null**.| **Return value** @@ -763,9 +711,9 @@ Updates data records in the database. This API uses a promise to return the resu **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); @@ -774,14 +722,10 @@ const va = { "age": 21, "salary": 20.5, "blobType": "u8", -} -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.update( - "dataability:///com.example.DataAbility", - va, - da - ).then((data) => { - console.info("==========================>updateCallback=======================>"); +}; +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.update("dataability:///com.example.DataAbility", va, da).then((data) => { + console.info("update data: " + JSON.stringify(data)); }); ``` @@ -798,26 +742,22 @@ Queries data in the database. This API uses an asynchronous callback to return t | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| columns | rdb.ValuesBucket | Yes | Columns to query. If this parameter is **null**, all columns will be queried. | +| columns | Array\ | Yes | Columns to query. If this parameter is **null**, all columns will be queried. | | predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| | callback | AsyncCallback\ | Yes | Callback used to return the data queried. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); var cars=new Array("value1", "value2", "value3", "value4"); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.query( - "dataability:///com.example.DataAbility", - cars, - da, - (err, data) => { - console.info("==========================>Called=======================>"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.query("dataability:///com.example.DataAbility", cars, da, (err, data) => { + console.info("query err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -836,8 +776,8 @@ Queries data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | | uri | string | Yes | URI of the data to query. | -| columns | rdb.ValuesBucket | Yes | Columns to query. If this parameter is **null**, all columns will be queried. | -| predicates | dataAbility.DataAbilityPredicates | Yes | Filter criteria. You should define the processing logic when this parameter is **null**.| +| columns | Array\ | No | Columns to query. If this parameter is **null**, all columns will be queried. | +| predicates | dataAbility.DataAbilityPredicates | No | Filter criteria. You should define the processing logic when this parameter is **null**.| **Return value** @@ -847,28 +787,24 @@ Queries data in the database. This API uses a promise to return the result. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import ohos_data_ability from '@ohos.data.dataAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import ohos_data_ability from '@ohos.data.dataAbility'; var DAHelper = featureAbility.acquireDataAbilityHelper( "dataability:///com.example.DataAbility" ); -var cars=new Array("value1", "value2", "value3", "value4"); -let da = new ohos_data_ability.DataAbilityPredicates() -DAHelper.query( - "dataability:///com.example.DataAbility", - cars, - da - ).then((data) => { - console.info("==========================>queryCallback=======================>"); +var cars = new Array("value1", "value2", "value3", "value4"); +let da = new ohos_data_ability.DataAbilityPredicates(); +DAHelper.query("dataability:///com.example.DataAbility", cars, da).then((data) => { + console.info("query data: " + JSON.stringify(data)); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap): Promise\ +call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void -Calls the extended API of the Data ability. This API uses a promise to return the result. +Calls an extended API of the DataAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -876,35 +812,35 @@ Calls the extended API of the Data ability. This API uses a promise to return th | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | -| arg | string | Yes |Parameter to pass. | +| arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | - -**Return value** - -| Type| Description| -|------ | ------- | -|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| +| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "method", "arg", {"key1":"value1"}).then((data) => { +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", + "method", "arg", {"key1":"value1"}, (err, data) => { + if (err) { + console.error('Operation failed. Cause: ' + err); + return; + } console.info('Operation succeeded: ' + data); -}).catch((error) => { - console.error('Operation failed. Cause: ' + error); }); ``` ## DataAbilityHelper.call -call(uri: string, method: string, arg: string, extras: PacMap, callback: AsyncCallback\): void +call(uri: string, method: string, arg: string, extras: PacMap): Promise\ -Calls the extended API of the Data ability. This API uses an asynchronous callback to return the result. +Calls an extended API of the DataAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -912,24 +848,30 @@ Calls the extended API of the Data ability. This API uses an asynchronous callba | Name | Type | Mandatory| Description | | ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | | method | string | Yes | Name of the API to call. | -| arg | string | Yes |Parameter to pass. | +| arg | string | Yes | Parameter to pass in. | | extras | [PacMap](#pacmap) | Yes | Key-value pair parameter. | -| callback | AsyncCallback\<[PacMap](#pacmap)> | Yes| Callback used to return the result. | + +**Return value** + +| Type| Description| +|------ | ------- | +|Promise\<[PacMap](#pacmap)> | Promise used to return the result.| **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", "method", "arg", {"key1":"value1"}, (err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + err); - return; - } +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", + "method", "arg", {"key1":"value1"}).then((data) => { console.info('Operation succeeded: ' + data); +}).catch((error) => { + console.error('Operation failed. Cause: ' + error); }); ``` @@ -937,26 +879,28 @@ dataAbilityHelper.call("dataability:///com.example.jsapidemo.UserDataAbility", " executeBatch(uri: string, operations: Array\, callback: AsyncCallback\>): void; -Operates data in the database. This API uses an asynchronous callback to return the result. +Operates data in the database in batches. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel **Parameters** -| Name | Type | Mandatory| Description | -| ---------- | --------------------------------- | ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | -| callback | AsyncCallback\> | Yes |Callback used to return the result of each operation in the **DataAbilityResult** array. | +| Name | Type | Mandatory| Description | +| ----------| ---------------------------------| ---- | ------------------------------------------------ | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. | +| callback | AsyncCallback\> | Yes | Callback used to return the result of each operation in the **DataAbilityResult** array. | **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op, (err, data) => { if (err) { console.error('Operation failed. Cause: ' + err); @@ -970,7 +914,7 @@ dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbi executeBatch(uri: string, operations: Array\): Promise\>; -Operates data in the database. This API uses a promise to return the result. +Operates data in the database in batches. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.FAModel @@ -978,24 +922,26 @@ Operates data in the database. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ---------- | -------------------------------| ---- | ------------------------------------------------ | -| uri | string | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx".| -| operations | Array\<[DataAbilityOperation](#dataabilityoperation)> | Yes | A list of data operations on the database. | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx".| +| operations | Array\<[DataAbilityOperation](js-apis-inner-ability-dataAbilityOperation.md)> | Yes | An array holding the data operations on the database. | **Return value** | Type| Description| |------ | ------- | -|Promise\> | Promise used to return the result of each operation in the **DataAbilityResult** array.| +|Promise\> | Promise used to return the result of each operation in the **DataAbilityResult** array.| **Example** -```js +```ts import featureAbility from '@ohos.ability.featureAbility'; // Select the operations to be performed on the database according to the DataAbilityOperation array. let op=new Array(); -let dataAbilityHelper = featureAbility.acquireDataAbilityHelper("dataability:///com.example.jsapidemo.UserDataAbility"); -dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility",op ).then((data) => { +let dataAbilityHelper = featureAbility.acquireDataAbilityHelper( + "dataability:///com.example.jsapidemo.UserDataAbility" +); +dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbility", op).then((data) => { console.info('Operation succeeded: ' + data); }).catch((error) => { console.error('Operation failed. Cause: ' + error); @@ -1012,27 +958,3 @@ dataAbilityHelper.executeBatch("dataability:///com.example.jsapidemo.UserDataAbi | Name| Type| Mandatory| Description| | ------ | ------ | ------ | ------ | | [key: string] | number \| string \| boolean \| Array\ \| null | Yes| Data stored in key-value pairs.| - -## DataAbilityOperation - -**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel - -| Name | Type | Readable | Writable | Mandatory| Description | -| -------- | -------- | -------- | -------- | --------| -------- | -| uri | string | Yes | No | Yes | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | -| type | featureAbility.DataAbilityOperationType | Yes | No | Yes | Operation type. | -| valuesBucket? | rdb.ValuesBucket | Yes | No | No | Data value to set. | -| valueBackReferences? | rdb.ValuesBucket | Yes | No | No | **ValuesBucket** object that contains a set of key-value pairs. | -| predicates? | dataAbility.DataAbilityPredicates | Yes | No | No | Predicates to set. If no predicate is set, all data records are displayed. | -| predicatesBackReferences? | Map\ | Yes | No | No | Back references of the predicates. | -| interrupted? | boolean | Yes | No | No | Whether batch operations can be interrupted. | -| expectedCount? | number | Yes | No | No | Expected number of rows to be updated or deleted. | - -## DataAbilityResult - -**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel - -| Name | Type | Readable | Writable | Mandatory | Description | -| -------- | -------- | -------- | -------- | -------- | -------- | -| uri? | string | Yes | No | No | URI of the Data ability. Example: "dataability:///com.example.xxx.xxxx". | -| count? | number | Yes | No | No | Number of rows affected by the operation. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md new file mode 100644 index 0000000000000000000000000000000000000000..0b96b8caa97bb28e7515bbc00ee1d7852ad2d21a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityOperation.md @@ -0,0 +1,21 @@ +# DataAbilityOperation + +The **DataAbilityOperation** module defines the operation on DataAbilities. It can be used as an input parameter of [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to specify the database operation information. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the FA model. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Template | Mandatory| Description | +| -------- | -------- | --------| -------- | +| uri | string | Yes | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| type | featureAbility.DataAbilityOperationType | Yes | Operation type. | +| valuesBucket? | rdb.ValuesBucket | No | Data value to set. | +| valueBackReferences? | rdb.ValuesBucket | No | **ValuesBucket** object that contains a set of key-value pairs. | +| predicates? | dataAbility.DataAbilityPredicates | No | Predicates to set. If no predicate is set, all data records are displayed. | +| predicatesBackReferences? | Map\ | No | Back references of the predicates. | +| interrupted? | boolean | No | Whether batch operations can be interrupted. | +| expectedCount? | number | No | Expected number of rows to be updated or deleted. | diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md new file mode 100644 index 0000000000000000000000000000000000000000..49b14bebedfaa76b495e8a127e3f4bd243c649b7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-dataAbilityResult.md @@ -0,0 +1,77 @@ +# DataAbilityResult + +The **DataAbilityResult** module defines the operation result on DataAbilities. When you call [executeBatch](js-apis-inner-ability-dataAbilityHelper.md#dataabilityhelperexecutebatch) to operate the database, the operation result is returned through the **DataAbilityResult** object. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the FA model. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Mandatory | Description | +| -------- | -------- | -------- | -------- | +| uri? | string | No | URI of the DataAbility. Example: "dataability:///com.example.xxx.xxxx". | +| count? | number | No | Number of rows affected by the operation. | + +**Example** + +```ts +import featureAbility from '@ohos.ability.featureAbility' + +// Perform database operations in batches. +function executeBatchOperation() { + let dataAbilityUri = ("dataability:///com.example.myapplication.TestDataAbility"); + let DAHelper; + try { + DAHelper = featureAbility.acquireDataAbilityHelper(dataAbilityUri); + if (DAHelper == null) { + console.error('DAHelper is null'); + return; + } + } catch (err) { + console.error('acquireDataAbilityHelper fail, error:' + JSON.stringify(err)); + return; + } + + let valueBucket = { + "name": "DataAbilityHelperTest", + "age": 24, + "salary": 2024.20, + }; + let operations = [ + { + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, + }, + { + uri: dataAbilityUri, + type: featureAbility.DataAbilityOperationType.TYPE_INSERT, + valuesBucket: valueBucket, + predicates: null, + expectedCount: 1, + PredicatesBackReferences: {}, + interrupted: true, + } + ]; + + try { + DAHelper.executeBatch(dataAbilityUri, operations).then((data) => { + for (let i = 0; i < data.length; i++) { + let dataAbilityResult = data[i]; + console.log('dataAbilityResult.uri: ' + dataAbilityResult.uri); + console.log('dataAbilityResult.count: ' + dataAbilityResult.count); + } + }).catch(err => { + console.error('executeBatch error: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('executeBatch error: ' + JSON.stringify(err)); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md new file mode 100644 index 0000000000000000000000000000000000000000..71b8d529703d28e01072d8f18f92ebe30b82c556 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-startAbilityParameter.md @@ -0,0 +1,46 @@ +# StartAbilityParameter + +The **StartAbilityParameter** module defines the parameters for starting an ability. The parameters can be used as input parameters in [startAbility](js-apis-ability-featureAbility.md#featureabilitystartability) to start the specified ability. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module can be used only in the FA model. + +**System capability**: SystemCapability.Ability.AbilityRuntime.FAModel + +| Name | Type | Mandatory | Description | +| ------------------- | -------- | ---- | -------------------------------------- | +| want | [Want](js-apis-application-want.md)| Yes | Want information about the target ability. | +| abilityStartSetting | {[key: string]: any} | No | Special attribute of the target ability. This attribute can be passed in the call.| + +**Example** +```ts +import featureAbility from '@ohos.ability.featureAbility' + +let Want = { + bundleName: "com.example.abilityStartSettingApp2", + abilityName: "com.example.abilityStartSettingApp.EntryAbility", +} + +let abilityStartSetting ={ + [featureAbility.AbilityStartSetting.BOUNDS_KEY] : [100,200,300,400], + [featureAbility.AbilityStartSetting.WINDOW_MODE_KEY] : + featureAbility.AbilityWindowConfiguration.WINDOW_MODE_UNDEFINED, + [featureAbility.AbilityStartSetting.DISPLAY_ID_KEY] : 1, +} + +let startAbilityParameter = { + want : Want, + abilityStartSetting : abilityStartSetting +} + +try { + featureAbility.startAbility(startAbilityParameter, (err, data) => { + console.log('errCode : ' + JSON.stringify(err)); + console.log('data : ' + JSON.stringify(data)); + }); +} catch(error) { + console.log("startAbility error: " + JSON.stringify(error)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-ability-want.md b/en/application-dev/reference/apis/js-apis-inner-ability-want.md new file mode 100644 index 0000000000000000000000000000000000000000..afb331b3fc2cb610025dd741e94abe0392fe4a5b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-ability-want.md @@ -0,0 +1,71 @@ +# Want + +Want is a carrier for information transfer between objects (application components). Want can be used as a parameter of [startAbility](js-apis-inner-application-uiAbilityContext.md#uiabilitycontextstartability) to specify a startup target and information that needs to be carried during startup, for example, **bundleName** and **abilityName**, which respectively indicate the bundle name of the target ability and the ability name in the bundle. When ability A needs to start ability B and transfer some data to ability B, it can use Want a carrier to transfer the data. + +> **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. + +**System capability**: SystemCapability.Ability.AbilityBase + +| Name | Type | Mandatory| Description | +| ----------- | -------------------- | ---- | ------------------------------------------------------------ | +| deviceId | string | No | ID of the device running the ability. If this field is unspecified, the local device is used. | +| bundleName | string | No | Bundle name.| +| abilityName | string | No | Name of the ability. If both **bundleName** and **abilityName** are specified in a **Want** object, the **Want** object can match a specific ability. The value of **abilityName** must be unique in an application.| +| uri | string | No | URI. If **uri** is specified in a **Want** object, the **Want** object will match the specified URI information, including **scheme**, **schemeSpecificPart**, **authority**, and **path**.| +| type | string | No | MIME type, that is, the type of the file to open, for example, **text/xml** and **image/***. For details about the MIME type definition, see https://www.iana.org/assignments/media-types/media-types.xhtml?utm_source=ld246.com. | +| flags | number | No | How the **Want** object will be handled. By default, numbers are passed in. For details, see [flags](js-apis-ability-wantConstant.md#wantconstantflags). | +| action | string | No | Action to take, such as viewing and sharing application details. In implicit Want, you can define this field and use it together with **uri** or **parameters** to specify the operation to be performed on the data. For details, see [action](js-apis-app-ability-wantConstant.md#wantconstantaction). For details about the definition and matching rules of implicit Want, see [Matching Rules of Explicit Want and Implicit Want](../../application-models/explicit-implicit-want-mappings.md). | +| parameters | {[key: string]: any} | No | Want parameters in the form of custom key-value (KV) pairs. By default, the following keys are carried:
**ohos.aafwk.callerPid**: PID of the caller.
**ohos.aafwk.param.callerToken**: token of the caller.
**ohos.aafwk.param.callerUid**: UID in [bundleInfo](js-apis-bundle-BundleInfo.md#bundleinfo-1), that is, the application UID in the bundle information. | +| entities | Array\ | No | Additional category information (such as browser and video player) of the target ability. It is a supplement to **action** in implicit Want and is used to filter ability types. For details, see [entity](js-apis-app-ability-wantConstant.md#wantconstantentity). | +| moduleName9+ | string | No | Module to which the ability belongs.| + +**Example** + +- Basic usage (called in a UIAbility object, where context in the example is the context object of the UIAbility). + + ```ts + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", + "moduleName": "entry" // moduleName is optional. + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + ``` + +- Passing a file descriptor (FD) (called in the UIAbility object, where context in the example is the context object of the UIAbility): + + ```ts + import fileio from '@ohos.fileio'; + + // ... + let fd; + try { + fd = fileio.openSync("/data/storage/el2/base/haps/pic.png"); + } catch(e) { + console.log("openSync fail:" + JSON.stringify(e)); + } + let want = { + "deviceId": "", // An empty deviceId indicates the local device. + "bundleName": "com.example.myapplication", + "abilityName": "EntryAbility", + "moduleName": "entry", // moduleName is optional. + "parameters": { + "keyFd":{"type":"FD", "value":fd} + } + }; + this.context.startAbility(want, (error) => { + // Start an ability explicitly. The bundleName, abilityName, and moduleName parameters work together to uniquely identify an ability. + console.log("error.code = " + error.code) + }) + // ... + ``` + +- For more details and examples, see [Want](../../application-models/want-overview.md). + + diff --git a/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..39c846bb6e96a2e8db53b71c6685e3e1ce3a4579 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-app-appVersionInfo.md @@ -0,0 +1,15 @@ +# AppVersionInfo + +The **AppVersionInfo** module defines the application version information. You can use [getAppVersionInfo](js-apis-inner-app-context.md#contextgetappversioninfo7) to obtain the version information of the current application. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| ----------- | ------ | ---- | ---- | -------------- | +| appName | string | Yes | No | Application name. | +| versionCode | number | Yes | No | Application version code.| +| versionName | string | Yes | No | Application version name. | diff --git a/en/application-dev/reference/apis/js-apis-Context.md b/en/application-dev/reference/apis/js-apis-inner-app-context.md similarity index 75% rename from en/application-dev/reference/apis/js-apis-Context.md rename to en/application-dev/reference/apis/js-apis-inner-app-context.md index 116af9c40bdb3c13cc278a13bb7ae5b08330095f..ec729194807c24ea49b7b117cb308628c031a75a 100644 --- a/en/application-dev/reference/apis/js-apis-Context.md +++ b/en/application-dev/reference/apis/js-apis-inner-app-context.md @@ -4,17 +4,20 @@ The **Context** module provides context for abilities or applications. It allows > **NOTE** > -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> > The APIs of this module can be used only in the FA model. ## Usage -The **Context** object is created in a **featureAbility** and returned through its **getContext()** API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: +The **Context** object is created in a **featureAbility** and returned through its [getContext](js-apis-ability-featureAbility.md#featureabilitygetcontext) API. Therefore, you must import the **@ohos.ability.featureAbility** package before using the **Context** module. An example is as follows: -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getOrCreateLocalDir() +context.getOrCreateLocalDir().then((data) => { + console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); +}); ``` ## Context.getOrCreateLocalDir7+ @@ -35,12 +38,12 @@ If this API is called for the first time, a root directory will be created. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateLocalDir((err, data)=>{ - console.info("data=" + data); -}) + console.info("getOrCreateLocalDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -63,16 +66,14 @@ If this API is called for the first time, a root directory will be created. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateLocalDir().then((data) => { - console.info("data=" + data); + console.info("getOrCreateLocalDir data: " + JSON.stringify(data)); }); ``` - - ## Context.verifyPermission7+ verifyPermission(permission: string, options: PermissionOptions, callback: AsyncCallback\): void @@ -86,19 +87,22 @@ Verifies whether a specific PID and UID have the given permission. This API uses | Name | Type | Mandatory | Description | | ---------- | --------------------------------------- | ---- | -------------------- | | permission | string | Yes | Name of the permission to verify. | -| options | [PermissionOptions](#permissionoptions) | Yes | Permission options. | +| options | [PermissionOptions](#permissionoptions7) | Yes | Permission options. | | callback | AsyncCallback\ | Yes | Callback used to return the permission verification result. The value **0** means that the PID and UID have the given permission, and the value **-1** means the opposite.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import bundle from '@ohos.bundle' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import bundle from '@ohos.bundle.bundleManager'; var context = featureAbility.getContext(); -bundle.getBundleInfo('com.context.test', 1, (err,datainfo) =>{ - context.verifyPermission("com.example.permission", {uid:datainfo.uid}); +bundle.getBundleInfo('com.context.test', 1, (err, datainfo) =>{ + context.verifyPermission("com.example.permission", {uid:datainfo.appInfo.uid}, (err, data) =>{ + console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + }); }); ``` +For details about **getBundleInfo** in the sample code, see [bundleManager](js-apis-bundleManager.md). @@ -119,10 +123,12 @@ Verifies whether the current PID and UID have the given permission. This API use **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.verifyPermission("com.example.permission") +context.verifyPermission("com.example.permission", (err, data) =>{ + console.info("verifyPermission err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` ## Context.verifyPermission7+ @@ -148,13 +154,12 @@ Verifies whether a specific PID and UID have the given permission. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); var Permission = {pid:1}; context.verifyPermission('com.context.permission',Permission).then((data) => { - console.info("======================>verifyPermissionCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("verifyPermission data: " + JSON.stringify(data)); }); ``` @@ -178,8 +183,8 @@ Requests certain permissions from the system. This API uses an asynchronous call **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.requestPermissionsFromUser( ["com.example.permission1", @@ -187,11 +192,11 @@ context.requestPermissionsFromUser( "com.example.permission3", "com.example.permission4", "com.example.permission5"], - 1,(err, data)=>{ - console.info("====>requestdata====>" + JSON.stringify(data)); - console.info("====>requesterrcode====>" + JSON.stringify(err.code)); + 1, + (err, data) => { + console.info("requestPermissionsFromUser err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); } -) +); ``` @@ -218,8 +223,8 @@ Requests certain permissions from the system. This API uses a promise to return **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.requestPermissionsFromUser( ["com.example.permission1", @@ -228,8 +233,9 @@ context.requestPermissionsFromUser( "com.example.permission4", "com.example.permission5"], 1).then((data)=>{ - console.info("====>requestdata====>" + JSON.stringify(data)); - }); + console.info("requestPermissionsFromUser data: " + JSON.stringify(data)); + } +); ``` @@ -246,14 +252,16 @@ Obtains information about the current application. This API uses an asynchronous | Name | Type | Mandatory | Description | | -------- | ------------------------------- | ---- | ------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the application information.| +| callback | AsyncCallback\<[ApplicationInfo](js-apis-bundleManager-applicationInfo.md)> | Yes | Callback used to return the application information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getApplicationInfo() +context.getApplicationInfo((err, data) => { + console.info("getApplicationInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -270,16 +278,15 @@ Obtains information about the current application. This API uses a promise to re | Type | Description | | ------------------------- | --------- | -| Promise\ | Promise used to return the application information.| +| Promise\<[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)> | Promise used to return the application information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getApplicationInfo().then((data) => { - console.info("=====================>getApplicationInfoCallback===================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getApplicationInfo data: " + JSON.stringify(data)); }); ``` @@ -301,10 +308,12 @@ Obtains the bundle name of this ability. This API uses an asynchronous callback **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getBundleName() +context.getBundleName((err, data) => { + console.info("getBundleName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -325,12 +334,11 @@ Obtains the bundle name of this ability. This API uses a promise to return the r **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getBundleName().then((data) => { - console.info("=======================>getBundleNameCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getBundleName data: " + JSON.stringify(data)); }); ``` @@ -346,14 +354,16 @@ Obtains the display orientation of this ability. This API uses an asynchronous c | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation.| +| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Yes | Callback used to return the display orientation.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getDisplayOrientation() +context.getDisplayOrientation((err, data) => { + console.info("getDisplayOrientation err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` ## Context.getDisplayOrientation7+ @@ -368,16 +378,15 @@ Obtains the display orientation of this ability. This API uses a promise to retu | Type | Description | | ---------------------------------------- | --------- | -| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation.| +| Promise\<[bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation)> | Promise used to return the display orientation.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getDisplayOrientation().then((data) => { - console.info("=======================>getDisplayOrientationCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getDisplayOrientation data: " + JSON.stringify(data)); }); ``` @@ -397,10 +406,12 @@ Obtains the external cache directory of the application. This API uses an asynch **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getExternalCacheDir() +context.getExternalCacheDir((err, data) => { + console.info("getExternalCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` ## Context.getExternalCacheDir @@ -419,12 +430,11 @@ Obtains the external cache directory of the application. This API uses a promise **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getExternalCacheDir().then((data) => { - console.info("=======================>getExternalCacheDirCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getExternalCacheDir data: " + JSON.stringify(data)); }); ``` @@ -440,18 +450,18 @@ Sets the display orientation for this ability. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | ----------- | ---------------------------------------- | ---- | ------------ | -| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | Yes | Display orientation to set.| -| callback | AsyncCallback\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Yes | Callback used to return the display orientation. | +| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | Yes | Display orientation to set.| +| callback | AsyncCallback\ | Yes | Callback used to return the display orientation. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import bundle from '@ohos.bundle' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); -var orientation=bundle.DisplayOrientation.UNSPECIFIED +var orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation, (err) => { - console.log('---------- setDisplayOrientation fail, err: -----------', err); + console.info("setDisplayOrientation err: " + JSON.stringify(err)); }); ``` @@ -467,19 +477,18 @@ Sets the display orientation for this ability. This API uses a promise to return | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| orientation | [bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation) | -| Promise\<[bundle.DisplayOrientation](js-apis-Bundle.md#displayorientation)> | Promise used to return the display orientation. | +| orientation | [bundle.DisplayOrientation](js-apis-bundleManager.md#displayorientation) | +| Promise\ | Promise used to return the display orientation. | **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' -import bundle from '@ohos.bundle' +```ts +import featureAbility from '@ohos.ability.featureAbility'; +import bundle from '@ohos.bundle'; var context = featureAbility.getContext(); -var orientation=bundle.DisplayOrientation.UNSPECIFIED +var orientation = bundle.DisplayOrientation.UNSPECIFIED; context.setDisplayOrientation(orientation).then((data) => { - console.info("=======================>setDisplayOrientationCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("setDisplayOrientation data: " + JSON.stringify(data)); }); ``` @@ -500,12 +509,12 @@ Sets whether to show this feature at the top of the lock screen so that the feat **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var show=true +var show = true; context.setShowOnLockScreen(show, (err) => { - console.log('---------- setShowOnLockScreen fail, err: -----------', err); + console.info("setShowOnLockScreen err: " + JSON.stringify(err)); }); ``` @@ -531,13 +540,12 @@ Sets whether to show this feature at the top of the lock screen so that the feat **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var show=true +var show = true; context.setShowOnLockScreen(show).then((data) => { - console.info("=======================>setShowOnLockScreenCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("setShowOnLockScreen data: " + JSON.stringify(data)); }); ``` @@ -558,12 +566,12 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var wakeUp=true +var wakeUp = true; context.setWakeUpScreen(wakeUp, (err) => { - console.log('---------- setWakeUpScreen fail, err: -----------', err); + console.info("setWakeUpScreen err: " + JSON.stringify(err)); }); ``` @@ -589,13 +597,12 @@ Sets whether to wake up the screen when this feature is restored. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -var wakeUp=true +var wakeUp = true; context.setWakeUpScreen(wakeUp).then((data) => { - console.info("=======================>setWakeUpScreenCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("setWakeUpScreen data: " + JSON.stringify(data)); }); ``` @@ -614,14 +621,16 @@ Obtains information about the current process, including the PID and process nam | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | ---------- | -| callback | AsyncCallback\ | Yes | Callback used to return the process information.| +| callback | AsyncCallback\<[ProcessInfo](js-apis-inner-app-processInfo.md)> | Yes | Callback used to return the process information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getProcessInfo() +context.getProcessInfo((err, data) => { + console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -638,16 +647,15 @@ Obtains information about the current process, including the PID and process nam | Type | Description | | --------------------- | ------- | -| Promise\ | Promise used to return the process information.| +| Promise\<[ProcessInfo](js-apis-inner-app-processInfo.md)> | Promise used to return the process information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getProcessInfo().then((data) => { - console.info("=======================>getProcessInfoCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getProcessInfo data: " + JSON.stringify(data)); }); ``` @@ -667,14 +675,16 @@ This API is available only to Page abilities. | Name | Type | Mandatory | Description | | -------- | --------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the **ohos.bundle.ElementName** object.| +| callback | AsyncCallback\<[ElementName](js-apis-bundleManager-elementName.md)> | Yes | Callback used to return the **ohos.bundle.ElementName** object.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getElementName() +context.getElementName((err, data) => { + console.info("getElementName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -693,16 +703,15 @@ This API is available only to Page abilities. | Type | Description | | --------------------- | ------------------------------------ | -| Promise\ | Promise used to return the **ohos.bundle.ElementName** object.| +| Promise\<[ElementName](js-apis-bundleManager-elementName.md)> | Promise used to return the **ohos.bundle.ElementName** object.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getElementName().then((data) => { - console.info("=======================>getElementNameCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getElementName data: " + JSON.stringify(data)); }); ``` @@ -722,10 +731,12 @@ Obtains the name of the current process. This API uses an asynchronous callback **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getProcessName() +context.getProcessName((err, data) => { + console.info("getProcessName err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -746,12 +757,11 @@ Obtains the name of the current process. This API uses a promise to return the r **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getProcessName().then((data) => { - console.info("=======================>getProcessNameCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getProcessName data: " + JSON.stringify(data)); }); ``` @@ -761,7 +771,7 @@ context.getProcessName().then((data) => { getCallingBundle(callback: AsyncCallback\): void -Obtains the bundle name of the calling ability. This API uses an asynchronous callback to return the result. +Obtains the bundle name of the caller ability. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -773,10 +783,12 @@ Obtains the bundle name of the calling ability. This API uses an asynchronous ca **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.getCallingBundle() +context.getCallingBundle((err, data) => { + console.info("getCallingBundle err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); +}); ``` @@ -785,7 +797,7 @@ context.getCallingBundle() getCallingBundle(): Promise\ -Obtains the bundle name of the calling ability. This API uses a promise to return the result. +Obtains the bundle name of the caller ability. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -797,12 +809,11 @@ Obtains the bundle name of the calling ability. This API uses a promise to retur **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getCallingBundle().then((data) => { - console.info("======================>getCallingBundleCallback====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getCallingBundle data: " + JSON.stringify(data)); }); ``` @@ -822,15 +833,11 @@ Obtains the cache directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getCacheDir((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getCacheDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -850,12 +857,11 @@ Obtains the cache directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getCacheDir().then((data) => { - console.info("======================>getCacheDirPromsie====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getCacheDir data: " + JSON.stringify(data)); }); ``` @@ -875,15 +881,11 @@ Obtains the file directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getFilesDir((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getFilesDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -903,12 +905,11 @@ Obtains the file directory of the application in the internal storage. This API **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getFilesDir().then((data) => { - console.info("======================>getFilesDirPromsie====================>"); - console.info("====>data====>" + JSON.stringify(data)); + console.info("getFilesDir data: " + JSON.stringify(data)); }); ``` @@ -926,19 +927,15 @@ If the distributed file path does not exist, the system will create one and retu | Name | Type | Mandatory | Description | | -------- | ---------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path. If the distributed file path does not exist, the system will create one and return the created path.| +| callback | AsyncCallback\ | Yes | Callback used to return the distributed file path.
If the path does not exist, the system will create one and return the created path.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateDistributedDir((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getOrCreateDistributedDir err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -956,15 +953,15 @@ If the distributed file path does not exist, the system will create one and retu | Type | Description | | ---------------- | ----------------------------------- | -| Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a new path will be created.| +| Promise\ | Promise used to return the distributed file path. If this API is called for the first time, a path will be created.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getOrCreateDistributedDir().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getOrCreateDistributedDir data: " + JSON.stringify(data)); }); ``` @@ -984,15 +981,11 @@ Obtains the application type. This API uses an asynchronous callback to return t **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppType((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getAppType err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1012,11 +1005,11 @@ Obtains the application type. This API uses a promise to return the result. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppType().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getAppType data: " + JSON.stringify(data)); }); ``` @@ -1032,19 +1025,15 @@ Obtains the **ModuleInfo** object of the application. This API uses an asynchron | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| +| callback | AsyncCallback\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Yes | Callback used to return the **ModuleInfo** object.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getHapModuleInfo((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getHapModuleInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1060,15 +1049,15 @@ Obtains the **ModuleInfo** object of the application. This API uses a promise to | Type | Description | | ---------------------------------------- | ------------------ | -| Promise\<[HapModuleInfo](js-apis-bundle-HapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| +| Promise\<[HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md)> | Promise used to return the **ModuleInfo** object.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getHapModuleInfo().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getHapModuleInfo data: " + JSON.stringify(data)); }); ``` @@ -1084,19 +1073,15 @@ Obtains the version information of the application. This API uses an asynchronou | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback\<[AppVersionInfo](#appversioninfo)> | Yes | Callback used to return the version information.| +| callback | AsyncCallback\<[AppVersionInfo](js-apis-inner-app-appVersionInfo.md)> | Yes | Callback used to return the version information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppVersionInfo((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getAppVersionInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1112,15 +1097,15 @@ Obtains the version information of the application. This API uses a promise to r | Type | Description | | ---------------------------------------- | --------- | -| Promise\<[AppVersionInfo](#appversioninfo)> | Promise used to return the version information.| +| Promise\<[AppVersionInfo](js-apis-inner-app-appVersionInfo.md)> | Promise used to return the version information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAppVersionInfo().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getAppVersionInfo data: " + JSON.stringify(data)); }); ``` @@ -1136,19 +1121,15 @@ Obtains information about this ability. This API uses an asynchronous callback t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| callback | AsyncCallback\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Yes | Callback used to return the ability information.| +| callback | AsyncCallback\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Yes | Callback used to return the ability information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAbilityInfo((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("getAbilityInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1164,15 +1145,15 @@ Obtains information about this ability. This API uses a promise to return the re | Type | Description | | ---------------------------------------- | ------------------ | -| Promise\<[AbilityInfo](js-apis-bundle-AbilityInfo.md)> | Promise used to return the ability information.| +| Promise\<[AbilityInfo](js-apis-bundleManager-abilityInfo.md)> | Promise used to return the ability information.| **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.getAbilityInfo().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("getAbilityInfo data: " + JSON.stringify(data)); }); ``` @@ -1192,8 +1173,8 @@ Obtains the context of the application. **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext().getApplicationContext(); ``` @@ -1213,15 +1194,11 @@ Checks whether the configuration of this ability is being updated. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.isUpdatingConfigurations((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); + console.info("isUpdatingConfigurations err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); }); ``` @@ -1241,11 +1218,11 @@ Checks whether the configuration of this ability is being updated. This API uses **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.isUpdatingConfigurations().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("isUpdatingConfigurations data: " + JSON.stringify(data)); }); ``` @@ -1265,15 +1242,11 @@ Notifies the system of the time required to draw this page function. This API us **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); -context.printDrawnCompleted((err, data) => { - if (err) { - console.error('Operation failed. Cause: ' + JSON.stringify(err)); - return; - } - console.info('Operation successful. Data:' + JSON.stringify(data)); +context.printDrawnCompleted((err) => { + console.error('printDrawnCompleted err: ' + JSON.stringify(err)); }); ``` @@ -1293,11 +1266,11 @@ Notifies the system of the time required to draw this page function. This API us **Example** -```js -import featureAbility from '@ohos.ability.featureAbility' +```ts +import featureAbility from '@ohos.ability.featureAbility'; var context = featureAbility.getContext(); context.printDrawnCompleted().then((data) => { - console.info("====>data====>" + JSON.stringify(data)); + console.info("printDrawnCompleted data: " + JSON.stringify(data)); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..351d6ad145824d0eba37a3a1eadc846034763c97 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-app-processInfo.md @@ -0,0 +1,28 @@ +# ProcessInfo + +The **ProcessInfo** module defines process information. You can use [getProcessInfo](js-apis-inner-app-context.md#contextgetprocessinfo7) to obtain information about the processes running on the current ability. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs of this module can be used only in the FA model. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| pid | number | Yes| No| Process ID.| +| processName | string | Yes| No| Process name.| + +**Example** +```ts +import featureAbility from '@ohos.ability.featureAbility'; + +var context = featureAbility.getContext(); +context.getProcessInfo((err, data) => { + console.info("getProcessInfo err: " + JSON.stringify(err) + "data: " + JSON.stringify(data)); + let pid = data.pid; + let processName = data.processName; +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md similarity index 83% rename from en/application-dev/reference/apis/js-apis-application-abilityDelegator.md rename to en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md index 1a6035f15c6d68dd374d21e1953163b57d1e7648..ad4f7e19a9fd40b82684c0acc11a458073bbb16b 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegator.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegator.md @@ -8,21 +8,18 @@ The **AbilityDelegator** module provides APIs for managing **AbilityMonitor** in ## Usage -The ability delegator can be obtained by calling **getAbilityDelegator** in **AbilityDelegatorRegistry**. -```js +An **AbilityDelegator** object is obtained by calling [getAbilityDelegator](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetabilitydelegator) in **AbilityDelegatorRegistry**. +```ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' -var abilityDelegator; - -abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); - +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); ``` ## AbilityDelegator ### addAbilityMonitor9+ -addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void +addAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to return the result. @@ -32,12 +29,12 @@ Adds an **AbilityMonitor** instance. This API uses an asynchronous callback to r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -55,11 +52,9 @@ abilityDelegator.addAbilityMonitor(monitor, (err : any) => { }); ``` - - ### addAbilityMonitor9+ -addAbilityMonitor(monitor: AbilityMonitor): Promise\ +addAbilityMonitor(monitor: AbilityMonitor): Promise\; Adds an **AbilityMonitor** instance. This API uses a promise to return the result. @@ -69,7 +64,7 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| **Return value** @@ -79,7 +74,7 @@ Adds an **AbilityMonitor** instance. This API uses a promise to return the resul **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -101,7 +96,7 @@ abilityDelegator.addAbilityMonitor(monitor).then(() => { ### removeAbilityMonitor9+ -removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void +removeAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; Removes an **AbilityMonitor** instance. This API uses an asynchronous callback to return the result. @@ -111,12 +106,12 @@ Removes an **AbilityMonitor** instance. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -138,7 +133,7 @@ abilityDelegator.removeAbilityMonitor(monitor, (err : any) => { ### removeAbilityMonitor9+ -removeAbilityMonitor(monitor: AbilityMonitor): Promise\ +removeAbilityMonitor(monitor: AbilityMonitor): Promise\; Removes an **AbilityMonitor** instance. This API uses a promise to return the result. @@ -148,7 +143,7 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| **Return value** @@ -158,7 +153,7 @@ Removes an **AbilityMonitor** instance. This API uses a promise to return the re - Example -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -180,7 +175,7 @@ abilityDelegator.removeAbilityMonitor(monitor).then(() => { ### waitAbilityMonitor9+ -waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void +waitAbilityMonitor(monitor: AbilityMonitor, callback: AsyncCallback\): void; Waits for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses an asynchronous callback to return the result. @@ -190,12 +185,12 @@ Waits for the **Ability** instance that matches the **AbilityMonitor** instance | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| -| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result. | +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| +| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -213,11 +208,9 @@ abilityDelegator.waitAbilityMonitor(monitor, (err : any, data : any) => { }); ``` - - ### waitAbilityMonitor9+ -waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void +waitAbilityMonitor(monitor: AbilityMonitor, timeout: number, callback: AsyncCallback\): void; Waits a period of time for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses an asynchronous callback to return the result. @@ -227,13 +220,13 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| -| timeout | number | Yes | Maximum waiting time, in milliseconds. | -| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result. | +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| +| timeout | number | No | Maximum waiting time, in milliseconds. | +| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var timeout = 100; @@ -256,7 +249,7 @@ abilityDelegator.waitAbilityMonitor(monitor, timeout, (err : any, data : any) => ### waitAbilityMonitor9+ -waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\ +waitAbilityMonitor(monitor: AbilityMonitor, timeout?: number): Promise\; Waits a period of time for the **Ability** instance that matches the **AbilityMonitor** instance to reach the **OnCreate** lifecycle state and returns the **Ability** instance. This API uses a promise to return the result. @@ -266,18 +259,18 @@ Waits a period of time for the **Ability** instance that matches the **AbilityMo | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-application-abilityMonitor.md#AbilityMonitor) instance.| +| monitor | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) | Yes | [AbilityMonitor](js-apis-inner-application-abilityMonitor.md#AbilityMonitor) instance.| | timeout | number | No | Maximum waiting time, in milliseconds. | **Return value** | Type | Description | | ----------------------------------------------------------- | -------------------------- | -| Promise\<[Ability](js-apis-application-ability.md#Ability)> | Promise used to return the **Ability** instance.| +| Promise\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Promise used to return the **Ability** instance.| **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -299,7 +292,7 @@ abilityDelegator.waitAbilityMonitor(monitor).then((data : any) => { ### getAppContext9+ -getAppContext(): Context +getAppContext(): Context; Obtains the application context. @@ -309,11 +302,11 @@ Obtains the application context. | Type | Description | | ------------------------------------- | ------------------------------------------- | -| [Context](js-apis-Context.md#Context) | [Context](js-apis-Context.md#Context) of the application.| +| [Context](js-apis-inner-application-context.md) | Application [context](js-apis-inner-application-context.md).| **Example** -```js +```ts var abilityDelegator; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); @@ -324,7 +317,7 @@ var context = abilityDelegator.getAppContext(); ### getAbilityState9+ -getAbilityState(ability: Ability): number +getAbilityState(ability: UIAbility): number; Obtains the lifecycle state of an ability. @@ -334,17 +327,17 @@ Obtains the lifecycle state of an ability. | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------- | ---- | --------------- | -| ability | [Ability](js-apis-application-ability.md#Ability) | Yes | Target ability.| +| ability | [UIAbility](js-apis-app-ability-uiAbility.md) | Yes | Target ability.| **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Lifecycle state of the ability. For details about the available enumerated values, see [AbilityLifecycleState](js-apis-abilityDelegatorRegistry.md#AbilityLifecycleState).| +| number | Lifecycle state of the ability. For details about the available enumerated values, see [AbilityLifecycleState](js-apis-application-abilityDelegatorRegistry.md#AbilityLifecycleState).| **Example** -```js +```ts var abilityDelegator; var ability; @@ -361,7 +354,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### getCurrentTopAbility9+ -getCurrentTopAbility(callback: AsyncCallback\): void +getCurrentTopAbility(callback: AsyncCallback\): void; Obtains the top ability of this application. This API uses an asynchronous callback to return the result. @@ -371,11 +364,11 @@ Obtains the top ability of this application. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | -| callback | AsyncCallback\<[Ability](js-apis-application-ability.md#Ability)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Yes | Callback used to return the result.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -390,7 +383,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### getCurrentTopAbility9+ -getCurrentTopAbility(): Promise\ +getCurrentTopAbility(): Promise\; Obtains the top ability of this application. This API uses a promise to return the result. @@ -400,11 +393,11 @@ Obtains the top ability of this application. This API uses a promise to return t | Type | Description | | ----------------------------------------------------------- | -------------------------------------- | -| Promise\<[Ability](js-apis-application-ability.md#Ability)> | Promise used to return the top ability.| +| Promise\<[UIAbility](js-apis-app-ability-uiAbility.md)> | Promise used to return the top ability.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -419,7 +412,7 @@ abilityDelegator.getCurrentTopAbility().then((data : any) => { ### startAbility9+ -startAbility(want: Want, callback: AsyncCallback\): void +startAbility(want: Want, callback: AsyncCallback\): void; Starts an ability. This API uses an asynchronous callback to return the result. @@ -429,12 +422,12 @@ Starts an ability. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | -------------------------------------- | ---- | ------------------ | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** parameter for starting the ability. | +| want | [Want](js-apis-application-want.md) | Yes | **Want** parameter for starting the ability. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -```js +```ts var abilityDelegator; var want = { bundleName: "bundleName", @@ -451,7 +444,7 @@ abilityDelegator.startAbility(want, (err : any, data : any) => { ### startAbility9+ -startAbility(want: Want): Promise\ +startAbility(want: Want): Promise\; Starts an ability. This API uses a promise to return the result. @@ -461,7 +454,7 @@ Starts an ability. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | -------------------------------------- | ---- | --------------- | -| want | [Want](js-apis-application-Want.md) | Yes | **Want** parameter for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes | **Want** parameter for starting the ability.| **Return value** @@ -471,7 +464,7 @@ Starts an ability. This API uses a promise to return the result. **Example** -```js +```ts var abilityDelegator; var want = { bundleName: "bundleName", @@ -488,7 +481,7 @@ abilityDelegator.startAbility(want).then((data: any) => { ### doAbilityForeground9+ -doAbilityForeground(ability: Ability, callback: AsyncCallback\): void +doAbilityForeground(ability: UIAbility, callback: AsyncCallback\): void; Schedules the lifecycle state of an ability to **Foreground**. This API uses an asynchronous callback to return the result. @@ -498,12 +491,12 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses an | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------- | -| ability | Ability | Yes | Target ability. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| +| ability | UIAbility | Yes | Target ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -521,7 +514,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### doAbilityForeground9+ -doAbilityForeground(ability: Ability): Promise\ +doAbilityForeground(ability: UIAbility): Promise\; Schedules the lifecycle state of an ability to **Foreground**. This API uses a promise to return the result. @@ -531,7 +524,7 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p | Name | Type | Mandatory| Description | | ------- | ------- | ---- | --------------- | -| ability | Ability | Yes | Target ability.| +| ability | UIAbility | Yes | Target ability.| **Return value** @@ -541,7 +534,7 @@ Schedules the lifecycle state of an ability to **Foreground**. This API uses a p **Example** -```js +```ts var abilityDelegator; var ability; @@ -559,7 +552,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### doAbilityBackground9+ -doAbilityBackground(ability: Ability, callback: AsyncCallback\): void +doAbilityBackground(ability: UIAbility, callback: AsyncCallback\): void; Schedules the lifecycle state of an ability to **Background**. This API uses an asynchronous callback to return the result. @@ -569,12 +562,12 @@ Schedules the lifecycle state of an ability to **Background**. This API uses an | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------- | -| ability | Ability | Yes | Target ability. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| +| ability | UIAbility | Yes | Target ability. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
\- **true**: The operation is successful.
\- **false**: The operation failed.| **Example** -```js +```ts var abilityDelegator; var ability; @@ -592,7 +585,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### doAbilityBackground9+ -doAbilityBackground(ability: Ability): Promise\ +doAbilityBackground(ability: UIAbility): Promise\; Schedules the lifecycle state of an ability to **Background**. This API uses a promise to return the result. @@ -602,7 +595,7 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p | Name | Type | Mandatory| Description | | ------- | ------- | ---- | --------------- | -| ability | Ability | Yes | Target ability.| +| ability | UIAbility | Yes | Target ability.| **Return value** @@ -612,7 +605,7 @@ Schedules the lifecycle state of an ability to **Background**. This API uses a p **Example** -```js +```ts var abilityDelegator; var ability; @@ -630,7 +623,7 @@ abilityDelegator.getCurrentTopAbility((err : any, data : any) => { ### printSync9+ -printSync(msg: string): void +printSync(msg: string): void; Prints log information to the unit test console. @@ -644,7 +637,7 @@ Prints log information to the unit test console. **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -656,7 +649,7 @@ abilityDelegator.printSync(msg); ### print -print(msg: string, callback: AsyncCallback\): void +print(msg: string, callback: AsyncCallback\): void; Prints log information to the unit test console. This API uses an asynchronous callback to return the result. @@ -671,7 +664,7 @@ Prints log information to the unit test console. This API uses an asynchronous c **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -685,7 +678,7 @@ abilityDelegator.print(msg, (err : any) => { ### print -print(msg: string): Promise\ +print(msg: string): Promise\; Prints log information to the unit test console. This API uses a promise to return the result. @@ -705,7 +698,7 @@ Prints log information to the unit test console. This API uses a promise to retu **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -719,7 +712,7 @@ abilityDelegator.print(msg).then(() => { ### executeShellCommand -executeShellCommand(cmd: string, callback: AsyncCallback\): void +executeShellCommand(cmd: string, callback: AsyncCallback\): void; Executes a shell command. This API uses an asynchronous callback to return the result. @@ -730,11 +723,11 @@ Executes a shell command. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ------------------ | | cmd | string | Yes | Shell command string. | -| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result.| +| callback | AsyncCallback\<[ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result.| **Example** -```js +```ts var abilityDelegator; var cmd = "cmd"; @@ -748,7 +741,7 @@ abilityDelegator.executeShellCommand(cmd, (err : any, data : any) => { ### executeShellCommand -executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void +executeShellCommand(cmd: string, timeoutSecs: number, callback: AsyncCallback\): void; Executes a shell command with the timeout period specified. This API uses an asynchronous callback to return the result. @@ -759,12 +752,12 @@ Executes a shell command with the timeout period specified. This API uses an asy | Name | Type | Mandatory| Description | | ----------- | ------------------------------------------------------------ | ---- | ----------------------------- | | cmd | string | Yes | Shell command string. | -| timeoutSecs | number | Yes | Command timeout period, in seconds.| -| callback | AsyncCallback\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result. | +| timeoutSecs | number | No | Command timeout period, in seconds.| +| callback | AsyncCallback\<[ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult)> | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var cmd = "cmd"; var timeout = 100; @@ -779,7 +772,7 @@ abilityDelegator.executeShellCommand(cmd, timeout, (err : any, data : any) => { ### executeShellCommand -executeShellCommand(cmd: string, timeoutSecs?: number): Promise\ +executeShellCommand(cmd: string, timeoutSecs?: number): Promise\; Executes a shell command with the timeout period specified. This API uses a promise to return the result. @@ -796,11 +789,11 @@ Executes a shell command with the timeout period specified. This API uses a prom | Type | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | -| Promise\<[ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult)> | Promise used to return a [ShellCmdResult](js-apis-application-shellCmdResult.md#ShellCmdResult) object.| +| Promise\<[ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult)> | Promise used to return a [ShellCmdResult](js-apis-inner-application-shellCmdResult.md#ShellCmdResult) object.| **Example** -```js +```ts var abilityDelegator; var cmd = "cmd"; var timeout = 100; @@ -815,7 +808,7 @@ abilityDelegator.executeShellCommand(cmd, timeout).then((data : any) => { ### finishTest9+ -finishTest(msg: string, code: number, callback: AsyncCallback\): void +finishTest(msg: string, code: number, callback: AsyncCallback\): void; Finishes the test and prints log information to the unit test console. This API uses an asynchronous callback to return the result. @@ -831,7 +824,7 @@ Finishes the test and prints log information to the unit test console. This API **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -845,7 +838,7 @@ abilityDelegator.finishTest(msg, 0, (err : any) => { ### finishTest9+ -finishTest(msg: string, code: number): Promise\ +finishTest(msg: string, code: number): Promise\; Finishes the test and prints log information to the unit test console. This API uses a promise to return the result. @@ -866,7 +859,7 @@ Finishes the test and prints log information to the unit test console. This API **Example** -```js +```ts var abilityDelegator; var msg = "msg"; @@ -888,12 +881,12 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -921,7 +914,7 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| **Return value** @@ -931,7 +924,7 @@ Adds an **AbilityStageMonitor** instance to monitor the lifecycle state changes **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -957,12 +950,12 @@ Removes an **AbilityStageMonitor** instance from the application memory. This AP | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -990,7 +983,7 @@ Removes an **AbilityStageMonitor** object from the application memory. This API | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| **Return value** @@ -1000,7 +993,7 @@ Removes an **AbilityStageMonitor** object from the application memory. This API **Example** -```js +```ts var abilityDelegator; var monitor = { @@ -1026,12 +1019,12 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | -------- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. | **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -1048,7 +1041,7 @@ abilityDelegator.waitAbilityStageMonitor(monitor, (err : any, data : any) => { console.info("waitAbilityStageMonitor callback"); }); ``` - + ### waitAbilityStageMonitor9+ waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\; @@ -1061,7 +1054,7 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | timeout | number | No | Maximum waiting time, in milliseconds.| **Return value** @@ -1072,7 +1065,7 @@ Waits for an **AbilityStage** instance that matches the conditions set in an **A **Example** -```js +```ts var abilityDelegator; function onAbilityCreateCallback(data) { @@ -1102,13 +1095,13 @@ Waits a period of time for an **AbilityStage** instance that matches the conditi | Name | Type | Mandatory| Description | | ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| monitor | [AbilityStageMonitor](#abilitystagemonitor) | Yes | [AbilityStageMonitor](#abilitystagemonitor) instance.| +| monitor | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) | Yes | [AbilityStageMonitor](js-apis-inner-application-abilityStageMonitor.md) instance.| | timeout | number | No | Maximum waiting time, in milliseconds.| | callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, an **AbilityStage** instance is returned. Otherwise, no value is returned. | **Example** -```js +```ts var abilityDelegator; var timeout = 100; @@ -1126,14 +1119,3 @@ abilityDelegator.waitAbilityStageMonitor(monitor, timeout, (err : any, data : an console.info("waitAbilityStageMonitor callback"); }); ``` - -## AbilityStageMonitor - -Provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Readable| Writable| Description | -| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | -| moduleName9+ | string | Yes | Yes | Module name of the **AbilityStage** instance.| -| srcEntrance9+ | string | Yes | Yes | Source path of the **AbilityStage** instance.| diff --git a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md similarity index 67% rename from en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md rename to en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md index e1b3aa3bbe5e16262db584894055c090a224b625..a5f131c3e02071f3d55cbfdc73955ffef42889d3 100644 --- a/en/application-dev/reference/apis/js-apis-application-abilityDelegatorArgs.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityDelegatorArgs.md @@ -1,6 +1,6 @@ # AbilityDelegatorArgs -The **AbilityDelegatorArgs** module provides a global register to store the registered **AbilityDelegator** and **AbilityDelegatorArgs** instances during application startup. +The **AbilityDelegatorArgs** module provides APIs to obtain an **AbilityDelegatorArgs** object during the execution of test cases. > **NOTE** > @@ -8,13 +8,7 @@ The **AbilityDelegatorArgs** module provides a global register to store the regi ## Usage -The ability delegator arguments are obtained by calling **getArguments** in **AbilityDelegatorRegistry**. - -```js -import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; - -var args = AbilityDelegatorRegistry.getArguments(); -``` +An **AbilityDelegatorArgs** object is obtained by calling [getArguments](js-apis-app-ability-abilityDelegatorRegistry.md#abilitydelegatorregistrygetarguments) in **AbilityDelegatorRegistry**. ## AbilityDelegatorArgs @@ -24,7 +18,15 @@ Describes the ability delegator arguments. | Name | Type | Readable| Writable| Description | | ------------------- | ---------------------- | ---- | ---- | ------------------------------------------------------------ | -| bundleName | string | Yes | Yes | Bundle name of the application to test. | -| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently. | -| testCaseNames | string | Yes | Yes | Test case names. | -| testRunnerClassName | string | Yes | Yes | Names of the test case executors. | +| bundleName | string | Yes | Yes | Bundle name of the application to test.| +| parameters | {[key:string]: string} | Yes | Yes | Parameters of the unit test that is started currently.| +| testCaseNames | string | Yes | Yes | Test case names.| +| testRunnerClassName | string | Yes | Yes | Names of the test case executors.| + +**Example** + +```ts +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; + +var args = AbilityDelegatorRegistry.getArguments(); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md new file mode 100644 index 0000000000000000000000000000000000000000..d8726205b8caec547f270e8efe6472e37cd99eb4 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityMonitor.md @@ -0,0 +1,48 @@ +# AbilityMonitor + +The **AbilityMonitor** module provides monitors for abilities that meet specified conditions. The latest matched abilities are stored in an **AbilityMonitor** object. + +> **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. + +## Usage + +**AbilityMonitor** can be used as an input parameter of [addAbilityMonitor](js-apis-inner-application-abilityDelegator.md#addabilitymonitor9) in **abilityDelegator** to listen for lifecycle changes of an ability. + +## AbilityMonitor + +Describes an ability monitor. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| abilityName | string | Yes | Yes | Name of the ability bound to the ability monitor.| +| onAbilityCreate?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| +| onAbilityForeground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the foreground.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| +| onAbilityBackground?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability starts to run in the background.
If this attribute is not set, the corresponding lifecycle callback cannot be received.| +| onAbilityDestroy?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the ability is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| +| onWindowStageCreate?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the window stage is created.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| +| onWindowStageRestore?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the window stage is restored.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| +| onWindowStageDestroy?:(data: [UIAbility](js-apis-app-ability-uiAbility.md)) | function | Yes | Yes | Called when the window stage is destroyed.
If this attribute is not set, the corresponding lifecycle callback cannot be received.
| + +**Example** + +```ts +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' + +function onAbilityCreateCallback(data) { + console.info("onAbilityCreateCallback"); +} + +var monitor = { + abilityName: "abilityname", + onAbilityCreate: onAbilityCreateCallback +} + +var abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.addAbilityMonitor(monitor, (err : any) => { + console.info("addAbilityMonitor callback"); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..62b1f7e1fae204f2e6b1f6dcdc76521da3c51777 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityRunningInfo.md @@ -0,0 +1,44 @@ +# AbilityRunningInfo + +The **AbilityRunningInfo** module defines the running information and state of an ability. + +> **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. + +## Usage + +The ability running information is obtained by calling [getAbilityRunningInfos](js-apis-app-ability-abilityManager.md#getabilityrunninginfos) in **abilityManager**. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ability | ElementName | Yes| No| Information that matches an ability. | +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID. | +| processName | string | Yes| No| Process name. | +| startTime | number | Yes| No| Ability start time. | +| abilityState | [abilityManager.AbilityState](js-apis-app-ability-abilityManager.md#abilitystate) | Yes| No| Ability state. | + +**Example** + +```ts +import abilitymanager from '@ohos.application.abilityManager'; +abilitymanager.getAbilityRunningInfos((err,data) => { + console.log("getAbilityRunningInfos err: " + err + " data: " + JSON.stringify(data)); + for (let i = 0; i < data.length; i++) { + let abilityinfo = data[i]; + console.log("abilityinfo.ability: " + JSON.stringify(abilityinfo.ability)); + console.log("abilityinfo.pid: " + JSON.stringify(abilityinfo.pid)); + console.log("abilityinfo.uid: " + JSON.stringify(abilityinfo.uid)); + console.log("abilityinfo.processName: " + JSON.stringify(abilityinfo.processName)); + console.log("abilityinfo.startTime: " + JSON.stringify(abilityinfo.startTime)); + console.log("abilityinfo.abilityState: " + JSON.stringify(abilityinfo.abilityState)); + } +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md similarity index 81% rename from en/application-dev/reference/apis/js-apis-abilitystagecontext.md rename to en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md index 5475dc51466d01d8eadef472248cce237f1b6241..79f750797c12bfd9c323e2f613650c016ea2930b 100644 --- a/en/application-dev/reference/apis/js-apis-abilitystagecontext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageContext.md @@ -13,7 +13,7 @@ This module provides APIs for accessing a specific ability stage. You can use th The ability stage context is obtained through an **AbilityStage** instance. -```js +```ts import AbilityStage from '@ohos.application.AbilityStage'; class MyAbilityStage extends AbilityStage { onCreate() { @@ -26,7 +26,7 @@ class MyAbilityStage extends AbilityStage { **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name| Type| Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| -| config | [Configuration](js-apis-configuration.md) | Yes| No| Configuration for the environment where the application is running.| +| currentHapModuleInfo | HapModuleInfo | Yes| No| **ModuleInfo** object corresponding to the **AbilityStage**.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Configuration for the environment where the application is running.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md new file mode 100644 index 0000000000000000000000000000000000000000..76a4ae2e425ce91acb0f79d22889cba231809c26 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStageMonitor.md @@ -0,0 +1,25 @@ +# AbilityStageMonitor + +The **AbilityStageMonitor** module provides conditions for matching **AbilityStage** instances. The most recently matched **AbilityStage** instance is saved in an **AbilityStageMonitor** instance. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| ------------------------------------------------------------ | -------- | ---- | ---- | ------------------------------------------------------------ | +| moduleName9+ | string | Yes | Yes | Module name of the **AbilityStage** instance.| +| srcEntrance9+ | string | Yes | Yes | Source path of the **AbilityStage** instance.| + +**Example** +```ts +import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' + +let monitor = { + moduleName: "feature_as1", + srcEntrance: "./ets/Application/MyAbilityStage.ts", +}; + +let abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); +abilityDelegator.waitAbilityStageMonitor(monitor, (error, data) => { + console.info("stageMonitor waitAbilityStageMonitor, abilityStage = " + JSON.stringify(data)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md new file mode 100644 index 0000000000000000000000000000000000000000..eb539bd981610af81a6e9598bcab3da8dc3f9279 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-abilityStateData.md @@ -0,0 +1,36 @@ +# AbilityStateData + +The **AbilityStateData** module defines the ability state information, which can be obtained through the **onAbilityStateChanged** lifecycle callback of [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md). The callback can be invoked after a lifecycle change listener is registered through [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| pid8+ | number | Yes | No | Process ID. | +| bundleName8+ | string | Yes | No | Bundle name. | +| abilityName8+ | string | Yes | No | Ability name. | +| uid8+ | number | Yes | No | User ID. | +| state8+ | number | Yes | No | [Ability state](#ability-states). | +| moduleName9+ | string | Yes | No | Name of the HAP file to which the ability belongs. | +| abilityType8+ | number | Yes | No | [Ability type](#ability-types), which can be **page** or **service**.| + +#### Ability States + +| Value | State | Description | +| ---- | -------------------------- | ---------------------- | +| 0 | ABILITY_STATE_CREATE | The ability is being created. | +| 1 | ABILITY_STATE_READY | The ability has been created. | +| 2 | ABILITY_STATE_FOREGROUND | The ability is running in the foreground. | +| 3 | ABILITY_STATE_FOCUS | The ability has focus. | +| 4 | ABILITY_STATE_BACKGROUND | The ability is running in the background. | +| 5 | ABILITY_STATE_TERMINATED | The ability is terminated. | +| 8 | ABILITY_STATE_CONNECTED | The background service is connected to the client.| +| 9 | ABILITY_STATE_DISCONNECTED | The background service is disconnected from the client.| + +#### Ability Types + +| Value | Status | Description | +| ---- | ------- | --------------------- | +| 0 | UNKNOWN | Unknown type. | +| 1 | PAGE | Ability that has the UI. | +| 2 | SERVICE | Ability that provides the background service.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..63336a289f7804e9f69f1f0cf7db95b19a01d080 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-accessibilityExtensionContext.md @@ -0,0 +1,1159 @@ +# AccessibilityExtensionContext + +The **AccessibilityExtensionContext** module, inherited from **ExtensionContext**, provides context for **Accessibility Extension** abilities. + +You can use the APIs of this module to configure the concerned information, obtain root information, and inject gestures. + +> **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. + +## Usage + +Before using the **AccessibilityExtensionContext** module, you must define a child class that inherits from **AccessibilityExtensionAbility**. + +```ts +import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' +let axContext; +class EntryAbility extends AccessibilityExtensionAbility { + onConnect(): void { + console.log('AxExtensionAbility onConnect'); + axContext = this.context; + } +} +``` + +## FocusDirection + +Enumerates the focus directions. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Description | +| -------- | ------- | +| 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 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 the focus types. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Description | +| ------------- | ----------- | +| accessibility | Accessibility focus.| +| normal | Normal focus. | + +## Rect + +Defines a rectangle. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Type | Readable | Writable | Description | +| ------ | ------ | ---- | ---- | --------- | +| left | number | Yes | No | Left boundary of the rectangle.| +| top | number | Yes | No | Top boundary of the rectangle.| +| width | number | Yes | No | Width of the rectangle. | +| height | number | Yes | No | Height of the rectangle. | + +## WindowType + +Enumerates the window types. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name | Description | +| ----------- | --------- | +| application | Application window.| +| system | System window.| + +## AccessibilityExtensionContext.setTargetBundleName + +setTargetBundleName(targetNames: Array\): Promise\; + +Sets the concerned target bundle. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | ---- | -------- | +| targetNames | Array<string> | Yes | Name of the target bundle.| + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +let targetNames = ['com.ohos.xyz']; +try { + axContext.setTargetBundleName(targetNames).then(() => { + console.info('set target bundle names success'); + }).catch((err) => { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; +``` + +## AccessibilityExtensionContext.setTargetBundleName + +setTargetBundleName(targetNames: Array\, callback: AsyncCallback\): void; + +Sets the concerned target bundle. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ------------------- | ---- | -------- | +| targetNames | Array<string> | Yes | Name of the target bundle.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation fails, **error** that contains data is returned.| + +**Example** + +```ts +let targetNames = ['com.ohos.xyz']; +try { + axContext.setTargetBundleName(targetNames, (err, data) => { + if (err) { + console.error('failed to set target bundle names, because ' + JSON.stringify(err)); + return; + } + console.info('set target bundle names success'); + }); +} catch (exception) { + console.error('failed to set target bundle names, because ' + JSON.stringify(exception)); +}; +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(isAccessibilityFocus?: boolean): Promise\; + +Obtains the focus element. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| isAccessibilityFocus | boolean | No | Whether the obtained focus element is an accessibility focus. The default value is **false**.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<AccessibilityElement> | Promise used to return the current focus element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let focusElement; +try { + axContext.getFocusElement().then((data) => { + focusElement = data; + console.log('get focus element success'); + }).catch((err) => { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(callback: AsyncCallback\): void; + +Obtains the focus element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let focusElement; +try { + axContext.getFocusElement((err, data) => { + if (err) { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); + }); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(isAccessibilityFocus: boolean, callback: AsyncCallback\): void; + +Obtains the focus element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| isAccessibilityFocus | boolean | Yes | Whether the obtained focus element is an accessibility focus.| +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the current focus element.| + +**Example** + +```ts +let focusElement; +let isAccessibilityFocus = true; +try { + axContext.getFocusElement(isAccessibilityFocus, (err, data) => { + if (err) { + console.error('failed to get focus element, because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); +}); +} catch (exception) { + console.error('failed to get focus element, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(windowId?: number): Promise\; + +Obtains the root element of a window. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| windowId | number | No | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<AccessibilityElement> | Promise used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +try { + axContext.getWindowRootElement().then((data) => { + rootElement = data; + console.log('get root element of the window success'); + }).catch((err) => { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get root element of the window, ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(callback: AsyncCallback\): void; + +Obtains the root element of a window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +try { + axContext.getWindowRootElement((err, data) => { + if (err) { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + return; + } + rootElement = data; + console.info('get root element of the window success'); +}); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(windowId: number, callback: AsyncCallback\): void; + +Obtains the root element of a window. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| windowId | number | Yes | Window for which you want to obtain the root element. If this parameter is not specified, it indicates the current active window.| +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the root element.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let rootElement; +let windowId = 10; +try { + axContext.getWindowRootElement(windowId, (err, data) => { + if (err) { + console.error('failed to get root element of the window, because ' + JSON.stringify(err)); + return; + } + rootElement = data; + console.info('get root element of the window success'); +}); +} catch (exception) { + console.error('failed to get root element of the window, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(displayId?: number): Promise\>; + +Obtains the list of windows on a display. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | No | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<Array<AccessibilityElement>> | Promise used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +try { + axContext.getWindows().then((data) => { + windows = data; + console.log('get windows success'); + }).catch((err) => { + console.error('failed to get windows, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(callback: AsyncCallback\>): void; + +Obtains the list of windows on a display. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +try { + axContext.getWindows((err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(displayId: number, callback: AsyncCallback\>): void; + +Obtains the list of windows on a display. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | Yes | ID of the display from which the window information is obtained. If this parameter is not specified, it indicates the default main display.| +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the window list.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +let windows; +let displayId = 10; +try { + axContext.getWindows(displayId, (err, data) => { + if (err) { + console.error('failed to get windows, because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); + }); +} catch (exception) { + console.error('failed to get windows, because ' + JSON.stringify(exception)); +} +``` + +## AccessibilityExtensionContext.injectGesture + +injectGesture(gesturePath: GesturePath): Promise\; + +Inject a gesture. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | + +**Return value** + +| Type | Description | +| ----------------------------------- | ---------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePoint from '@ohos.accessibility.GesturePoint'; +let gesturePath = new GesturePath.GesturePath(100); +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint.GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); + } + axContext.injectGesture(gesturePath).then(() => { + console.info('inject gesture success'); + }).catch((err) => { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityExtensionContext.injectGesture + +injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void + +Inject a gesture. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | Yes | Path of the gesture to inject. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300003 | Do not have accessibility right for this operation. | + +**Example** + +```ts +import GesturePath from "@ohos.accessibility.GesturePath"; +import GesturePoint from '@ohos.accessibility.GesturePoint'; +let gesturePath = new GesturePath.GesturePath(100); +try { + for (let i = 0; i < 10; i++) { + let gesturePoint = new GesturePoint.GesturePoint(100, i * 200); + gesturePath.points.push(gesturePoint); + } + axContext.injectGesture(gesturePath, (err, data) => { + if (err) { + console.error('failed to inject gesture, because ' + JSON.stringify(err)); + return; + } + console.info('inject gesture success'); + }); +} catch (exception) { + console.error('failed to inject gesture, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityElement9+ + +Defines the accessibilityelement. Before calling APIs of **AccessibilityElement**, you must call [AccessibilityExtensionContext.getFocusElement()](#accessibilityextensioncontextgetfocuselement) or [AccessibilityExtensionContext.getWindowRootElement()](#accessibilityextensioncontextgetwindowrootelement) to obtain an **AccessibilityElement** instance. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +## attributeNames + +attributeNames\(): Promise\>; + +Obtains all attribute names of this element. This API uses a promise to return the result. + +**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 rootElement; +let attributeNames; +rootElement.attributeNames().then((data) => { + console.log('get attribute names success'); + attributeNames = data; +}).catch((err) => { + console.log('failed to get attribute names, because ' + JSON.stringify(err)); +}); +``` +## attributeNames + +attributeNames\(callback: AsyncCallback\>): void; + +Obtains all attribute names of this element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<T>> | Yes | Callback used to return all attribute names of the element.| + +**Example** + +```ts +let rootElement; +let attributeNames; +rootElement.attributeNames((err, data) => { + if (err) { + console.error('failed to get attribute names, because ' + JSON.stringify(err)); + return; + } + attributeNames = data; + console.info('get attribute names success'); +}); +``` +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T): Promise\; + +Obtains the attribute value based on an attribute name. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<ElementAttributeValues[T]> | Promise used to return the attribute value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + +**Example** + +```ts +let attributeName = 'name'; +let attributeValue; +let rootElement; +try { + rootElement.attributeValue(attributeName).then((data) => { + console.log('get attribute value by name success'); + attributeValue = data; + }).catch((err) => { + console.log('failed to get attribute value, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); +} +``` +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T, + callback: AsyncCallback\): void; + +Obtains the attribute value based on an attribute name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | Yes | Attribute name. | +| callback | AsyncCallback<ElementAttributeValues[T]> | Yes | Callback used to return the attribute value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300004 | This property does not exist. | + +**Example** + +```ts +let rootElement; +let attributeValue; +let attributeName = 'name'; +try { + rootElement.attributeValue(attributeName, (err, data) => { + if (err) { + console.error('failed to get attribute value, because ' + JSON.stringify(err)); + return; + } + attributeValue = data; + console.info('get attribute value success'); + }); +} catch (exception) { + console.log('failed to get attribute value, because ' + JSON.stringify(exception)); +} +``` +## actionNames + +actionNames(): Promise\>; + +Obtains the names of all actions supported by this element. This API uses a promise to return the result. + +**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 rootElement; +let actionNames; +rootElement.actionNames().then((data) => { + console.log('get action names success'); + actionNames = data; +}).catch((err) => { + console.log('failed to get action names because ' + JSON.stringify(err)); +}); +``` +## actionNames + +actionNames(callback: AsyncCallback\>): void; + +Obtains the names of all actions supported by this element. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<string>> | Yes | Callback used to return the names of all actions supported by the element.| + +**Example** + +```ts +let rootElement; +let actionNames; +rootElement.actionNames((err, data) => { + if (err) { + console.error('failed to get action names, because ' + JSON.stringify(err)); + return; + } + actionNames = data; + console.info('get action names success'); +}); +``` +## performAction + +performAction(actionName: string, parameters?: object): Promise\; + +Performs an action based on the specified action name. This API uses a promise to return the result. + +**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<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +try { + rootElement.performAction('action').then((data) => { + console.info('perform action success'); + }).catch((err) => { + console.log('failed to perform action, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## performAction + +performAction(actionName: string, callback: AsyncCallback\): void; + +Performs an action based on the specified action name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Attribute name. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +try { + rootElement.performAction('action', (err, data) => { + if (err) { + console.error('failed to perform action, because ' + JSON.stringify(err)); + return; + } + console.info('perform action success'); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## performAction + +performAction(actionName: string, parameters: object, callback: AsyncCallback\): void; + +Performs an action based on the specified action name. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | Yes | Action name. | +| parameters | object | Yes | Parameter required for performing the target action. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Accessibility Error Codes](../errorcodes/errorcode-accessibility.md). + +| ID| Error Message| +| ------- | -------------------------------- | +| 9300005 | This action is not supported. | + +**Example** + +```ts +let rootElement; +let actionName = 'action'; +let parameters = { + 'setText': 'test text' +}; +try { + rootElement.performAction(actionName, parameters, (err, data) => { + if (err) { + console.error('failed to perform action, because ' + JSON.stringify(err)); + return; + } + console.info('perform action success'); + }); +} catch (exception) { + console.log('failed to perform action, because ' + JSON.stringify(exception)); +} +``` +## findElement('content') + +findElement(type: 'content', condition: string): Promise\>; + +Queries the element information of the **content** type. This API uses a promise to return the result. + +**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<AccessibilityElement>> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'content'; +let condition = 'keyword'; +let elements; +try { + rootElement.findElement(type, condition).then((data) => { + elements = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('content') + +findElement(type: 'content', condition: string, callback: AsyncCallback\>): void; + +Queries the element information of the **content** type. This API uses an asynchronous callback to return the result. + +**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. | +| callback | AsyncCallback<Array<AccessibilityElement>> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'content'; +let condition = 'keyword'; +let elements; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType): Promise\; + +Queries the element information of the **focusType** type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**. | +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<AccessibilityElement> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusType'; +let condition = 'normal'; +let element; +try { + rootElement.findElement(type, condition).then((data) => { + element = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\): void; + +Queries the element information of the **focusType** type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusType'**. | +| condition | [FocusType](#focustype) | Yes | Enumerates the focus types. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusType'; +let condition = 'normal'; +let element; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + element = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection): Promise\; + +Queries the element information of the **focusDirection** type. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | +| condition | [FocusDirection](#focusdirection) | Yes | Enumerates the focus directions. | + +**Return value** + +| Type | Description | +| ---------------------------------------- | ------------------------ | +| Promise<AccessibilityElement> | Promise used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusDirection'; +let condition = 'up'; +let element; +try { + rootElement.findElement(type, condition).then((data) => { + element = data; + console.log('find element success'); + }).catch((err) => { + console.log('failed to find element, because ' + JSON.stringify(err)); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\): void; + +Queries the element information of the **focusDirection** type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | Yes | Information type. The value is fixed at **'focusDirection'**. | +| condition | [FocusDirection](#focusdirection) | Yes | Direction of the next focus element. | +| callback | AsyncCallback<AccessibilityElement> | Yes | Callback used to return the result.| + +**Example** + +```ts +let rootElement; +let type = 'focusDirection'; +let condition = 'up'; +let elements; +try { + rootElement.findElement(type, condition, (err, data) => { + if (err) { + console.error('failed to find element, because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (exception) { + console.log('failed to find element, because ' + JSON.stringify(exception)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md new file mode 100644 index 0000000000000000000000000000000000000000..c281c62ff040c74bdc84def40b9db824ce95492a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-appStateData.md @@ -0,0 +1,35 @@ +# AppStateData + +The **AppStateData** module defines the application state data, which can be obtained through [getForegroundApplications](js-apis-app-ability-appManager.md#appmanagergetforegroundapplications). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This module is marked as @systemapi and not visible to third-party applications. + +| Name | Type | Mandatory | Description | +| ------------------------- | ------ | ---- | --------- | +| bundleName8+ | string | No | Bundle name.| +| uid8+ | number | No | UID of the application. | +| state8+ | number | No | Application state.
**0**: The application is being initialized.
**1**: The application has been initialized and is ready.
**2**: The application is running in the foreground.
**3**: The application is having the focus. (This state is reserved.)
**4**: The application is running in the background.
**5**: The application has exited.| + +**Example** + +```ts +import appManager from "@ohos.app.ability.appManager" + +function getForegroundAppInfos() { + appManager.getForegroundApplications((error, data) => { + if (error && error.code) { + console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + for (let i = 0; i < data.length; i++) { + let appStateData = data[i]; + console.log('appStateData.bundleName: ' + appStateData.bundleName); + console.log('appStateData.uid: ' + appStateData.uid); + console.log('appStateData.state: ' + appStateData.state); + } + }); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-application-applicationContext.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md similarity index 69% rename from en/application-dev/reference/apis/js-apis-application-applicationContext.md rename to en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md index 88eccc98c39c5373930f35465ca48da1df19c40d..73b2a329f018d64bf93ac8f64ece86792e4eff59 100644 --- a/en/application-dev/reference/apis/js-apis-application-applicationContext.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationContext.md @@ -11,11 +11,10 @@ The **ApplicationContext** module provides application-level context. You can us Before calling any APIs in **ApplicationContext**, obtain an **ApplicationContext** instance through the **context** instance. -```js +```ts let applicationContext = this.context.getApplicationContext(); ``` - ## ApplicationContext.registerAbilityLifecycleCallback registerAbilityLifecycleCallback(callback: AbilityLifecycleCallback): **number**; @@ -28,7 +27,7 @@ Registers a listener to monitor the ability lifecycle of the application. | Name | Type | Mandatory| Description | | ------------------------ | -------- | ---- | ------------------------------ | -| callback | [AbilityLifecycleCallback](js-apis-application-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.| +| callback | [AbilityLifecycleCallback](js-apis-app-ability-abilityLifecycleCallback.md) | Yes | Callback used to return the ID of the registered listener.| **Return value** @@ -38,34 +37,44 @@ Registers a listener to monitor the ability lifecycle of the application. **Example** - ```js -import AbilityStage from "@ohos.application.AbilityStage"; +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; var lifecycleId; -export default class MyAbilityStage extends AbilityStage { +export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbilityStage onCreate") - let AbilityLifecycleCallback = { - onAbilityCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + console.log("MyAbility onCreate") + let AbilityLifecycleCallback = { + onAbilityCreate(ability) { + console.log("AbilityLifecycleCallback onAbilityCreate ability:" + JSON.stringify(ability)); + }, + onWindowStageCreate(ability, windowStage) { + console.log("AbilityLifecycleCallback onWindowStageCreate ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageCreate windowStage:" + JSON.stringify(windowStage)); + }, + onWindowStageActive(ability, windowStage) { + console.log("AbilityLifecycleCallback onWindowStageActive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageActive windowStage:" + JSON.stringify(windowStage)); }, - onAbilityWindowStageCreate(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageCreate ability:" + JSON.stringify(ability)); + onWindowStageInactive(ability, windowStage) { + console.log("AbilityLifecycleCallback onWindowStageInactive ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageInactive windowStage:" + JSON.stringify(windowStage)); }, - onAbilityWindowStageDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityWindowStageDestroy ability:" + JSON.stringify(ability)); + onWindowStageDestroy(ability, windowStage) { + console.log("AbilityLifecycleCallback onWindowStageDestroy ability:" + JSON.stringify(ability)); + console.log("AbilityLifecycleCallback onWindowStageDestroy windowStage:" + JSON.stringify(windowStage)); }, - onAbilityDestroy(ability){ - console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); + onAbilityDestroy(ability) { + console.log("AbilityLifecycleCallback onAbilityDestroy ability:" + JSON.stringify(ability)); }, - onAbilityForeground(ability){ - console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); + onAbilityForeground(ability) { + console.log("AbilityLifecycleCallback onAbilityForeground ability:" + JSON.stringify(ability)); }, - onAbilityBackground(ability){ - console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); + onAbilityBackground(ability) { + console.log("AbilityLifecycleCallback onAbilityBackground ability:" + JSON.stringify(ability)); }, - onAbilityContinue(ability){ + onAbilityContinue(ability) { console.log("AbilityLifecycleCallback onAbilityContinue ability:" + JSON.stringify(ability)); } } @@ -75,15 +84,8 @@ export default class MyAbilityStage extends AbilityStage { lifecycleId = applicationContext.registerAbilityLifecycleCallback(AbilityLifecycleCallback); console.log("registerAbilityLifecycleCallback number: " + JSON.stringify(lifecycleId)); } - onDestroy() { - let applicationContext = this.context.getApplicationContext(); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - } } - ``` - +``` ## ApplicationContext.unregisterAbilityLifecycleCallback @@ -102,14 +104,21 @@ Deregisters the listener that monitors the ability lifecycle of the application. **Example** - ```js - let applicationContext = this.context.getApplicationContext(); - let lifecycleId = 1; - console.log("stage applicationContext: " + JSON.stringify(applicationContext)); - applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { - console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); - }); - ``` +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +var lifecycleId; + +export default class EntryAbility extends UIAbility { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + console.log("stage applicationContext: " + JSON.stringify(applicationContext)); + applicationContext.unregisterAbilityLifecycleCallback(lifecycleId, (error, data) => { + console.log("unregisterAbilityLifecycleCallback success, err: " + JSON.stringify(error)); + }); + } +} +``` ## ApplicationContext.registerEnvironmentCallback @@ -123,7 +132,7 @@ Registers a listener for system environment changes. This API uses an asynchrono | Name | Type | Mandatory| Description | | ------------------------ | -------- | ---- | ------------------------------ | -| callback | [EnvironmentCallback](js-apis-application-EnvironmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| +| callback | [EnvironmentCallback](js-apis-app-ability-environmentCallback.md) | Yes | Callback used to return the ID of the registered listener.| **Return value** @@ -133,19 +142,22 @@ Registers a listener for system environment changes. This API uses an asynchrono **Example** - ```js -import AbilityStage from "@ohos.application.AbilityStage"; +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; var callbackId; -export default class MyAbilityStage extends AbilityStage { +export default class EntryAbility extends UIAbility { onCreate() { - console.log("MyAbilityStage onCreate") + console.log("MyAbility onCreate") globalThis.applicationContext = this.context.getApplicationContext(); let EnvironmentCallback = { onConfigurationUpdated(config){ console.log("onConfigurationUpdated config:" + JSON.stringify(config)); }, + onMemoryLevel(level){ + console.log("onMemoryLevel level:" + level); + } } // 1. Obtain an applicationContext object. let applicationContext = globalThis.applicationContext; @@ -153,14 +165,8 @@ export default class MyAbilityStage extends AbilityStage { callbackId = applicationContext.registerEnvironmentCallback(EnvironmentCallback); console.log("registerEnvironmentCallback number: " + JSON.stringify(callbackId)); } - onDestroy() { - let applicationContext = globalThis.applicationContext; - applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); - }); - } } - ``` +``` ## ApplicationContext.unregisterEnvironmentCallback @@ -179,10 +185,17 @@ Deregisters the listener for system environment changes. This API uses an asynch **Example** - ```js - let applicationContext = this.context.getApplicationContext(); - let callbackId = 1; - applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { - console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); - }); - ``` +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +var callbackId; + +export default class EntryAbility extends UIAbility { + onDestroy() { + let applicationContext = this.context.getApplicationContext(); + applicationContext.unregisterEnvironmentCallback(callbackId, (error, data) => { + console.log("unregisterEnvironmentCallback success, err: " + JSON.stringify(error)); + }); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md new file mode 100644 index 0000000000000000000000000000000000000000..e6d3137582ee3b485e4a342a4a5a3b6b5473ed32 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-applicationStateObserver.md @@ -0,0 +1,39 @@ +# ApplicationStateObserver + +The **ApplicationStateObserver** module defines an observer to listen for application state changes. It can be used as an input parameter in [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8) to listen for lifecycle changes of the current application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | ------------------------- | +| onForegroundApplicationChanged8+ | [AppStateData](js-apis-inner-application-appStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the foreground or background state of an application changes. | +| onAbilityStateChanged8+ | [AbilityStateData](js-apis-inner-application-abilityStateData.md) | AsyncCallback\ | Yes | No | Callback invoked when the ability state changes. | +| onProcessCreated8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is created. | +| onProcessDied8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when a process is destroyed. | +| onProcessStateChanged8+ | [ProcessData](js-apis-inner-application-processData.md) | AsyncCallback\ | Yes | No | Callback invoked when the process state is changed. | + +**Example** +```ts +import appManager from "@ohos.application.appManager" + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('onForegroundApplicationChanged appStateData: ' + JSON.stringify(appStateData)); + }, + onAbilityStateChanged(abilityStateData) { + console.log('onAbilityStateChanged onAbilityStateChanged: ' + JSON.stringify(abilityStateData)); + }, + onProcessCreated(processData) { + console.log('onProcessCreated onProcessCreated: ' + JSON.stringify(processData)); + }, + onProcessDied(processData) { + console.log('onProcessDied onProcessDied: ' + JSON.stringify(processData)); + }, + onProcessStateChanged(processData) { + console.log('onProcessStateChanged onProcessStateChanged: ' + JSON.stringify(processData)); + } +} +let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md new file mode 100644 index 0000000000000000000000000000000000000000..3c0e5e3806181cbff0492cfe4faa387f315e516b --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-baseContext.md @@ -0,0 +1,28 @@ +# BaseContext + +**BaseContext** is an abstract class that specifies whether a child class **Context** is used for the stage model or FA model. It is the parent class for all types of **Context**. + +> **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. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------- | +| stageMode | boolean | Yes | Yes | Whether the child class **Context** is used for the stage model.
**true**: used for the stage model.
**false**: used for the FA model.| + +**Example** + +Take the stage model as an example. You can access the **stageMode** field through **UIAbilityContext**. + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + // EntryAbility onCreate, isStageMode: true + console.log("EntryAbility onCreate, isStageMode: " + this.context.stageMode); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-context.md b/en/application-dev/reference/apis/js-apis-inner-application-context.md new file mode 100644 index 0000000000000000000000000000000000000000..2a4fe5eaaf05dd8f7e6c907966a8a411382a6daa --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-context.md @@ -0,0 +1,184 @@ +# Context + +The **Context** module provides context for abilities or applications. It allows access to application-specific resources. + +> **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. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable | Writable | Description | +| ----------- | ------ | ---- | ---- | ------- | +| resourceManager | resmgr.[ResourceManager](js-apis-resource-manager.md) | Yes | No | Object for resource management. | +| applicationInfo | [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | Yes | No | Application information.| +| cacheDir | string | Yes | No | Cache directory.| +| tempDir | string | Yes | No | Temporary directory.| +| filesDir | string | Yes | No | File directory.| +| databaseDir | string | Yes | No | Database directory.| +| preferencesDir | string | Yes | No | Preferences directory.| +| bundleCodeDir | string | Yes | No | Bundle code directory.| +| distributedFilesDir | string | Yes | No | Distributed file directory.| +| eventHub | string | Yes | No | Event hub that implements event subscription, unsubscription, and triggering.| +| area | [AreaMode](#areamode) | Yes | No | Area in which the file to be access is located.| + +## Context.createBundleContext + +createBundleContext(bundleName: string): Context; + +Creates the context based on the bundle name. + +**Required permissions**: ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| bundleName | string | Yes | Bundle name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Context | Context created.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +let bundleContext; +try { + bundleContext = this.context.createBundleContext("com.example.test"); +} catch (error) { + console.log('createBundleContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} +``` + +## Context.createModuleContext + +createModuleContext(moduleName: string): Context; + +Creates the context based on the module name. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| moduleName | string | Yes | Module name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Context | Context created.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +let moduleContext; +try { + moduleContext = this.context.createModuleContext("entry"); +} catch (error) { + console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} +``` + +createModuleContext(bundleName: string, moduleName: string): Context; + +Creates the context based on the bundle name and module name. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | ------------- | +| bundleName | string | Yes | Bundle name.| +| moduleName | string | Yes | Module name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Context | Context created.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 401 | If the input parameter is not valid parameter. | + +For details about the error codes, see [Ability Error Codes](../errorcodes/errorcode-ability.md). + +**Example** + +```ts +let moduleContext; +try { + moduleContext = this.context.createModuleContext("com.example.test", "entry"); +} catch (error) { + console.log('createModuleContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} +``` + +## Context.getApplicationContext + +getApplicationContext(): ApplicationContext; + +Obtains the context of this application. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| [ApplicationContext](js-apis-inner-application-applicationContext.md) | Application context obtained.| + +**Example** + +```ts +let applicationContext; +try { + applicationContext = this.context.getApplicationContext(); +} catch (error) { + console.log('getApplicationContext failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} +``` + +## AreaMode + +Enumerates the areas in which the file to be access can be located. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Value| Description| +| -------- | -------- | -------- | +| EL1 | 0 | Device-level encryption area, which is accessible after the device is powered on.| +| EL2 | 1 | User-level encryption area, which is accessible only after the device is powered on and the password is entered (for the first time).| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md new file mode 100644 index 0000000000000000000000000000000000000000..b67c612c1b3b6dd82537b6dd5e6e7fcad2d6bdcb --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueCallback.md @@ -0,0 +1,46 @@ +# ContinueCallback + +The **ContinueCallback** module defines the callback function that indicates the result of mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission). + +## ContinueCallback.onContinueDone + +onContinueDone(result: number): void; + +Called when the mission continuation is complete. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | result | number | No| Mission continuation result.| + +**Example** + + ```ts + import distributedMissionManager from '@ohos.distributedMissionManager' + + let continueDeviceInfo = { + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } + }; + + let continueCallback = { + onContinueDone(result) { + console.log('onContinueDone, result: ' + JSON.stringify(result)); + } + }; + + distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { + if (error && error.code) { + console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + console.log('continueMission finished'); + }) + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..5582132e3f610a76175cbb73796b6283498c4395 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-continueDeviceInfo.md @@ -0,0 +1,41 @@ +# ContinueDeviceInfo + +The **ContinueDeviceInfo** module defines the parameters required for initiating mission continuation. For details about mission continuation, see [continueMission](js-apis-distributedMissionManager.md#distributedmissionmanagercontinuemission). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------- | +| srcDeviceId | string | Yes | Yes | ID of the source device.| +| dstDeviceId | string | Yes | Yes | ID of the target device.| +| missionId | number | Yes | Yes | Mission ID.| +| wantParam | {[key: string]: any} | Yes | Yes | Extended parameters.| + +**Example** + + ```ts + import distributedMissionManager from '@ohos.distributedMissionManager' + + let continueDeviceInfo = { + srcDeviceId: "123", + dstDeviceId: "456", + missionId: 123, + wantParam: { + "key":"value" + } + }; + + let continueCallback = { + onContinueDone(result) { + console.log('onContinueDone, result: ' + JSON.stringify(result)); + } + }; + + distributedMissionManager.continueMission(continueDeviceInfo, continueCallback, (error) => { + if (error && error.code) { + console.log('continueMission failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + console.log('continueMission finished'); + }) + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md new file mode 100644 index 0000000000000000000000000000000000000000..271f2697803dde9d0b3f78c3bb661a03d925b95e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-errorObserver.md @@ -0,0 +1,36 @@ +# ErrorObserver + +The **ErrorObserver** module defines an observer to listen for application errors. It can be used as an input parameter in [ErrorManager.on](js-apis-app-ability-errorManager.md#errormanageron) to listen for errors that occur in the current application. + +## ErrorObserver.onUnhandledException + +onUnhandledException(errMsg: string): void; + +Called when an unhandled exception occurs in the JS runtime. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| errMsg | string | No| Message and error stack trace about the exception.| + +**Example** + +```ts +import errorManager from '@ohos.app.ability.errorManager' + +let observer = { + onUnhandledException(errorMsg) { + console.log('HXW onUnhandledException, errorMsg: ', errorMsg); + } +} + +try { + errorManager.on("error", observer); +} catch (error) { + console.log('registerErrorObserver' + ' failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md new file mode 100644 index 0000000000000000000000000000000000000000..8b580177c7622b33b0d2c06749a928e825ae84bc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-eventHub.md @@ -0,0 +1,146 @@ +# EventHub + +The **EventHub** module provides APIs to subscribe to, unsubscribe from, and trigger events. + +> **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. + +## Usage + +Before using any APIs in the **EventHub**, you must obtain an **EventHub** instance through the member variable **context** of the **UIAbility** instance. + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + eventFunc(){ + console.log("eventFunc is called"); + } + + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc); + } +} +``` + +## EventHub.on + +on(event: string, callback: Function): void; + +Subscribes to an event. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| callback | Function | Yes| Callback invoked when the event is triggered.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc); + // Anonymous functions can be used to subscribe to events. + this.context.eventHub.on("myEvent", () => { + console.log("call anonymous eventFunc"); + }); + // Result + // eventFunc is called + // call anonymous eventFunc + this.context.eventHub.emit("myEvent"); + } + + eventFunc() { + console.log("eventFunc is called"); + } +} +``` + +## EventHub.off + +off(event: string, callback?: Function): void; + +Unsubscribes from an event. + - If **callback** is specified, this API unsubscribes from the given event with the specified callback. + - If **callback** is not specified, this API unsubscribes from the given event with all callbacks. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| callback | Function | No| Callback for the event. If **callback** is unspecified, the given event with all callbacks is unsubscribed.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc1); + this.context.eventHub.off("myEvent", this.eventFunc1); // Unsubscribe from the myEvent event with the callback eventFunc1. + this.context.eventHub.on("myEvent", this.eventFunc1); + this.context.eventHub.on("myEvent", this.eventFunc2); + this.context.eventHub.off("myEvent"); // Unsubscribe from the myEvent event with all the callbacks (eventFunc1 and eventFunc2). + } + + eventFunc1() { + console.log("eventFunc1 is called"); + } + + eventFunc2() { + console.log("eventFunc2 is called"); + } +} +``` + +## EventHub.emit + +emit(event: string, ...args: Object[]): void; + +Triggers an event. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| event | string | Yes| Event name.| +| ...args | Object[] | Yes| Variable parameters, which are passed to the callback when the event is triggered.| + +**Example** + +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + onForeground() { + this.context.eventHub.on("myEvent", this.eventFunc); + // Result + // eventFunc is called,undefined,undefined + this.context.eventHub.emit("myEvent"); + // Result + // eventFunc is called,1,undefined + this.context.eventHub.emit("myEvent", 1); + // Result + // eventFunc is called,1,2 + this.context.eventHub.emit("myEvent", 1, 2); + } + + eventFunc(argOne, argTwo) { + console.log("eventFunc is called," + argOne + "," + argTwo); + } +} +``` diff --git a/en/application-dev/reference/apis/js-apis-extension-context.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md similarity index 84% rename from en/application-dev/reference/apis/js-apis-extension-context.md rename to en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md index 71d3df6c294d62f2fafa0801df0d132b88c42fe3..a855d9577c9ef364caa7436a89983ca58d320d3c 100644 --- a/en/application-dev/reference/apis/js-apis-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionContext.md @@ -2,10 +2,10 @@ The **ExtensionContext** module, inherited from **Context**, implements the context for 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**. +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-inner-application-serviceExtensionContext.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. @@ -15,8 +15,8 @@ This module provides APIs for accessing resources of a specific Extension abilit | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| 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.)| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundle-HapModuleInfo.md) | Yes| No| Information about the HAP file
(See **api\bundle\hapModuleInfo.d.ts** in the **SDK** directory.) | +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| Module configuration information.
(See **api\@ohos.app.ability.Configuration.d.ts** in the **SDK** directory.)| | extensionAbilityInfo | [ExtensionAbilityInfo](js-apis-bundleManager-extensionAbilityInfo.md) | Yes| No| Extension ability information.
(See **api\bundle\extensionAbilityInfo.d.ts** in the **SDK** directory.)| ## When to Use @@ -30,7 +30,7 @@ To adapt to devices with different performance, an application provides three mo **Example** Define a **ServiceExtension** with the same name for the three modules. -``` js +```ts import ServiceExtension from '@ohos.app.ability.ServiceExtensionAbility' import Want from '@ohos.application.Want' export default class TheServiceExtension extends ServiceExtension { @@ -60,11 +60,12 @@ export default class TheServiceExtension extends ServiceExtension { ``` Start **ServiceExtension** within the **onCreate** callback of the main ability of the entry. -``` js -import Ability from '@ohos.app.ability.Ability' -export default class MainAbility extends Ability { +```ts +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { - console.log("[Demo] MainAbility onCreate"); + console.log("[Demo] EntryAbility onCreate"); let wantExt = { deviceId: "", bundleName: "com.example.TheServiceExtension", @@ -76,7 +77,7 @@ export default class MainAbility extends Ability { ``` Create a **ServiceModule.ts** file in the entry to execute service logic. -``` js +```ts export default class ServiceModel { moduleName: string; diff --git a/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..9485de9efd0dc76d78a905725fb742225b50340f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-extensionRunningInfo.md @@ -0,0 +1,53 @@ +# ExtensionRunningInfo + +The **ExtensionRunningInfo** module encapsulates ExtensionAbility running information, which can be obtained through [getExtensionRunningInfos](js-apis-app-ability-abilityManager.md#getextensionrunninginfos). + +> **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. +> - This module is marked as @systemapi and not visible to third-party applications. + +## Usage + +Import the **abilityManager** module and obtain the ExtensionAbility running information by calling the method in the **abilityManager** module. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| extension | [ElementName](js-apis-bundleManager-elementName.md) | Yes| No| ExtensionAbility information.| +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| UID of the application.| +| processName | string | Yes| No| Process name.| +| startTime | number | Yes| No| Timestamp when the ExtensionAbility is started.| +| clientPackage | Array<String> | Yes| No| Names of all packages in the process.| +| type | [ExtensionAbilityType](js-apis-bundleManager.md#extensionabilitytype) | Yes| No| ExtensionAbility type.| + +**Example** +```ts +import abilityManager from '@ohos.app.ability.abilityManager' + +var upperLimit = 1; +function getExtensionInfos() { + abilityManager.getExtensionRunningInfos(upperLimit, (error, data) => { + if (error && error.code) { + console.log('getForegroundApplications failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + + for (let i = 0; i < data.length; i++) { + let extensionRunningInfo = data[i]; + console.log("extensionRunningInfo.extension: " + JSON.stringify(extensionRunningInfo.extension)); + console.log("extensionRunningInfo.pid: " + JSON.stringify(extensionRunningInfo.pid)); + console.log("extensionRunningInfo.uid: " + JSON.stringify(extensionRunningInfo.uid)); + console.log("extensionRunningInfo.processName: " + JSON.stringify(extensionRunningInfo.processName)); + console.log("extensionRunningInfo.startTime: " + JSON.stringify(extensionRunningInfo.startTime)); + console.log("extensionRunningInfo.clientPackage: " + JSON.stringify(extensionRunningInfo.clientPackage)); + console.log("extensionRunningInfo.type: " + JSON.stringify(extensionRunningInfo.type)); + } + }); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md new file mode 100644 index 0000000000000000000000000000000000000000..d888ccdc51bef996937e9d2e6ef891980ffe457c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-formExtensionContext.md @@ -0,0 +1,125 @@ +# FormExtensionContext + +The **FormExtensionContext** module, inherited from **ExtensionContext**, provides context for FormExtensionAbilities. + +You can use the APIs of this module to start FormExtensionAbilities. + +> **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. + +## Usage + +Before using the **ServiceExtensionContext** module, you must first obtain a **FormExtensionAbility** instance. + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; +import formBindingData from '@ohos.app.form.formBindingData'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onAddForm(want) { + let formContext = this.context; // Obtain a FormExtensionContext instance. + // ... + let dataObj1 = { + temperature: "11c", + "time": "11:00" + }; + let obj1 = formBindingData.createFormBindingData(dataObj1); + return obj1; + } +}; +``` + +## startAbility + +startAbility(want: Want, callback: AsyncCallback<void>): void + +Starts an ability. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------| --------------------------------- | ---- | -------------------------------------- | +| want| [Want](js-apis-application-want.md) | Yes | Information about the ability to start, such as the bundle name, ability name, and custom parameters.| +| callback| AsyncCallback<void> | Yes | Callback used to return the result. If the ability is started, **err** is undefined; otherwise, **err** is an error object.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onFormEvent(formId, message) { + // Call startAbility() when the message event is triggered. + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "EntryAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want, (error, data) => { + if (error) { + console.log('FormExtensionContext startAbility, error:' + JSON.stringify(error)); + } else { + console.log('FormExtensionContext startAbility success'); + } + }); + } +}; +``` + +## startAbility + +startAbility(want: Want): Promise<void> + +Starts an ability. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Ability.Form + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------| --------------------------------- | ---- | -------------------------------------- | +| want| [Want](js-apis-application-want.md) | Yes | Information about the ability to start, such as the bundle name, ability name, and custom parameters.| + +**Return value** + +| Type | Description | +| ------------ | ---------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```ts +import FormExtensionAbility from '@ohos.app.form.FormExtensionAbility'; + +export default class MyFormExtensionAbility extends FormExtensionAbility { + onFormEvent(formId, message) { + // Call startAbility() when the message event is triggered. + console.log('FormExtensionAbility onFormEvent, formId:' + formId + ", message:" + message); + let want = { + deviceId: "", + bundleName: "com.example.formstartability", + abilityName: "EntryAbility", + parameters: { + "message": message + } + }; + this.context.startAbility(want).then(() => { + console.info("StartAbility Success"); + }).catch((error) => { + console.info("StartAbility failed"); + }); + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md new file mode 100644 index 0000000000000000000000000000000000000000..7ccae03fa363d0850338d07f1318a377f10fc293 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionCallbacks.md @@ -0,0 +1,34 @@ +# MissionCallback + +The **MissionCallback** module defines the callbacks invoked after synchronization starts. These callbacks can be used as input parameters in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Template | Readable| Writable| Description | +| ---------------------------------------------------- | -------- | ---- | ---- | ---------------------------------- | +| notifyMissionsChanged(deviceId: string) | function | Yes | No | Callback used to notify the mission change event and return the device ID. | +| notifySnapshot(deviceId: string, mission: number) | function | Yes | No | Callback used to notify the snapshot change event and return the device ID and mission ID. | +| notifyNetDisconnect(deviceId: string, state: number) | function | Yes | No | Callback used to notify the disconnection event and return the device ID and network status.| + +**Example** +```ts +import distributedMissionManager from '@ohos.distributedMissionManager'; + +let missionDeviceInfo = { + deviceId: "123456" +}; +let missionCallback = { + notifyMissionsChanged: function (deviceId) { + console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + }, + notifySnapshot: function (deviceId, mission) { + console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + console.log("notifySnapshot mission: " + JSON.stringify(mission)); + }, + notifyNetDisconnect: function (deviceId, state) { + console.log("notifyNetDisconnect deviceId: " + JSON.stringify(deviceId)); + console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + } +}; +distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..9157fc697346087895870a5bbd6e4a0368d6bde7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionDeviceInfo.md @@ -0,0 +1,32 @@ +# MissionDeviceInfo + +The **MissionDeviceInfo** module defines the parameters required for registering a listener. It can be used as an input parameter in [registerMissionListener](js-apis-distributedMissionManager.md#distributedmissionmanagerregistermissionlistener). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| -------- | ------ | ---- | ---- | ------- | +| deviceId | string | Yes | Yes | Device ID.| + +**Example** +```ts +import distributedMissionManager from '@ohos.distributedMissionManager'; + +let missionDeviceInfo = { + deviceId: "123456" +}; +let missionCallback = { + notifyMissionsChanged: function (deviceId) { + console.log("notifyMissionsChanged deviceId: " + JSON.stringify(deviceId)); + }, + notifySnapshot: function (mission, deviceId) { + console.log("notifySnapshot mission: " + JSON.stringify(mission)); + console.log("notifySnapshot deviceId: " + JSON.stringify(deviceId)); + }, + notifyNetDisconnect: function (mission, state) { + console.log("notifyNetDisconnect mission: " + JSON.stringify(mission)); + console.log("notifyNetDisconnect state: " + JSON.stringify(state)); + } +}; +distributedMissionManager.registerMissionListener(missionDeviceInfo, missionCallback); +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..afefb70c5a3e0b0059e4712992c3f736516bc2f7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionInfo.md @@ -0,0 +1,45 @@ +# MissionInfo + +The **MissionInfo** module defines detailed information about a mission. The information can be obtained through [getMissionInfo](js-apis-app-ability-missionManager.md#missionmanagergetmissioninfo). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| missionId | number | Yes| Yes| Mission ID.| +| runningState | number | Yes| Yes| Running state of the mission.| +| lockedState | boolean | Yes| Yes| Locked state of the mission.| +| timestamp | string | Yes| Yes| Latest time when the mission was created or updated.| +| want | [Want](js-apis-application-want.md) | Yes| Yes| Want information of the mission.| +| label | string | Yes| Yes| Label of the mission.| +| iconPath | string | Yes| Yes| Path of the mission icon.| +| continuable | boolean | Yes| Yes| Whether the mission can be continued on another device.| + +**Example** +```ts +import missionManager from '@ohos.app.ability.missionManager' + +try { + missionManager.getMissionInfo("", 1, (error, data) => { + if (error.code) { + // Process service logic errors. + console.log("getMissionInfo failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + + console.log('getMissionInfo missionId is:' + JSON.stringify(data.missionId)); + console.log('getMissionInfo runningState is:' + JSON.stringify(data.runningState)); + console.log('getMissionInfo lockedState is:' + JSON.stringify(data.lockedState)); + console.log('getMissionInfo timestamp is:' + JSON.stringify(data.timestamp)); + console.log('getMissionInfo want is:' + JSON.stringify(data.want)); + console.log('getMissionInfo label is:' + JSON.stringify(data.label)); + console.log('getMissionInfo iconPath is:' + JSON.stringify(data.iconPath)); + console.log('getMissionInfo continuable is:' + JSON.stringify(data.continuable)); + }); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md new file mode 100644 index 0000000000000000000000000000000000000000..a9f9e6cf9540c02ada58ea7e89f76b9c9c297efb --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionListener.md @@ -0,0 +1,47 @@ +# MissionListener + +The **MissionListener** module defines the listeners used to observe the mission status. The listeners can be registered by using [on](js-apis-app-ability-missionManager.md#missionmanageron). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Mandatory| Description | +| ----------- | -------- | ---- | ------------------------------------------------------------ | +| onMissionCreated | function | No | Called when the system creates a mission. | +| onMissionDestroyed | function | No | Called when the system destroys the mission.| +| onMissionSnapshotChanged | function | No | Called when the system updates the mission snapshot.| +| onMissionMovedToFront | function | No | Called when the system moves the mission to the foreground.| +| onMissionLabelUpdated | function | No | Called when the system updates the mission label.| +| onMissionIconUpdated | function | No | Called when the system updates the mission icon.| +| onMissionClosed | function | No | Called when the system closes the mission.| + +**Example** +```ts +import missionManager from '@ohos.app.ability.missionManager' + +let listener = { + onMissionCreated: function (mission) { + console.log("onMissionCreated mission: " + JSON.stringify(mission)); + }, + onMissionDestroyed: function (mission) { + console.log("onMissionDestroyed mission: " + JSON.stringify(mission)); + }, + onMissionSnapshotChanged: function (mission) { + console.log("onMissionSnapshotChanged mission: " + JSON.stringify(mission)); + }, + onMissionMovedToFront: function (mission) { + console.log("onMissionMovedToFront mission: " + JSON.stringify(mission)); + }, + onMissionIconUpdated: function (mission, icon) { + console.log("onMissionIconUpdated mission: " + JSON.stringify(mission)); + }, + onMissionClosed: function (mission) { + console.log("onMissionClosed mission: " + JSON.stringify(mission)); + } +}; + +try { + let listenerId = missionManager.on("mission", listener); +} catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md new file mode 100644 index 0000000000000000000000000000000000000000..9e2e2aa23a6589c0eb80075f8de60f65261e6903 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionParameter.md @@ -0,0 +1,31 @@ +# MissionParameter + +The **MissionParameter** module defines the parameters required for mission synchronization. It can be used an input parameter in [startSyncRemoteMissions](js-apis-distributedMissionManager.md#distributedmissionmanagerstartsyncremotemissions). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name | Type | Readable | Writable | Description | +| ----------- | ------- | ---- | ---- | ----------- | +| deviceId | string | Yes | Yes | Device ID. | +| fixConflict | boolean | Yes | Yes | Whether a version conflict occurs.| +| tag | number | Yes | Yes | Tag of the mission. | + +**Example** +```ts +import distributedMissionManager from '@ohos.distributedMissionManager'; + +let missionParameter = { + deviceId: "123456", + fixConflict: true, + tag: 123 +}; +try { + distributedMissionManager.startSyncRemoteMissions(missionParameter, + (err, data) => { + console.log("startSyncRemoteMissions, data: " + JSON.stringify(data)); + } + ); +} catch (err) { + console.error('startSyncRemoteMissions fail: ' + JSON.stringify(err)); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md new file mode 100644 index 0000000000000000000000000000000000000000..a97f3b32b71f90078cb03f32fa46262f5cf6b770 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-missionSnapshot.md @@ -0,0 +1,52 @@ +# MissionSnapshot + +The **MissionSnapshot** module defines the snapshot of a mission. The snapshot can be obtained through [getMissionSnapShot](js-apis-app-ability-missionManager.md#missionmanagergetmissionsnapshot). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are system APIs and cannot be called by third-party applications. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ability | ElementName | Yes| Yes| Ability information of the mission.| +| snapshot | [image.PixelMap](js-apis-image.md) | Yes| Yes| Snapshot of the mission.| + +## How to Use + +The mission snapshot information can be obtained by using **getMissionSnapShot** in **missionManager**. + +**Example** +```ts + import ElementName from '@ohos.bundle'; + import image from '@ohos.multimedia.image'; + import missionManager from '@ohos.app.ability.missionManager'; + + try { + missionManager.getMissionInfos("", 10, (error, missions) => { + if (error.code) { + console.log("getMissionInfos failed, error.code:" + JSON.stringify(error.code) + + "error.message:" + JSON.stringify(error.message)); + return; + } + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; + + missionManager.getMissionSnapShot("", id, (err, snapshot) => { + if (err.code) { + console.log("getMissionInfos failed, err.code:" + JSON.stringify(err.code) + + "err.message:" + JSON.stringify(err.message)); + return; + } + + // Carry out normal service processing. + console.log("bundleName = " + snapshot.ability.bundleName); + }) + }) + } catch (paramError) { + console.log("error: " + paramError.code + ", " + paramError.message); + } +``` diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processData.md b/en/application-dev/reference/apis/js-apis-inner-application-processData.md new file mode 100644 index 0000000000000000000000000000000000000000..c6e91944c5ed16800f3a2a7785de5a5e60dc623a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-processData.md @@ -0,0 +1,44 @@ +# ProcessData + +The **ProcessData** module defines process data. If a lifecycle change listener is registered by calling [registerApplicationStateObserver](js-apis-application-appManager.md#appmanagerregisterapplicationstateobserver8), the **onProcessCreated** callback in [ApplicationStateObserver](js-apis-inner-application-applicationStateObserver.md) is invoked when the lifecycle of an application or ability changes. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| pid8+ | number | Yes | No | Process ID. | +| bundleName8+ | string | Yes | No | Bundle name of the application. | +| uid8+ | number | Yes | No | UID of the application. | +| isContinuousTask9+ | boolean | Yes | No | Whether the task is a continuous task. The value **true** means that the task is a continuous task, and **false** means the opposite. | +| isKeepAlive9+ | boolean | Yes | No | Whether the process is a resident task. The value **true** means that the process is a resident, and **false** means the opposite. | +| state9+ | number | Yes | No | Application state. The value can be **0** (newly created), **2** (foreground), **4** (background), or **5** (terminated). | + +**Example** +```ts +import appManager from '@ohos.application.appManager' + +let applicationStateObserver = { + onForegroundApplicationChanged(appStateData) { + console.log('onForegroundApplicationChanged appStateData: ' + JSON.stringify(appStateData)); + }, + onAbilityStateChanged(abilityStateData) { + console.log('onAbilityStateChanged onAbilityStateChanged: ' + JSON.stringify(abilityStateData)); + }, + onProcessCreated(processData) { + console.log('onProcessCreated onProcessCreated: ' + JSON.stringify(processData)); + }, + onProcessDied(processData) { + console.log('onProcessDied onProcessDied: ' + JSON.stringify(processData)); + }, + onProcessStateChanged(processData) { + console.log('onProcessStateChanged processData.pid : ' + JSON.stringify(processData.pid)); + console.log('onProcessStateChanged processData.bundleName : ' + JSON.stringify(processData.bundleName)); + console.log('onProcessStateChanged processData.uid : ' + JSON.stringify(processData.uid)); + console.log('onProcessStateChanged processData.isContinuousTask : ' + JSON.stringify(processData.isContinuousTask)); + console.log('onProcessStateChanged processData.isKeepAlive : ' + JSON.stringify(processData.isKeepAlive)); + } +} +let observerCode = appManager.registerApplicationStateObserver(applicationStateObserver); +``` diff --git a/en/application-dev/reference/apis/js-apis-processrunninginfo.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md similarity index 50% rename from en/application-dev/reference/apis/js-apis-processrunninginfo.md rename to en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md index dfed42e70b0c506124341952c1fa5c8b724299c1..0652791f728de12c144459146287ecbbb680480e 100644 --- a/en/application-dev/reference/apis/js-apis-processrunninginfo.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInfo.md @@ -1,31 +1,33 @@ -# ProcessRunningInfo(deprecated) +# ProcessRunningInfo -The **ProcessRunningInfo** module provides process running information. +The **ProcessRunningInfo** module defines the running information of a process. > **NOTE** -> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-processrunninginformation.md) instead. +> - The APIs provided by this module are deprecated since API version 9. You are advised to use [ProcessRunningInformation9+](js-apis-inner-application-processRunningInformation.md) instead. > - The initial APIs of this module are supported since API version 8. +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Mission + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| bundleNames | Array<string> | Yes| No| Names of all running bundles in the process.| + ## Usage -The process running information is obtained by using [getProcessRunningInfos](js-apis-appmanager.md#appmanagergetprocessrunninginfosdeprecated) in **appManager**. +The process running information is obtained by using [getProcessRunningInfos](js-apis-application-appManager.md#appmanagergetprocessrunninginfosdeprecated) in **appManager**. -```js +**Example** +```ts import appManager from '@ohos.application.appManager'; -app.getProcessRunningInfos().then((data) => { + +appManager.getProcessRunningInfos().then((data) => { console.log('success:' + JSON.stringify(data)); }).catch((error) => { console.log('failed:' + JSON.stringify(error)); }); ``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Mission - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| bundleNames | Array<string> | Yes| No| Names of all bundles running in the process.| diff --git a/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md new file mode 100644 index 0000000000000000000000000000000000000000..a376446b2af90c8cc13f6eee80a10a5399dae041 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-processRunningInformation.md @@ -0,0 +1,30 @@ +# ProcessRunningInformation + +The **ProcessRunningInformation** module defines the running information of a process. + +> **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. + +## How to Use + +The process running information is obtained through [getProcessRunningInformation](js-apis-application-appManager.md#appmanagergetprocessrunninginformation9) in **appManager**. + +```ts +import appManager from '@ohos.application.appManager'; + +appManager.getProcessRunningInformation((error, data) => { + console.log("error: " + error.code + " data: " + JSON.stringify(data)); +}); +``` + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| pid | number | Yes| No| Process ID.| +| uid | number | Yes| No| User ID.| +| processName | string | Yes| No| Process name.| +| bundleNames | Array<string> | Yes| No| Names of all running bundles in the process.| diff --git a/en/application-dev/reference/apis/js-apis-service-extension-context.md b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md similarity index 58% rename from en/application-dev/reference/apis/js-apis-service-extension-context.md rename to en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md index e2af193a5c0e62c9c5081589243d0615669a51d5..ae6beb1357d9d25dfcd06cbcd1d65df660fa44bb 100644 --- a/en/application-dev/reference/apis/js-apis-service-extension-context.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-serviceExtensionContext.md @@ -1,6 +1,6 @@ # ServiceExtensionContext -The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for Service Extension abilities. +The **ServiceExtensionContext** module, inherited from **ExtensionContext**, provides context for ServiceExtensionAbilities. You can use the APIs of this module to start, terminate, connect, and disconnect abilities. @@ -17,9 +17,9 @@ Before using the **ServiceExtensionContext** module, you must define a child cla import ServiceExtensionAbility from '@ohos.app.ability.ServiceExtensionAbility'; let context = undefined; - class MainAbility extends ServiceExtensionAbility { + class EntryAbility extends ServiceExtensionAbility { onCreate() { - context = this.context; + context = this.context; // Obtain a ServiceExtensionContext instance. } } ``` @@ -36,17 +36,34 @@ Starts an ability. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -86,23 +103,40 @@ Starts an ability. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -147,24 +181,41 @@ Starts an ability with the start options specified. This API uses an asynchronou | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| | callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var options = { windowMode: 0 @@ -194,6 +245,11 @@ startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\< Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -202,7 +258,7 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -210,16 +266,34 @@ Starts an ability with the account ID specified. This API uses an asynchronous c | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -247,6 +321,11 @@ startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, ca Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -255,25 +334,43 @@ Starts an ability with the account ID and start options specified. This API uses | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -305,6 +402,11 @@ startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Starts an ability with the account ID specified. This API uses a promise to return the result. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -313,30 +415,48 @@ Starts an ability with the account ID specified. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -365,7 +485,7 @@ Starts an ability with the account ID specified. This API uses a promise to retu startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Starts a new Service Extension ability. This API uses an asynchronous callback to return the result. +Starts a new ServiceExtensionAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -375,23 +495,33 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -416,7 +546,7 @@ Starts a new Service Extension ability. This API uses an asynchronous callback t startServiceExtensionAbility(want: Want): Promise\; -Starts a new Service Extension ability. This API uses a promise to return the result. +Starts a new ServiceExtensionAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -426,28 +556,38 @@ Starts a new Service Extension ability. This API uses a promise to return the re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -472,9 +612,9 @@ Starts a new Service Extension ability. This API uses a promise to return the re startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Starts a new Service Extension ability with the account ID specified. This API uses an asynchronous callback to return the result. +Starts a new ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -484,7 +624,7 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -492,8 +632,19 @@ Starts a new Service Extension ability with the account ID specified. This API u | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** @@ -501,8 +652,8 @@ Starts a new Service Extension ability with the account ID specified. This API u ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -528,9 +679,9 @@ Starts a new Service Extension ability with the account ID specified. This API u startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Starts a new Service Extension ability with the account ID specified. This API uses a promise to return the result. +Starts a new ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -540,29 +691,40 @@ Starts a new Service Extension ability with the account ID specified. This API u | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -588,7 +750,7 @@ Starts a new Service Extension ability with the account ID specified. This API u stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -598,23 +760,30 @@ Stops a Service Extension ability in the same application. This API uses an asyn | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | callback | AsyncCallback\ | Yes| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -639,7 +808,7 @@ Stops a Service Extension ability in the same application. This API uses an asyn stopServiceExtensionAbility(want: Want): Promise\; -Stops a Service Extension ability in the same application. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -649,28 +818,35 @@ Stops a Service Extension ability in the same application. This API uses a promi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; try { @@ -695,9 +871,9 @@ Stops a Service Extension ability in the same application. This API uses a promi stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; -Stops a Service Extension ability in the same application with the account ID specified. This API uses an asynchronous callback to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -707,7 +883,7 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| | callback | AsyncCallback\ | Yes| Callback used to return the result.| @@ -715,16 +891,24 @@ Stops a Service Extension ability in the same application with the account ID sp | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -750,9 +934,9 @@ Stops a Service Extension ability in the same application with the account ID sp stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; -Stops a Service Extension ability in the same application with the account ID specified. This API uses a promise to return the result. +Stops a ServiceExtensionAbility in the same application with the account ID specified. This API uses a promise to return the result. -**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -762,29 +946,37 @@ Stops a Service Extension ability in the same application with the account ID sp | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; @@ -818,16 +1010,20 @@ Terminates this ability. This API uses an asynchronous callback to return the re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -856,16 +1052,20 @@ Terminates this ability. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -884,7 +1084,7 @@ Terminates this ability. This API uses a promise to return the result. connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; -Connects this ability to a Service ability. +Connects this ability to a ServiceAbility. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -892,23 +1092,28 @@ Connects this ability to a Service ability. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| - | options | [ConnectOptions](js-apis-featureAbility.md#connectoptions) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability, such as the ability name and bundle name.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Callback used to return the information indicating that the connection is successful, interrupted, or failed.| **Return value** - | Type| Description| - | -------- | -------- | - | number | A number, based on which the connection will be interrupted.| +| Type| Description| +| -------- | -------- | +| number | A number, based on which the connection will be interrupted.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -947,9 +1152,9 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want information about the target ability.| +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| | accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getosaccountlocalidfromprocess).| -| options | ConnectOptions | Yes| Remote object instance.| +| options | ConnectOptions | No| Remote object instance.| **Return value** @@ -961,16 +1166,22 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** ```ts var want = { deviceId: "", - bundleName: "com.extreme.test", - abilityName: "MainAbility" + bundleName: "com.example.myapplication", + abilityName: "EntryAbility" }; var accountId = 100; var options = { @@ -993,7 +1204,7 @@ Uses the **AbilityInfo.AbilityType.SERVICE** template and account ID to connect disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback<void>): void; -Disconnects this ability from the Service ability. This API uses an asynchronous callback to return the result. +Disconnects this ability from the ServiceAbility. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1001,17 +1212,21 @@ Disconnects this ability from the Service ability. This API uses an asynchronous **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | connection | number | Yes| Number returned after **connectAbility** is called.| - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Number returned after **connectAbility** is called.| +| callback | AsyncCallback<void> | No| Callback used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -1041,7 +1256,7 @@ Disconnects this ability from the Service ability. This API uses an asynchronous disconnectServiceExtensionAbility(connection: number): Promise<void>; -Disconnects this ability from the Service ability. This API uses a promise to return the result. +Disconnects this ability from the ServiceAbility. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core @@ -1049,22 +1264,26 @@ Disconnects this ability from the Service ability. This API uses a promise to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | connection | number | Yes| Number returned after **connectAbility** is called.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Number returned after **connectAbility** is called.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Error codes** | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | **Example** @@ -1096,6 +1315,11 @@ startAbilityByCall(want: Want): Promise<Caller>; Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + **System capability**: SystemCapability.Ability.AbilityRuntime.Core **System API**: This is a system API and cannot be called by third-party applications. @@ -1104,7 +1328,7 @@ Starts an ability in the foreground or background and obtains the caller object | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| +| want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| **Return value** @@ -1116,8 +1340,15 @@ Starts an ability in the foreground or background and obtains the caller object | ID| Error Message| | ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | | 401 | Invalid input parameter. | -| Other IDs| See [Ability Error Codes](../errorcodes/errorcode-ability.md).| +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000050 | Internal Error. | **Example** @@ -1130,7 +1361,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantBackground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "" }; @@ -1161,7 +1392,7 @@ Starts an ability in the foreground or background and obtains the caller object var wantForeground = { bundleName: "com.example.myservice", moduleName: "entry", - abilityName: "MainAbility", + abilityName: "EntryAbility", deviceId: "", parameters: { "ohos.aafwk.param.callAbilityToForeground": true @@ -1185,4 +1416,3 @@ Starts an ability in the foreground or background and obtains the caller object ' error.message: ' + JSON.stringify(paramError.message)); } ``` - diff --git a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md similarity index 69% rename from en/application-dev/reference/apis/js-apis-application-shellCmdResult.md rename to en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md index 7f9e03d201873f689838a4a53c7519ec566b990d..51b10659d38d55686ced548c624798d77391f102 100644 --- a/en/application-dev/reference/apis/js-apis-application-shellCmdResult.md +++ b/en/application-dev/reference/apis/js-apis-inner-application-shellCmdResult.md @@ -6,29 +6,26 @@ The **ShellCmdResult** module provides the shell command execution result. > > 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. +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | ------------------------------------------------------------ | +| stdResult | string | Yes | Yes | Standard output content.| +| exitCode | number | Yes | Yes | Result code.| + ## Usage -The result is obtained by calling [executeShellCommand](js-apis-application-abilityDelegator.md#executeshellcommand) in **abilityDelegator**. +The result is obtained by calling [executeShellCommand](js-apis-inner-application-abilityDelegator.md#executeshellcommand) in **abilityDelegator**. -```js +**Example** +```ts import AbilityDelegatorRegistry from "@ohos.application.abilityDelegatorRegistry"; let abilityDelegator; let cmd = "cmd"; abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); abilityDelegator.executeShellCommand(cmd, (err: any, data: any) => { - console.info("executeShellCommand callback, failed: ", err); - console.info("executeShellCommand callback, success: ", data); + console.info("executeShellCommand callback, result: ", err); + console.info("executeShellCommand callback, data: ", data); }); ``` - -## ShellCmdResult - -Describes the shell command execution result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Type | Readable| Writable| Description | -| --------- | ------ | ---- | ---- | ------------------------------------------------------------ | -| stdResult | string | Yes | Yes | Standard output content. | -| exitCode | number | Yes | Yes | Result code. | diff --git a/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md new file mode 100644 index 0000000000000000000000000000000000000000..f8528cc1bf6c8b4468c5c475934fe1c91c70490a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-application-uiAbilityContext.md @@ -0,0 +1,2190 @@ +# UIAbilityContext + +**UIAbilityContext**, inherited from [Context](js-apis-inner-application-context.md), provides the context environment for [UIAbility](js-apis-app-ability-uiAbility.md). **UIAbilityContext** provides UIAbility-related configuration and APIs for operating UIAbilities and ServiceExtensionAbilities. For example, you can use the APIs to start a UIAbility, terminate a UIAbility to which the UIAbilityContext belongs, and start, terminate, connect to, or disconnect from a ServiceExtensionAbility. + +> **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. + +## Attributes + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| abilityInfo | [AbilityInfo](js-apis-bundleManager-abilityInfo.md) | Yes| No| UIAbility information.| +| currentHapModuleInfo | [HapModuleInfo](js-apis-bundleManager-hapModuleInfo.md) | Yes| No| HAP information.| +| config | [Configuration](js-apis-app-ability-configuration.md) | Yes| No| UIAbility configuration, such as the language and color mode.| + +> **NOTE** +> - In the sample code provided in this topic, **this.context** is used to obtain **UIAbilityContext**, where **this** indicates a UIAbility instance inherited from **UIAbility**. To use **UIAbilityContext** capabilities on pages, see [Obtaining the Context of UIAbility](../../application-models/uiability-usage.md#obtaining-the-context-of-uiability). + +## UIAbilityContext.startAbility + +startAbility(want: Want, callback: AsyncCallback<void>): void; + +Starts an ability. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + + try { + this.context.startAbility(want, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startAbility + +startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void; + +Starts an ability with the start options specified. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbility(want, options, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startAbility + +startAbility(want: Want, options?: StartOptions): Promise<void>; + +Starts an ability. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapp", + abilityName: "MyAbility" + }; + var options = { + windowMode: 0, + }; + + try { + this.context.startAbility(want, options) + .then(() => { + // Carry out normal service processing. + console.log('startAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startAbilityForResult + +startAbilityForResult(want: Want, callback: AsyncCallback<AbilityResult>): void; + +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + + try { + this.context.startAbilityForResult(want, (error, result) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode) + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startAbilityForResult + +startAbilityForResult(want: Want, options: StartOptions, callback: AsyncCallback<AbilityResult>): void; + +Starts an ability with the start options specified. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want |[Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var options = { + windowMode: 0, + }; + + try { + this.context.startAbilityForResult(want, options, (error, result) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode) + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## UIAbilityContext.startAbilityForResult + +startAbilityForResult(want: Want, options?: StartOptions): Promise<AbilityResult>; + +Starts an ability. After the ability is started, you can call [terminateSelfWithResult](#uiabilitycontextterminateselfwithresult) to terminate the ability and return the result to the caller. If an exception occurs, for example, the ability is killed, exception information is returned to the caller. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var options = { + windowMode: 0, + }; + + try { + this.context.startAbilityForResult(want, options) + .then((result) => { + // Carry out normal service processing. + console.log("startAbilityForResult succeed, result.resultCode = " + result.resultCode); + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityForResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| callback | AsyncCallback<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, (error, result) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode + ' result.want = ' + JSON.stringify(result.want)) + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## UIAbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; + +Starts an ability with the start options and account ID specified. This API uses an asynchronous callback to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback invoked when the ability is terminated.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log("startAbilityForResultWithAccount succeed") + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## UIAbilityContext.startAbilityForResultWithAccount + +startAbilityForResultWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; + +Starts an ability with the account ID specified. This API uses a promise to return the result when the ability is terminated. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[AbilityResult](js-apis-inner-ability-abilityResult.md)> | Promise used to return the ability result when the ability is terminated.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityForResultWithAccount(want, accountId, options) + .then((result) => { + // Carry out normal service processing. + console.log("startAbilityForResultWithAccount succeed, result.resultCode = " + + result.resultCode) + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityForResultWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` +## UIAbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Starts a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + + try { + this.context.startServiceExtensionAbility(want, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startServiceExtensionAbility + +startServiceExtensionAbility(want: Want): Promise\; + +Starts a ServiceExtensionAbility. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + + try { + this.context.startServiceExtensionAbility(want) + .then(() => { + // Carry out normal service processing. + console.log('startServiceExtensionAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts a ServiceExtensionAbility with the account ID specified. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + var accountId = 100; + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startServiceExtensionAbilityWithAccount + +startServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Starts a ServiceExtensionAbility with the account ID specified. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + var accountId = 100; + + try { + this.context.startServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // Carry out normal service processing. + console.log('startServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` +## UIAbilityContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want, callback: AsyncCallback\): void; + +Stops a ServiceExtensionAbility in the same application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + + try { + this.context.stopServiceExtensionAbility(want, (error) => { + if (error.code) { + // Process service logic errors. + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('stopServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.stopServiceExtensionAbility + +stopServiceExtensionAbility(want: Want): Promise\; + +Stops a ServiceExtensionAbility in the same application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + + try { + this.context.stopServiceExtensionAbility(want) + .then((data) => { + // Carry out normal service processing. + console.log('stopServiceExtensionAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('stopServiceExtensionAbility failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + var accountId = 100; + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // Process service logic errors. + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.stopServiceExtensionAbilityWithAccount + +stopServiceExtensionAbilityWithAccount(want: Want, accountId: number): Promise\; + +Stops a ServiceExtensionAbility with the account ID specified in the same application. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ServiceExtensionAbility.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + var accountId = 100; + + try { + this.context.stopServiceExtensionAbilityWithAccount(want, accountId) + .then((data) => { + // Carry out normal service processing. + console.log('stopServiceExtensionAbilityWithAccount succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('stopServiceExtensionAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.terminateSelf + +terminateSelf(callback: AsyncCallback<void>): void; + +Terminates this ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + try { + this.context.terminateSelf((error) => { + if (error.code) { + // Process service logic errors. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('terminateSelf succeed'); + }); + } catch (error) { + // Capture the synchronization parameter error. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + ``` + + +## UIAbilityContext.terminateSelf + +terminateSelf(): Promise<void>; + +Terminates this ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + try { + this.context.terminateSelf() + .then(() => { + // Carry out normal service processing. + console.log('terminateSelf succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (error) { + // Capture the synchronization parameter error. + console.log('terminateSelf failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + } + ``` + + +## UIAbilityContext.terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult, callback: AsyncCallback<void>): void; + +Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a callback when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + + try { + this.context.terminateSelfWithResult(abilityResult, (error) => { + if (error.code) { + // Process service logic errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('terminateSelfWithResult succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## UIAbilityContext.terminateSelfWithResult + +terminateSelfWithResult(parameter: AbilityResult): Promise<void>; + +Terminates this ability. If the ability is started by calling [startAbilityForResult](#uiabilitycontextstartabilityforresult), the result is returned to the caller in the form of a promise when **terminateSelfWithResult** is called. Otherwise, no result is returned to the caller when **terminateSelfWithResult** is called. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| parameter | [AbilityResult](js-apis-inner-ability-abilityResult.md) | Yes| Information returned to the caller.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + + +**Example** + + ```ts + var want = { + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + } + var resultCode = 100; + // AbilityResult information returned to the caller. + var abilityResult = { + want, + resultCode + } + + try { + this.context.terminateSelfWithResult(abilityResult) + .then((data) => { + // Carry out normal service processing. + console.log('terminateSelfWithResult succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('terminateSelfWithResult failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.connectServiceExtensionAbility + +connectServiceExtensionAbility(want: Want, options: ConnectOptions): number; + +Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information for connecting to the ServiceExtensionAbility.| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Result code of the ability connection.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + var options = { + onConnect(elementName, remote) { + console.log('----------- onConnect -----------') + }, + onDisconnect(elementName) { + console.log('----------- onDisconnect -----------') + }, + onFailed(code) { + console.log('----------- onFailed -----------') + } + } + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbility(want, options); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## UIAbilityContext.connectServiceExtensionAbilityWithAccount + +connectServiceExtensionAbilityWithAccount(want: Want, accountId: number, options: ConnectOptions): number; + +Connects this ability to an ability that uses the **AbilityInfo.AbilityType.SERVICE** template, with the account ID specified. + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [ConnectOptions](js-apis-inner-ability-connectOptions.md) | Yes| Instance of the callback function after the connection to the ServiceExtensionAbility is set up.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Result code of the ability connection.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000002 | Ability type error. The specified ability type is wrong. | +| 16000004 | Visibility verification failed. | +| 16000006 | Can not cross user operations. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "ServiceExtensionAbility" + }; + var accountId = 100; + var options = { + onConnect(elementName, remote) { + console.log('----------- onConnect -----------') + }, + onDisconnect(elementName) { + console.log('----------- onDisconnect -----------') + }, + onFailed(code) { + console.log('----------- onFailed -----------') + } + } + + var connection = null; + try { + connection = this.context.connectServiceExtensionAbilityWithAccount(want, accountId, options); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.disconnectServiceExtensionAbility + +disconnectServiceExtensionAbility(connection: number): Promise\; + +Disconnects from a ServiceExtensionAbility. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + // connection is the return value of connectServiceExtensionAbility. + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection) + .then((data) => { + // Carry out normal service processing. + console.log('disconnectServiceExtensionAbility succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.disconnectServiceExtensionAbility + +disconnectServiceExtensionAbility(connection: number, callback:AsyncCallback\): void; + +Disconnects from a ServiceExtensionAbility. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| connection | number | Yes| Digital code of the connected ServiceExtensionAbility, that is, connectionId returned by **connectServiceExtensionAbility**.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000003 | Input error. The specified id does not exist. | +| 16000011 | Context does not exist. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + // connection is the return value of connectServiceExtensionAbility. + var connection = 1; + + try { + this.context.disconnectServiceExtensionAbility(connection, (error) => { + if (error.code) { + // Process service logic errors. + console.log('disconnectServiceExtensionAbility failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('disconnectServiceExtensionAbility succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startAbilityByCall + +startAbilityByCall(want: Want): Promise<Caller>; + +Starts an ability in the foreground or background and obtains the caller object for communicating with the ability. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - The rules for using this API in the same-device and cross-device scenarios are different. For details, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Information about the ability to start, including **abilityName**, **moduleName**, **bundleName**, **deviceId** (optional), and **parameters** (optional). If **deviceId** is left blank or null, the local ability is started. If **parameters** is left blank or null, the ability is started in the background.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<Caller> | Promise used to return the caller object to communicate with.| + +**Example** + + Start an ability in the background. + + ```ts + var caller = undefined; + + // Start an ability in the background by not passing parameters. + var wantBackground = { + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "" + }; + + try { + this.context.startAbilityByCall(wantBackground) + .then((obj) => { + // Carry out normal service processing. + caller = obj; + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // Process service logic errors. + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + Start an ability in the foreground. + + ```ts + var caller = undefined; + + // Start an ability in the foreground with ohos.aafwk.param.callAbilityToForeground in parameters set to true. + var wantForeground = { + bundleName: "com.example.myservice", + moduleName: "entry", + abilityName: "MainAbility", + deviceId: "", + parameters: { + "ohos.aafwk.param.callAbilityToForeground": true + } + }; + + try { + this.context.startAbilityByCall(wantForeground) + .then((obj) => { + // Carry out normal service processing. + caller = obj; + console.log('startAbilityByCall succeed'); + }).catch((error) => { + // Process service logic errors. + console.log('startAbilityByCall failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, callback: AsyncCallback\): void; + +Starts an ability with the account ID specified. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var accountId = 100; + + try { + this.context.startAbilityWithAccount(want, accountId, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## UIAbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options: StartOptions, callback: AsyncCallback\): void; + +Starts an ability with the account ID and start options specified. This API uses an asynchronous callback to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | Yes| Parameters used for starting the ability.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityWithAccount(want, accountId, options, (error) => { + if (error.code) { + // Process service logic errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + return; + } + // Carry out normal service processing. + console.log('startAbilityWithAccount succeed'); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + + +## UIAbilityContext.startAbilityWithAccount + +startAbilityWithAccount(want: Want, accountId: number, options?: StartOptions): Promise\; + +Starts an ability with the account ID specified. This API uses a promise to return the result. + +Observe the following when using this API: + - If an application running in the background needs to call this API to start an ability, it must have the **ohos.permission.START_ABILITIES_FROM_BACKGROUND** permission. + - If **visible** of the target ability is **false** in cross-application scenarios, the caller must have the **ohos.permission.START_INVISIBLE_ABILITY** permission. + - For details about the startup rules for the components in the stage model, see [Component Startup Rules (Stage Model)](../../application-models/component-startup-rules.md). + +**Required permissions**: ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS (required only when the account ID is not the current user) + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| want | [Want](js-apis-application-want.md) | Yes| Want information about the target ability.| +| accountId | number | Yes| ID of a system account. For details, see [getCreatedOsAccountsCount](js-apis-osAccount.md#getCreatedOsAccountsCount).| +| options | [StartOptions](js-apis-app-ability-startOptions.md) | No| Parameters used for starting the ability.| + +**Error codes** + +| ID| Error Message| +| ------- | -------------------------------- | +| 201 | The application does not have permission to call the interface. | +| 401 | Invalid input parameter. | +| 16000001 | Input error. The specified ability name does not exist. | +| 16000004 | Visibility verification failed. | +| 16000005 | Static permission denied. The specified process does not have the permission. | +| 16000006 | Can not cross user operations. | +| 16000007 | Service busyness. There are concurrent tasks, waiting for retry. | +| 16000008 | Crowdtest App Expiration. | +| 16000009 | Can not start ability in wukong mode. | +| 16000010 | Can not operation with continue flag. | +| 16000011 | Context does not exist. | +| 16000051 | Network error. The network is abnormal. | +| 16000052 | Free install not support. The application does not support freeinstall | +| 16000053 | Not top ability. The application is not top ability. | +| 16000054 | Free install busyness. There are concurrent tasks, waiting for retry. | +| 16000055 | Free install timeout. | +| 16000056 | Can not free install other ability. | +| 16000057 | Not support cross device free install. | +| 16200001 | Caller released. The caller has been released. | +| 16000050 | Internal Error. | + +**Example** + + ```ts + var want = { + deviceId: "", + bundleName: "com.example.myapplication", + abilityName: "MainAbility" + }; + var accountId = 100; + var options = { + windowMode: 0 + }; + + try { + this.context.startAbilityWithAccount(want, accountId, options) + .then((data) => { + // Carry out normal service processing. + console.log('startAbilityWithAccount succeed'); + }) + .catch((error) => { + // Process service logic errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(error.code) + + ' error.message: ' + JSON.stringify(error.message)); + }); + } catch (paramError) { + // Process input parameter errors. + console.log('startAbilityWithAccount failed, error.code: ' + JSON.stringify(paramError.code) + + ' error.message: ' + JSON.stringify(paramError.message)); + } + ``` + +## UIAbilityContext.setMissionLabel + +setMissionLabel(label: string, callback:AsyncCallback<void>): void; + +Sets a label for this ability in the mission. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| label | string | Yes| Label of the ability to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| + +**Example** + + ```ts + this.context.setMissionLabel("test", (result) => { + console.log('setMissionLabel:' + JSON.stringify(result)); + }); + ``` + +## UIAbilityContext.setMissionLabel + +setMissionLabel(label: string): Promise<void>; + +Sets a label for this ability in the mission. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| label | string | Yes| Label of the ability to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + this.context.setMissionLabel("test").then(() => { + console.log('success'); + }).catch((error) => { + console.log('failed:' + JSON.stringify(error)); + }); + ``` +## UIAbilityContext.setMissionIcon + +setMissionIcon(icon: image.PixelMap, callback:AsyncCallback\): void; + +Sets an icon for this ability in the mission. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | image.PixelMap | Yes| Icon of the ability to set.| +| callback | AsyncCallback\ | Yes| Callback used to return the result.| + +**Example** + + ```ts + import image from '@ohos.multimedia.image'; + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; + }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap, (err) => { + console.log('---------- setMissionIcon fail, err: -----------', err); + }) + ``` + + +## UIAbilityContext.setMissionIcon + +setMissionIcon(icon: image.PixelMap): Promise\; + +Sets an icon for this ability in the mission. This API uses a promise to return the result. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| icon | image.PixelMap | Yes| Icon of the ability to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| + +**Example** + + ```ts + var imagePixelMap; + var color = new ArrayBuffer(0); + var initializationOptions = { + size: { + height: 100, + width: 100 + } + }; + image.createPixelMap(color, initializationOptions) + .then((data) => { + imagePixelMap = data; + }) + .catch((err) => { + console.log('--------- createPixelMap fail, err: ---------', err) + }); + this.context.setMissionIcon(imagePixelMap) + .then(() => { + console.log('-------------- setMissionIcon success -------------'); + }) + .catch((err) => { + console.log('-------------- setMissionIcon fail, err: -------------', err); + }); + ``` +## UIAbilityContext.restoreWindowStage + +restoreWindowStage(localStorage: LocalStorage) : void; + +Restores the window stage data for this ability. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| localStorage | image.LocalStorage | Yes| Storage used to store the restored window stage.| + +**Example** + + ```ts + var storage = new LocalStorage(); + this.context.restoreWindowStage(storage); + ``` + +## UIAbilityContext.isTerminating + +isTerminating(): boolean; + +Checks whether this ability is in the terminating state. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean| The value **true** means that the ability is in the terminating state, and **false** means the opposite.| + +**Example** + + ```ts + var isTerminating = this.context.isTerminating(); + console.log('ability state :' + isTerminating); + ``` diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..5ca299f0ad5f9df4f5b460b30e9e34c7dad82d5d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-triggerInfo.md @@ -0,0 +1,12 @@ +# TriggerInfo + +The **TriggerInfo** module defines the information required for triggering the WantAgent. The information is used as an input parameter of [trigger](js-apis-app-ability-wantAgent.md#wantagenttrigger). + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory| Description | +| ---------- | --- |-------------------- | ----------- | +| code | number | Yes | Custom result code provided for the target WantAgent.| +| want | Want | No | Want. | +| permission | string | No | Permission. | +| extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..8facc43fc842570c3eb0ea95a141bdaa77dcf252 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md @@ -0,0 +1,13 @@ +# WantAgentInfo + +The **WantAgentInfo** module defines the information required for triggering a **WantAgent** object. The information can be used as an input parameter in [getWantAgent](js-apis-app-ability-wantAgent.md#wantagentgetwantagent) to obtain a specified **WantAgent** object. + +**System capability**: SystemCapability.Ability.AbilityRuntime.Core + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------- | ---- | ---------------------- | +| wants | Array\ | Yes | Array of all **Want** objects. | +| operationType | wantAgent.OperationType | Yes | Operation type. | +| requestCode | number | Yes | Request code defined by the user.| +| wantAgentFlags | Array<[wantAgent.WantAgentFlags](js-apis-app-ability-wantAgent.md#wantagentflags)> | No | Array of flags for using the **WantAgent** object. | +| extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md index 373fbf8faee9549ab17b5fbe462997f8cb3eaa30..4de59dd1322f1cc83203ad38bc63746c81d56e8a 100644 --- a/en/application-dev/reference/apis/js-apis-inputconsumer.md +++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md @@ -1,18 +1,16 @@ -# Input Consumer +# @ohos.multimodalInput.inputConsumer (Input Consumer) -The Input Consumer module implements listening for key events. +The **inputConsumer** module implements listening for combination key events. > **NOTE** -> > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> - The APIs of this module are system APIs and cannot be called by third-party applications. +> - The APIs provided by this module are system APIs. ## Modules to Import -``` +```js import inputConsumer from '@ohos.multimodalInput.inputConsumer'; ``` @@ -21,32 +19,29 @@ import inputConsumer from '@ohos.multimodalInput.inputConsumer'; on(type: "key", keyOptions: KeyOptions, callback: Callback<KeyOptions>): void -Enables listening for combination key events. When a combination key event that meets the specified conditions occurs, **keyOptions** will be passed as an input parameter to **callback**. - -This is a system API. +Enables listening for combination key events. This API uses an asynchronous callback to return the combination key data when a combination key event that meets the specified condition occurs. **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| -| keyOptions | [keyOptions](#keyoptions) | Yes| Key option, which specifies the condition for combination key input.| -| callback | Callback<KeyOptions> | Yes| Callback used to return the result.
When a key input event that meets the specified options occurs, **keyOptions** will be passed as an input parameter to **callback**.| +| Name | Type | Mandatory | Description | +| ---------- | -------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type. Currently, only **key** is supported. | +| keyOptions | [KeyOptions](#keyoptions) | Yes | Combination key options. | +| callback | Callback<KeyOptions> | Yes | Callback used to return the combination key data when a combination key event that meets the specified condition occurs.| **Example** -``` -let keyOptions = { preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0 } -let callback = function (keyOptions) { - console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, - "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) -} +```js +let leftAltKey = 2045; +let tabKey = 2049; try { - inputConsumer.on(inputConsumer.SubscribeType.KEY, keyOptions, callback); + inputConsumer.on("key", {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}, keyOptions => { + console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); + }); } catch (error) { - console.info(`inputConsumer.on, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`); + console.log(`Subscribe failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` @@ -55,49 +50,63 @@ try { off(type: "key", keyOptions: KeyOptions, callback?: Callback<KeyOptions>): void -Stops listening for combination key events. - -This is a system API. +Disables listening for combination key events. **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the key input event to listen for. Only **key** is supported.| -| keyOptions | [keyOptions](#keyoptions) | Yes| Key options passed to the key input event when listening starts.| -| callback | Callback<KeyOptions> | Yes| Callback function passed to the key input event with **keyOptions** when listening starts.| +| Name | Type | Mandatory | Description | +| ---------- | -------------------------- | ---- | ------------------------------- | +| type | string | Yes | Event type. Currently, only **key** is supported. | +| keyOptions | [KeyOptions](#keyoptions) | Yes | Combination key options. | +| callback | Callback<KeyOptions> | No | Callback for which listening is disabled. If this parameter is not specified, listening will be disabled for all callbacks registered by the current application.| **Example** +```js +let leftAltKey = 2045; +let tabKey = 2049; +// Disable listening for a single callback function. +let callback = function (keyOptions) { + console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); +} +let keyOption = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}; +try { + inputConsumer.on("key", keyOption, callback); + inputConsumer.off("key", keyOption, callback); + console.log(`Unsubscribe success`); +} catch (error) { + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` -let keyOptions = { preKeys: [], finalKey: 18, isFinalKeyDown: true, finalKeyDownDuration: 0 } +```js +let leftAltKey = 2045; +let tabKey = 2049; +// Disable listening for all callback functions. let callback = function (keyOptions) { - console.info("preKeys: " + keyOptions.preKeys, "finalKey: " + keyOptions.finalKey, - "isFinalKeyDown: " + keyOptions.isFinalKeyDown, "finalKeyDownDuration: " + keyOptions.finalKeyDownDuration) + console.log(`keyOptions: ${JSON.stringify(keyOptions)}`); } +let keyOption = {preKeys: [leftAltKey], finalKey: tabKey, isFinalKeyDown: true, finalKeyDownDuration: 0}; try { - inputConsumer.off(inputConsumer.SubscribeType.KEY, keyOptions, callback); + inputConsumer.on("key", keyOption, callback); + inputConsumer.off("key", keyOption); + console.log(`Unsubscribe success`); } catch (error) { - console.info(`inputConsumer.off, error.code=${JSON.stringify(error.code)}, error.msg=${JSON.stringify(error.message)}`); + console.log(`Execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` -## keyOptions +## KeyOptions -Defines the key options that are met when a combination key input event occurs. - -This is a system API. +Represents combination key options. **System capability**: SystemCapability.MultimodalInput.Input.InputConsumer -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| preKeys | Array | Yes| Array of precedent keys. This parameter can be left empty. There is no requirement on the sequence of precedent keys.| -| finalKey | Number | Yes| Final key in the combination key. This parameter cannot be left blank.| -| isFinalKeyDown | boolean | Yes| Whether the final key is pressed or released. By default, the final key is pressed.| -| finalKeyDownDuration | Number | Yes| Duration for pressing the final key. By default, there is no requirement on the duration.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| preKeys | Array | Yes | No| Front key set. The number of front keys ranges from 0 to 4. There is no requirement on the sequence of the keys.| +| finalKey | number | Yes | No| Final key. This parameter is mandatory. A callback function is triggered by the final key.| +| isFinalKeyDown | boolean | Yes | No| Whether the final key is pressed.| +| finalKeyDownDuration | number | Yes | No| Duration within which the final key is pressed. If the value is **0**, the callback function is triggered immediately. If the value is greater than **0** and the value of **isFinalKeyDown** is **true**, the callback function is triggered when the key press duration is longer than the value of this parameter. If the value of **isFinalKeyDown** is **false**, the callback function is triggered when the duration from key press to key release is less than the value of this parameter. | diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md index f5cf9b1af9502462bd906302bee23fcff28780b4..c131d9bbd3e50790624d4eca0ea41c94d7022dd2 100644 --- a/en/application-dev/reference/apis/js-apis-inputdevice.md +++ b/en/application-dev/reference/apis/js-apis-inputdevice.md @@ -1,17 +1,12 @@ -# Input Device +# @ohos.multimodalInput.inputDevice (Input Device) +The **inputDevice** module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse. -The Input Device module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse. - - -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import - ```js import inputDevice from '@ohos.multimodalInput.inputDevice'; ``` @@ -33,7 +28,7 @@ Obtains the IDs of all input devices. This API uses an asynchronous callback to ```js try { - inputDevice.getDeviceList((error, ids) => { + inputDevice.getDeviceIds((error, ids) => { if (error) { console.log(`Failed to get device list. error code=${JSON.stringify(err.code)} msg=${JSON.stringify(err.message)}`); @@ -65,7 +60,7 @@ Obtains the IDs of all input devices. This API uses a promise to return the resu ```js try { - inputDevice.getDeviceList().then((ids) => { + inputDevice.getDeviceIds().then((ids) => { console.log("The device ID list is: " + ids); }); } catch (error) { @@ -245,10 +240,15 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. **Example** ```js -inputDevice.getDeviceIds((ids)=>{ - console.log("The device ID list is: " + ids); +inputDevice.getDeviceIds((error, ids) => { + if (error) { + console.log(`Failed to get device id list, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Device id list: ${JSON.stringify(ids)}`); }); ``` +``` ## inputDevice.getDeviceIds(deprecated) @@ -269,8 +269,8 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. **Example** ```js -inputDevice.getDeviceIds().then((ids)=>{ - console.log("The device ID list is: " + ids); +inputDevice.getDeviceIds().then((ids) => { + console.log(`Device id list: ${JSON.stringify(ids)}`); }); ``` @@ -295,8 +295,12 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ```js // Obtain the name of the device whose ID is 1. -inputDevice.getDevice(1, (inputDevice)=>{ - console.log("The device name is: " + inputDevice.name); +inputDevice.getDevice(1, (error, deviceData) => { + if (error) { + console.log(`Failed to get device info, error: ${JSON.stringify(error, [`code`, `message`])}`); + return; + } + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); ``` @@ -326,14 +330,14 @@ This API is deprecated since API version 9. You are advised to use [inputDevice. ```js // Obtain the name of the device whose ID is 1. -inputDevice.getDevice(1).then((inputDevice)=>{ - console.log("The device name is: " + inputDevice.name); +inputDevice.getDevice(1).then((deviceData) => { + console.log(`Device info: ${JSON.stringify(deviceData)}`); }); ``` ## inputDevice.supportKeys9+ -supportKeys(deviceId: number, keys: Array<KeyCode>, callback: Callback<Array<boolean>>): void +supportKeys(deviceId: number, keys: Array<KeyCode>, callback: AsyncCallback <Array<boolean>>): void Obtains the key codes supported by the input device. This API uses an asynchronous callback to return the result. @@ -345,7 +349,7 @@ Obtains the key codes supported by the input device. This API uses an asynchrono | -------- | ------------------------------------ | ---- | --------------------------------- | | deviceId | number | Yes | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| | keys | Array<KeyCode> | Yes | Key codes to be queried. A maximum of five key codes can be specified. | -| callback | Callback<Array<boolean>> | Yes | Callback used to return the result. | +| callback | AsyncCallback<Array<boolean>> | Yes | Callback used to return the result. | **Example** @@ -460,10 +464,10 @@ Defines the listener for hot swap events of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| -------- | ------------------------- | --------------------------------- | -| type | [ChangedType](#changedtype) | Device change type, which indicates whether an input device is inserted or removed. | -| deviceId | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| type | [ChangedType](#changedtype) | Yes| No| Device change type, which indicates whether an input device is inserted or removed.| +| deviceId | number | Yes| No| Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| ## InputDeviceData @@ -471,18 +475,18 @@ Defines the information about an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| -------------------- | -------------------------------------- | ---------------------------------------- | -| id | number | Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes. | -| name | string | Name of the input device. | -| sources | Array<[SourceType](#sourcetype)> | Source type of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad.| -| axisRanges | Array<[axisRanges](#axisrange)> | Axis information of the input device. | -| bus9+ | number | Bus type of the input device. | -| product9+ | number | Product information of the input device. | -| vendor9+ | number | Vendor information of the input device. | -| version9+ | number | Version information of the input device. | -| phys9+ | string | Physical address of the input device. | -| uniq9+ | string | Unique ID of the input device. | +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| id | number | Yes| No| Unique ID of the input device. If the same physical device is repeatedly inserted and removed, its ID changes.| +| name | string | Yes| No| Name of the input device. | +| sources | Array<[SourceType](#sourcetype)> | Yes| No| Source type of the input device. For example, if a keyboard is attached with a touchpad, the device has two input sources: keyboard and touchpad.| +| axisRanges | Array<[AxisRange](#axisrange)> | Yes| No| Axis information of the input device. | +| bus9+ | number | Yes| No| Bus type of the input device. | +| product9+ | number | Yes| No| Product information of the input device. | +| vendor9+ | number | Yes| No| Vendor information of the input device. | +| version9+ | number | Yes| No| Version information of the input device. | +| phys9+ | string | Yes| No| Physical address of the input device. | +| uniq9+ | string | Yes| No| Unique ID of the input device. | ## AxisType9+ @@ -490,17 +494,17 @@ Defines the axis type of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| ----------- | ------ | --------------- | -| touchMajor | string | touchMajor axis. | -| touchMinor | string | touchMinor axis. | -| toolMinor | string | toolMinor axis. | -| toolMajor | string | toolMajor axis. | -| orientation | string | Orientation axis.| -| pressure | string | Pressure axis. | -| x | string | X axis. | -| y | string | Y axis. | -| NULL | string | None. | +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| touchMajor | string | Yes| No| touchMajor axis. | +| touchMinor | string | Yes| No| touchMinor axis. | +| toolMinor | string | Yes| No| toolMinor axis. | +| toolMajor | string | Yes| No| toolMajor axis. | +| orientation | string | Yes| No| Orientation axis.| +| pressure | string | Yes| No| Pressure axis. | +| x | string | Yes| No| X axis. | +| y | string | Yes| No| Y axis. | +| NULL | string | Yes| No| None. | ## AxisRange @@ -508,41 +512,41 @@ Defines the axis range of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| ----------------------- | ------------------------- | -------- | -| source | [SourceType](#sourcetype) | Input source type of the axis.| -| axis | [AxisType](#axistype9) | Axis type. | -| max | number | Maximum value of the axis. | -| min | number | Minimum value of the axis. | -| fuzz9+ | number | Fuzzy value of the axis. | -| flat9+ | number | Benchmark value of the axis. | -| resolution9+ | number | Resolution of the axis. | +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| source | [SourceType](#sourcetype) | Yes| No| Input source type of the axis.| +| axis | [AxisType](#axistype9) | Yes| No| Axis type. | +| max | number | Yes| No| Maximum value of the axis. | +| min | number | Yes| No| Minimum value of the axis. | +| fuzz9+ | number | Yes| No| Fuzzy value of the axis. | +| flat9+ | number | Yes| No| Benchmark value of the axis. | +| resolution9+ | number | Yes| No| Resolution of the axis. | -## SourceType +## SourceType9+ Enumerates the input source types. For example, if a mouse reports an x-axis event, the source of the x-axis is the mouse. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| ----------- | ------ | ----------- | -| keyboard | string | The input device is a keyboard. | -| touchscreen | string | The input device is a touchscreen.| -| mouse | string | The input device is a mouse. | -| trackball | string | The input device is a trackball.| -| touchpad | string | The input device is a touchpad.| -| joystick | string | The input device is a joystick.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| keyboard | string | Yes| No| The input device is a keyboard. | +| touchscreen | string | Yes| No| The input device is a touchscreen.| +| mouse | string | Yes| No| The input device is a mouse. | +| trackball | string | Yes| No| The input device is a trackball.| +| touchpad | string | Yes| No| The input device is a touchpad.| +| joystick | string | Yes| No| The input device is a joystick.| -## ChangedType +## ChangedType9+ Defines the change type for the hot swap event of an input device. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Description | -| ------ | ------ | --------- | -| add | string | An input device is inserted.| -| remove | string | An input device is removed.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| add | string | Yes| No| An input device is inserted.| +| remove | string | Yes| No| An input device is removed.| ## KeyboardType9+ @@ -550,11 +554,11 @@ Enumerates the keyboard types. **System capability**: SystemCapability.MultimodalInput.Input.InputDevice -| Name | Type | Value | Description | -| ------------------- | ------ | ---- | --------- | -| NONE | number | 0 | Keyboard without keys. | -| UNKNOWN | number | 1 | Keyboard with unknown keys.| -| ALPHABETIC_KEYBOARD | number | 2 | Full keyboard. | -| DIGITAL_KEYBOARD | number | 3 | Keypad. | -| HANDWRITING_PEN | number | 4 | Stylus. | -| REMOTE_CONTROL | number | 5 | Remote control. | +| Name | Value | Description | +| ------------------- | ---- | --------- | +| NONE | 0 | Keyboard without keys. | +| UNKNOWN | 1 | Keyboard with unknown keys.| +| ALPHABETIC_KEYBOARD | 2 | Full keyboard. | +| DIGITAL_KEYBOARD | 3 | Keypad. | +| HANDWRITING_PEN | 4 | Stylus. | +| REMOTE_CONTROL | 5 | Remote control. | diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md index 862c39c608ba76b56c23b675c9ef1da19c43331f..d2d55fa57ee6bd71288d03aa3f42e24bebb80bea 100644 --- a/en/application-dev/reference/apis/js-apis-inputevent.md +++ b/en/application-dev/reference/apis/js-apis-inputevent.md @@ -1,6 +1,6 @@ -# Input Event +# @ohos.multimodalInput.inputEvent (Input Event) -The Input Event module describes basic events reported by an input device. +The **inputEvent** module describes basic events reported by an input device. > **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. diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md index 695a7a5bf4b611270ff32acb8aab17cc6f802aa3..354f10e3802d163343b658bef56ab4e03689d2c3 100644 --- a/en/application-dev/reference/apis/js-apis-inputeventclient.md +++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md @@ -1,12 +1,10 @@ -# Key Injection +# @ohos.multimodalInput.inputEventClient (Key Event Injection) -The Key Injection module implements injection of key events. +The **inputEventClient** module implements injection of key events. -> **NOTE**
-> +> **NOTE** > - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> - The APIs of this module are system APIs and cannot be called by third-party applications. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -21,9 +19,7 @@ import inputEventClient from '@ohos.multimodalInput.inputEventClient'; injectEvent({KeyEvent: KeyEvent}): void -Injects a key event. - -This is a system API. +Injects a key event. Currently, key injection is supported only for the **Back** key (key value 2). **System capability**: SystemCapability.MultimodalInput.Input.InputSimulator @@ -37,37 +33,36 @@ This is a system API. ```js try { - var keyEvent = { + let backKeyDown = { isPressed: true, keyCode: 2, keyDownDuration: 0, isIntercepted: false } - inputEventClient.injectKeyEvent({ KeyEvent: keyEvent }); - var keyEvent1 = { + inputEventClient.injectEvent({ KeyEvent: backKeyDown }); + + let backKeyUp = { isPressed: false, keyCode: 2, keyDownDuration: 0, isIntercepted: false }; - inputEventClient.injectKeyEvent({ KeyEvent: keyEvent1 }); + inputEventClient.injectEvent({ KeyEvent: backKeyUp }); } catch (error) { - console.info("injectKeyEvent " + error.code + " " + error.message); + console.log(`Failed to inject KeyEvent, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` ## KeyEvent -Defines the information about the key event to inject. +Represents information about the key event to inject. **System capability**: SystemCapability.MultimodalInput.Input.InputSimulator -**Parameters** - -| Name | Type | Mandatory | Description | -| --------------- | ------- | ---- | --------- | -| isPressed | boolean | Yes | Whether the key is pressed. | -| keyCode | number | Yes | Key code. | -| keyDownDuration | number | Yes | Duration within which the key is pressed. | -| isIntercepted | boolean | Yes | Whether the key can be intercepted.| +| Name | Type | Readable | Writable | Description | +| --------- | ------ | ---- | ---- | ------- | +| isPressed | boolean | Yes | No| Whether the key is pressed. | +| keyCode | number | Yes | No| Key value. Currently, only the **Back** key is supported.| +| keyDownDuration | number | Yes | No| Duration within which the key is pressed. | +| isIntercepted | boolean | Yes | No| Whether the key can be intercepted. | diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md index eb94104e5e3dfc430db1f395f48ac0302d1e0a1c..6a8cabde0302010e3739f298ba03583325491ef8 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @@ -1,15 +1,14 @@ # InputMethodExtensionAbility -The **InputMethodExtensionAbility** module provides the **InputMethodExtensionAbility** and **InputMethodExtensionContext** APIs that you can implement to develop input methods and manage their lifecycles. +The **InputMethodExtensionAbility** module provides APIs for developing input methods and managing their lifecycles. > **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. ## Modules to Import -``` +```js import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; ``` @@ -21,10 +20,9 @@ import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; | -------- | -------- | -------- | -------- | -------- | | context | [InputMethodExtensionContext](js-apis-inputmethod-extension-context.md) | Yes| No| Context of the **InputMethodExtension**, which is inherited from **ExtensionContext**.| +## InputMethodExtensionAbility.onCreate -## InputMethodExtensionAbility.onCreate() - -onCreate(want: Want): void; +onCreate(want: Want): void Called when the **InputMethodExtension** ability is started to implement initialization. @@ -32,24 +30,23 @@ Called when the **InputMethodExtension** ability is started to implement initial **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information related to the **InputMethodExtension** ability, including the ability name and bundle name. | +| Name| Type | Mandatory| Description | +| ------ | ----------- | ---- | ------------------------------- | +| want | [Want](js-apis-app-ability-want.md) | Yes | Information related to the **InputMethodExtension** ability, including the ability name and bundle name.| **Example** - ```js - class InputMethodExt extends InputMethodExtensionAbility { +```js +class InputMethodExt extends InputMethodExtensionAbility { onCreate(want) { - console.log('onCreate, want:' + want.abilityName); + console.log('onCreate, want:' + want.abilityName); } - } - ``` - +} +``` -## InputMethodExtensionAbility.onDestroy() +## InputMethodExtensionAbility.onDestroy -onDestroy(): void; +onDestroy(): void Called when this **InputMethodExtension** ability is destroyed to clear resources. @@ -57,10 +54,10 @@ Called when this **InputMethodExtension** ability is destroyed to clear resource **Example** - ```js - class InputMethodExt extends InputMethodExtensionAbility { +```js +class InputMethodExt extends InputMethodExtensionAbility { onDestroy() { - console.log('onDestroy'); + console.log('onDestroy'); } - } - ``` +} +``` 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 a6554d89363a60c801a547d76f306b1b8744e71e..b33db13faa840a1660a42e612ef5a4d523241877 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 @@ -1,13 +1,12 @@ -# InputMethodExtensionContext +# @ohos.inputmethodextensioncontext (InputMethodExtensionContext) The **InputMethodExtensionContext** module, inherited from **ExtensionContext**, provides context for **InputMethodExtension** abilities. You can use the APIs of this module to start, terminate, connect, and disconnect abilities. > **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. ## Modules to Import @@ -20,112 +19,17 @@ import InputMethodExtensionContext from '@ohos.inputmethodextensioncontext'; Before using the **InputMethodExtensionContext** module, you must define a child class that inherits from **InputMethodExtensionAbility**. ```js - import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; - class MainAbility extends InputMethodExtensionAbility { - onCreate() { - let context = this.context; - } - } +import InputMethodExtensionAbility from '@ohos.inputmethodextensionability'; +class EntryAbility extends InputMethodExtensionAbility { + onCreate() { + let context = this.context; + } +} ``` -## InputMethodExtensionContext.startAbility +## InputMethodExtensionContext.destroy -startAbility(want: Want, callback: AsyncCallback<void>): void; - -Starts an ability with the **want** parameter. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.MiscServices.InputMethodFramework - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - let want = { - 'bundleName': 'com.example.myapp', - 'abilityName': 'MyAbility' - }; - this.context.startAbility(want, (err) => { - console.log('startAbility result:' + JSON.stringify(err)); - }); - ``` - -## InputMethodExtensionContext.startAbility - -startAbility(want: Want, options?: StartOptions): Promise\; - -Starts an ability with the mandatory **want** and optional **options** parameters. This API uses a promise to return the result. - -**System capability**: SystemCapability.MiscServices.InputMethodFramework - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability, such as the ability name and bundle name.| -| options | [StartOptions](js-apis-application-StartOptions.md) | No| Parameters used for starting the ability.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - -**Example** - - ```js - let want = { - 'bundleName': 'com.example.myapp', - 'abilityName': 'MyAbility' - }; - this.context.startAbility(want).then((data) => { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - - ``` - -## InputMethodExtensionContext.startAbility - -startAbility(want: Want, options: StartOptions, callback: AsyncCallback<void>): void - -Starts an ability with the **want** and **options** parameters. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.MiscServices.InputMethodFramework - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Information about the target ability.| -| options | [StartOptions](js-apis-application-StartOptions.md) | Yes| Parameters used for starting the ability.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result.| - -**Example** - - ```js - var want = { - 'deviceId': '', - 'bundleName': 'com.extreme.test', - 'abilityName': 'MainAbility' - }; - var options = { - windowMode: 0, - }; - this.context.startAbility(want, options, (error) => { - console.log('error.code = ' + error.code) - }) - ``` - -## InputMethodExtensionContext.terminateSelf - -terminateSelf(callback: AsyncCallback<void>): void; +destroy(callback: AsyncCallback\): void Terminates this ability. This API uses an asynchronous callback to return the result. @@ -133,21 +37,21 @@ Terminates this ability. This API uses an asynchronous callback to return the re **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** - ```js -this.context.terminateSelf((err) => { - console.log('terminateSelf result:' + JSON.stringify(err)); +```js +this.context.destroy((err) => { + console.log('destroy result:' + JSON.stringify(err)); }); - ``` +``` -## InputMethodExtensionContext.terminateSelf +## InputMethodExtensionContext.destroy -terminateSelf(): Promise<void>; +destroy(): Promise { - console.log('success:' + JSON.stringify(data)); - }).catch((error) => { - console.log('failed:' + JSON.stringify(error)); - }); - ``` +```js +this.context.destroy().then((data) => { + console.log('success:' + JSON.stringify(data)); +}).catch((error) => { + console.log('failed:' + JSON.stringify(error)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md b/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md new file mode 100644 index 0000000000000000000000000000000000000000..61ec49997ccb35b204f860e57b0985793598e071 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-inputmethod-subtype.md @@ -0,0 +1,29 @@ +# @ohos.inputmethodsubtype + +The **inputMethodSubtype** module provides APIs for managing the attributes of input method subtypes. Different attribute settings result in different subtypes. + +> **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 inputMethodEngine from '@ohos.inputMethodSubtype'; +``` + +## Attributes + + **System capability**: SystemCapability.MiscServices.InputMethodFramework + +| Name| Type| Readable| Writable| Mandatory| Description| +| -------- | -------- | -------- | -------- | -------- | -------- | +| label | string | Yes| No| No| Label of the input method subtype.| +| name | string | Yes| No| Yes| Name of the input method subtype.| +| id | string | Yes| No| Yes| ID of the input method subtype.| +| mode | string | Yes| No| No| Mode of the input method subtype, including **upper** (uppercase) and **lower** (lowercase).| +| locale | string | Yes| No| Yes| Locale of the input method subtype.| +| language | string | Yes| No| Yes| Language of the input method subtype.| +| icon | string | Yes| No| No| Icon of the input method subtype.| +| iconId | number | Yes| No| No| Icon ID of the input method subtype.| +| extra | object | Yes| Yes| Yes| Extra information of the input method subtype.| diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index 924a6306618087d4589f5e33cf1c770e8c75c61f..424e48b357711a7ee94eb4b048f107d7ad4c7a3d 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -1,28 +1,27 @@ -# Input Method Framework +# @ohos.inputmethod The **inputMethod** module provides an input method framework, which can be used to hide the keyboard, obtain the list of installed input methods, display the dialog box for input method selection, and more. -> **NOTE** +> **NOTE** > > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import inputMethod from '@ohos.inputmethod'; ``` -## inputMethod8+ +## Constants8+ Provides the constants. **System capability**: SystemCapability.MiscServices.InputMethodFramework -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| MAX_TYPE_NUM | number | Yes| No| Maximum number of supported input methods.| - +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| MAX_TYPE_NUM | number | 128 | Maximum number of supported input methods.| ## InputMethodProperty8+ @@ -32,12 +31,18 @@ Describes the input method application attributes. | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| packageName | string | Yes| No| Package name.| -| methodId | string | Yes| No| Ability name.| +| name9+ | string | Yes| No| Internal name of the input method. Mandatory.| +| id9+ | string | Yes| No| Unique ID of the input method. Mandatory.| +| label9+ | string | Yes| No| External display name of the input method. Optional.| +| icon9+ | string | Yes| No| Icon of the input method. Optional.| +| iconId9+ | number | Yes| No| Icon ID of the input method. Optional.| +| extra9+ | object | Yes| Yes| Extra information about the input method. Mandatory.| +| packageName(deprecated) | string | Yes| No| Name of the input method package. Mandatory.
**NOTE**
This API is supported since API version 8 and deprecated since API version 9. You are advised to use **name**.| +| methodId(deprecated) | string | Yes| No| Unique ID of the input method. Mandatory.
**NOTE**
This API is supported since API version 8 and deprecated since API version 9. You are advised to use **id**.| -## inputMethod.getInputMethodController +## inputMethod.getController9+ -getInputMethodController(): InputMethodController +getController(): InputMethodController Obtains an **[InputMethodController](#inputmethodcontroller)** instance. @@ -49,15 +54,23 @@ Obtains an **[InputMethodController](#inputmethodcontroller)** instance. | ----------------------------------------------- | ------------------------ | | [InputMethodController](#inputmethodcontroller) | Current **InputMethodController** instance.| +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | ------------------------------ | +| 12800006 | Input method controller error. | + **Example** ```js - var InputMethodController = inputMethod.getInputMethodController(); +let inputMethodController = inputMethod.getController(); ``` -## inputMethod.getInputMethodSetting8+ +## inputMethod.getSetting9+ -getInputMethodSetting(): InputMethodSetting +getSetting(): InputMethodSetting Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. @@ -69,17 +82,27 @@ Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. | ----------------------------------------- | ---------------------------- | | [InputMethodSetting](#inputmethodsetting8) | Current **InputMethodSetting** instance.| +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800007 | Input method settings extension error. | **Example** ```js - var InputMethodSetting = inputMethod.getInputMethodSetting(); +let inputMethodSetting = inputMethod.getSetting(); ``` + ## inputMethod.switchInputMethod9+ switchInputMethod(target: InputMethodProperty, callback: AsyncCallback<boolean>): void -Switches to another input method. This API can be used only in the stage model. It uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Switches to another input method. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -87,29 +110,51 @@ Switches to another input method. This API can be used only in the stage model. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -|target | [InputmethodProperty](#inputmethodproperty8) | Yes| Input method to switch to.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the execution result.| +| target | [InputMethodProperty](#inputmethodproperty8) | Yes| Input method to switch to.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object. | + +**Error codes** +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method manager service error. | **Example** ```js -inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'} ,(err,result) => { - if (err) { - console.error('switchInputMethod err: ' + JSON.stringify(err)); - return; - } - if (result) { - console.info('Success to switchInputMethod.(callback)'); - } else { - console.error('Failed to switchInputMethod.(callback)'); - } -}); +let im = inputMethod.getCurrentInputMethod(); +let prop = { + packageName: im.packageName, + methodId: im.methodId, + name: im.packageName, + id: im.methodId, + extra: {} +} +try{ + inputMethod.switchInputMethod(prop, (err, result) => { + if (err !== undefined) { + console.error('Failed to switchInputMethod: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in switching inputmethod.'); + } else { + console.error('Failed to switchInputMethod.'); + } + }); +} catch(err) { + console.error('Failed to switchInputMethod: ' + JSON.stringify(err)); +} ``` ## inputMethod.switchInputMethod9+ switchInputMethod(target: InputMethodProperty): Promise<boolean> -Switches to another input method. This API can be used only in the stage model. It uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. +Switches to another input method. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -117,28 +162,49 @@ Switches to another input method. This API can be used only in the stage model. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -|target | [InputmethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| +|target | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| **Return value** | Type | Description | | ----------------------------------------- | ---------------------------- | -| Promise\ | Promise used to return the execution result.| +| Promise\ | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| -**Example** +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method manager service error. | + +**Example** ```js -inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'}).then((result) => { - if (result) { - console.info('Success to switchInputMethod.(promise)'); - } else { - console.error('Failed to switchInputMethod.(promise)'); - } -}).catch((err) => { - console.error('switchInputMethod promise err: ' + err); -}) +let im = inputMethod.getCurrentInputMethod(); +let prop = { + packageName: im.packageName, + methodId: im.methodId, + name: im.packageName, + id: im.methodId, + extra: {} +} +try { + inputMethod.switchInputMethod(prop).then((result) => { + if (result) { + console.info('Succeeded in switching inputmethod.'); + } else { + console.error('Failed to switchInputMethod.'); + } + }).catch((err) => { + console.error('Failed to switchInputMethod: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('Failed to switchInputMethod: ' + JSON.stringify(err)); +} ``` + ## inputMethod.getCurrentInputMethod9+ getCurrentInputMethod(): InputMethodProperty @@ -151,24 +217,339 @@ Obtains the current input method. This API synchronously returns the **Inputmeth | Type | Description | | -------------------------------------------- | ------------------------ | -| [InputmethodProperty](#inputmethodproperty8) | **InputmethodProperty** instance of the current input method.| +| [InputMethodProperty](#inputmethodproperty8) | **InputmethodProperty** instance of the current input method.| + +**Example** + +```js +let currentIme = inputMethod.getCurrentInputMethod(); +``` + +## inputMethod.switchCurrentInputMethodSubtype9+ + +switchCurrentInputMethodSubtype(target: InputMethodSubtype, callback: AsyncCallback\): void + +Switches to another subtype of the current input method. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method manager service error. | + +**Example** + +```js +try { + inputMethod.switchCurrentInputMethodSubtype({ + id: "com.example.kikakeyboard", + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} + }, (err, result) => { + if (err !== undefined) { + console.error('Failed to switchCurrentInputMethodSubtype: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in switching currentInputMethodSubtype.'); + } else { + console.error('Failed to switchCurrentInputMethodSubtype'); + } + }); +} catch(err) { + console.error('Failed to switchCurrentInputMethodSubtype: ' + JSON.stringify(err)); +} +``` + +## inputMethod.switchCurrentInputMethodSubtype9+ + +switchCurrentInputMethodSubtype(target: InputMethodSubtype): Promise<boolean> + +Switches to another subtype of the current input method. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|target | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| + +**Return value** + +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method manager service error. | + +**Example** + +```js +try { + inputMethod.switchCurrentInputMethodSubtype({ + id: "com.example.kikakeyboard", + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} + }).then((result) => { + if (result) { + console.info('Succeeded in switching currentInputMethodSubtype.'); + } else { + console.error('Failed to switchCurrentInputMethodSubtype.'); + } + }).catch((err) => { + console.error('Failed to switchCurrentInputMethodSubtype: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('Failed to switchCurrentInputMethodSubtype: ' + JSON.stringify(err)); +} +``` + +## inputMethod.getCurrentInputMethodSubtype9+ + +getCurrentInputMethodSubtype(): InputMethodSubtype + +Obtains the current input method subtype. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| -------------------------------------------- | ------------------------ | +| [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype) | Current input method subtype.| + +**Example** + +```js +let currentImeSubType = inputMethod.getCurrentInputMethodSubtype(); +``` + +## inputMethod.switchCurrentInputMethodAndSubtype9+ + +switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype, callback: AsyncCallback\): void + +Switches to a specified subtype of a specified input method. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|inputMethodProperty | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| +|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method manager service error. | **Example** +```js +let im = inputMethod.getCurrentInputMethod(); +let inputMethodProperty = { + packageName: im.packageName, + methodId: im.methodId, + name: im.packageName, + id: im.methodId, + extra: {} +} +try { + inputMethod.switchCurrentInputMethodAndSubtype(inputMethodProperty, { + id: "com.example.kikakeyboard", + label: "ServiceExtAbility", + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} + }, (err,result) => { + if (err !== undefined) { + console.error('Failed to switchCurrentInputMethodAndSubtype: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in switching currentInputMethodAndSubtype.'); + } else { + console.error('Failed to switchCurrentInputMethodAndSubtype.'); + } + }); +} catch (err) { + console.error('Failed to switchCurrentInputMethodAndSubtype: ' + JSON.stringify(err)); +} +``` + +## inputMethod.switchCurrentInputMethodAndSubtype9+ + +switchCurrentInputMethodAndSubtype(inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype): Promise<boolean> + +Switches to a specified subtype of a specified input method. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +|inputMethodProperty | [InputMethodProperty](#inputmethodproperty8)| Yes| Input method to switch to.| +|inputMethodSubtype | [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)| Yes| Input method subtype to switch to.| + +**Return value** + +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the switching is successful, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800005 | Configuration persisting error. | +| 12800008 | Input method manager service error. | + +**Example** + +```js +let im = inputMethod.getCurrentInputMethod(); +let inputMethodProperty = { + packageName: im.packageName, + methodId: im.methodId, + name: im.packageName, + id: im.methodId, + extra: {} +} +try { + inputMethod.switchCurrentInputMethodAndSubtype(inputMethodProperty, { + id: im.packageName, + label: im.methodId, + name: "", + mode: "upper", + locale: "", + language: "", + icon: "", + iconId: 0, + extra: {} + }).then((result) => { + if (result) { + console.info('Succeeded in switching currentInputMethodAndSubtype.'); + } else { + console.error('Failed to switchCurrentInputMethodAndSubtype.'); + } + }).catch((err) => { + console.error('Failed to switchCurrentInputMethodAndSubtype: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('Failed to switchCurrentInputMethodAndSubtype: ' + JSON.stringify(err)); +} +``` + +## inputMethod.getInputMethodController(deprecated) + +getInputMethodController(): InputMethodController + +Obtains an **[InputMethodController](#inputmethodcontroller)** instance. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getController()](#inputmethodgetcontroller9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------ | +| [InputMethodController](#inputmethodcontroller) | Current **InputMethodController** instance.| + +**Example** ```js -var currentIme = inputMethod.getCurrentInputMethod(); +let inputMethodController = inputMethod.getInputMethodController(); +``` + +## inputMethod.getInputMethodSetting(deprecated) + +getInputMethodSetting(): InputMethodSetting + +Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. + +> **NOTE** +> +> This API is supported since API version 6 and deprecated since API version 9. You are advised to use [getSetting()](#inputmethodgetsetting9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ----------------------------------------- | ---------------------------- | +| [InputMethodSetting](#inputmethodsetting8) | Current **InputMethodSetting** instance.| + +**Example** + +```js +let inputMethodSetting = inputMethod.getInputMethodSetting(); ``` ## InputMethodController -In the following API examples, you must first use **[getInputMethodController](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use [getController](#inputmethodgetcontroller9) to obtain an **InputMethodController** instance, and then call the APIs using the obtained instance. -### stopInput +### stopInputSession9+ -stopInput(callback: AsyncCallback<boolean>): void +stopInputSession(callback: AsyncCallback<boolean>): void -Hides the keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Ends this input session. The invoking of this API takes effect only after the input session is enabled by clicking the text box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -176,29 +557,42 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the keyboard is successfully hidden.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method manager service error. | **Example** ```js -InputMethodController.stopInput((error, result) => { - if (error) { - console.error('failed to stopInput because: ' + JSON.stringify(error)); - return; - } - if (result) { - console.info('Success to stopInput.(callback)'); - } else { - console.error('Failed to stopInput.(callback)'); - } -}); +try { + inputMethodController.stopInputSession((error, result) => { + if (error !== undefined) { + console.error('Failed to stopInputSession: ' + JSON.stringify(error)); + return; + } + if (result) { + console.info('Succeeded in stopping inputSession.'); + } else { + console.error('Failed to stopInputSession.'); + } + }); +} catch(error) { + console.error('Failed to stopInputSession: ' + JSON.stringify(error)); +} ``` -### stopInput +### stopInputSession9+ -stopInput(): Promise<boolean> +stopInputSession(): Promise<boolean> -Hides the keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Ends this input session. The invoking of this API takes effect only after the input session is enabled by clicking the text box. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -206,28 +600,42 @@ Hides the keyboard. This API uses a promise to return the result. If any paramet | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return whether the keyboard is successfully hidden.| +| Promise<boolean> | Promise used to return the result. The value **true** means that the ending is successful, and **false** means the opposite.| -**Example** +**Error codes** +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method manager service error. | + +**Example** ```js -InputMethodController.stopInput().then((result) => { - if (result) { - console.info('Success to stopInput.(promise)'); - } else { - console.error('Failed to stopInput.(promise)'); - } -}).catch((err) => { - console.error('stopInput promise err: ' + err); -}) +try { + inputMethodController.stopInputSession().then((result) => { + if (result) { + console.info('Succeeded in stopping inputSession.'); + } else { + console.error('Failed to stopInputSession.'); + } + }).catch((err) => { + console.error('Failed to stopInputSession: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('Failed to stopInputSession: ' + JSON.stringify(err)); +} ``` -### showSoftKeyboard9+ ### +### showSoftKeyboard9+ showSoftKeyboard(callback: AsyncCallback<void>): void -Shows this soft keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Shows this soft keyboard. This API must be used with the input text box and works only when the input text box is activated. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -235,26 +643,36 @@ Shows this soft keyboard. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method manager service error. | **Example** ```js -InputMethodController.showSoftKeyboard((err) => { +inputMethodController.showSoftKeyboard((err) => { if (err === undefined) { - console.info('showSoftKeyboard success'); + console.info('Succeeded in showing softKeyboard.'); } else { - console.error('showSoftKeyboard failed because : ' + JSON.stringify(err)); + console.error('Failed to showSoftKeyboard: ' + JSON.stringify(err)); } }) ``` - -### showSoftKeyboard9+ ### +### showSoftKeyboard9+ showSoftKeyboard(): Promise<void> -Shows this soft keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Shows this soft keyboard. This API must be used with the input text box and works only when the input text box is activated. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -264,21 +682,32 @@ Shows this soft keyboard. This API uses a promise to return the result. If any p | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method manager service error. | + **Example** ```js -InputMethodController.showSoftKeyboard().then(async (err) => { - console.log('showSoftKeyboard success'); +inputMethodController.showSoftKeyboard().then(() => { + console.log('Succeeded in showing softKeyboard.'); }).catch((err) => { - console.error('showSoftKeyboard promise err: ' + JSON.stringify(err)); + console.error('Failed to showSoftKeyboard: ' + JSON.stringify(err)); }); ``` -### hideSoftKeyboard9+ ### +### hideSoftKeyboard9+ hideSoftKeyboard(callback: AsyncCallback<void>): void -Hides this soft keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Hides this soft keyboard. This API must be used with the input text box and works only when the input text box is activated. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -286,26 +715,36 @@ Hides this soft keyboard. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method manager service error. | **Example** ```js -InputMethodController.hideSoftKeyboard((err) => { +inputMethodController.hideSoftKeyboard((err) => { if (err === undefined) { - console.info('hideSoftKeyboard success'); + console.info('Succeeded in hiding softKeyboard.'); } else { - console.error('hideSoftKeyboard failed because : ' + JSON.stringify(err)); + console.error('Failed to hideSoftKeyboard: ' + JSON.stringify(err)); } }) ``` - -### hideSoftKeyboard9+ ### +### hideSoftKeyboard9+ hideSoftKeyboard(): Promise<void> -Hides this soft keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Hides this soft keyboard. This API must be used with the input text box and works only when the input text box is activated. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -315,25 +754,317 @@ Hides this soft keyboard. This API uses a promise to return the result. If any p | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800003 | Input method client error. | +| 12800008 | Input method manager service error. | + **Example** ```js -InputMethodController.hideSoftKeyboard().then(async (err) => { - console.log('hideSoftKeyboard success'); +inputMethodController.hideSoftKeyboard().then(() => { + console.log('Succeeded in hiding softKeyboard.'); }).catch((err) => { - console.error('hideSoftKeyboard promise err: ' + JSON.stringify(err)); + console.error('Failed to hideSoftKeyboard: ' + JSON.stringify(err)); }); ``` +### stopInput(deprecated) + +stopInput(callback: AsyncCallback<boolean>): void + +Ends this input session. The invoking of this API takes effect only after the input session is enabled by clicking the text box. 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 [stopInputSession()](#stopinputsession9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object. | + +**Example** + +```js +inputMethodController.stopInput((error, result) => { + if (error !== undefined) { + console.error('Failed to stopInput: ' + JSON.stringify(error)); + return; + } + if (result) { + console.info('Succeeded in stopping input.'); + } else { + console.error('Failed to stopInput.'); + } +}); +``` + +### stopInput(deprecated) + +stopInput(): Promise<boolean> + +Ends this input session. The invoking of this API takes effect only after the input session is enabled by clicking the text box. 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 [stopInputSession()](#stopinputsession9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. The value **true** means that the hiding is successful, and **false** means the opposite.| + +**Example** + +```js +inputMethodController.stopInput().then((result) => { + if (result) { + console.info('Succeeded in stopping input.'); + } else { + console.error('Failed to stopInput.'); + } +}).catch((err) => { + console.error('Failed to stopInput: ' + err); +}) +``` + ## InputMethodSetting8+ -In the following API examples, you must first use **[getInputMethodSetting](#inputmethodgetinputmethodcontroller)** to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use [getSetting](#inputmethodgetsetting9) to obtain an **InputMethodSetting** instance, and then call the APIs using the obtained instance. -### listInputMethod9+ +### on('imeChange')9+ -listInputMethod(enable: boolean, callback: AsyncCallback<Array<InputMethodProperty>>): void +on(type: 'imeChange', callback: (inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype) => void): void -Obtains a list of activated or deactivated input methods. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Enables listening for the input method and subtype change event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'imeChange'** indicates the input method and subtype change event.| +| callback | (inputMethodProperty: [InputMethodProperty](#inputmethodproperty8), inputMethodSubtype: [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)) => void | Yes| Callback used to return the input method attributes and subtype.| + +**Example** + +```js +inputMethodSetting.on('imeChange', (inputMethodProperty, inputMethodSubtype) => { + console.info('Succeeded in subscribing imeChange: inputMethodProperty: ' + JSON.stringify(inputMethodProperty) + " , inputMethodSubtype: " + JSON.stringify(inputMethodSubtype)); +}); +``` + +### off('imeChange')9+ + +off(type: 'imeChange', callback?: (inputMethodProperty: InputMethodProperty, inputMethodSubtype: InputMethodSubtype) => void): void + +Disables listening for the input method and subtype change event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'imeChange'** indicates the input method and subtype change event.| +| callback | (inputMethodProperty: [InputMethodProperty](#inputmethodproperty8), inputMethodSubtype: [InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)) => void | No| Callback used to return the input method attributes and subtype.| + +**Example** + +```js +inputMethodSetting.off('imeChange'); +``` + +### listInputMethodSubtype9+ + +listInputMethodSubtype(inputMethodProperty: InputMethodProperty, callback: AsyncCallback<Array<InputMethodSubtype>>): void + +Obtains all subtypes of a specified input method. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ---------------------- | +| inputMethodProperty | InputMethodProperty| Yes| Input method to which the subtypes belong.| +| callback | AsyncCallback<Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)>> | Yes| Callback used to return all subtypes of the specified input method.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method manager service error. | + +**Example** + +```js +let inputMethodProperty = { + packageName: 'com.example.kikakeyboard', + methodId: 'com.example.kikakeyboard', + name: 'com.example.kikakeyboard', + id: 'com.example.kikakeyboard', + extra:{} +} +try { + inputMethodSetting.listInputMethodSubtype(inputMethodProperty, (err,data) => { + if (err !== undefined) { + console.error('Failed to listInputMethodSubtype: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in listing inputMethodSubtype.'); + }); +} catch (err) { + console.error('Failed to listInputMethodSubtype: ' + JSON.stringify(err)); +} +``` + +### listInputMethodSubtype9+ + +listInputMethodSubtype(inputMethodProperty: InputMethodProperty): Promise<Array<InputMethodSubtype>> + +Obtains all subtypes of a specified input method. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ---------------------- | +| inputMethodProperty | InputMethodProperty| Yes| Input method to which the subtypes belong.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ---------------------- | +| Promise> | Promise used to return all subtypes of the specified input method.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method manager service error. | + +**Example** + +```js +let inputMethodProperty = { + packageName: 'com.example.kikakeyboard', + methodId: 'com.example.kikakeyboard', + name: 'com.example.kikakeyboard', + id: 'com.example.kikakeyboard', + extra:{} +} +try { + inputMethodSetting.listInputMethodSubtype(inputMethodProperty).then((data) => { + console.info('Succeeded in listing inputMethodSubtype.'); + }).catch((err) => { + console.error('Failed to listInputMethodSubtype: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('Failed to listInputMethodSubtype: ' + JSON.stringify(err)); +} +``` + +### listCurrentInputMethodSubtype9+ + +listCurrentInputMethodSubtype(callback: AsyncCallback<Array<InputMethodSubtype>>): void + +Obtains all subtypes of this input method. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------------- | ---- | ---------------------- | +| callback | AsyncCallback<Array<[InputMethodSubtype](./js-apis-inputmethod-subtype.md#inputmethodsubtype)>> | Yes | Callback used to return all subtypes of the current input method.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method manager service error. | + +**Example** + +```js +try { + inputMethodSetting.listCurrentInputMethodSubtype((err, data) => { + if (err !== undefined) { + console.error('Failed to listCurrentInputMethodSubtype: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in listing currentInputMethodSubtype.'); + }); +} catch(err) { + console.error('Failed to listCurrentInputMethodSubtype: ' + JSON.stringify(err)); +} +``` + +### listCurrentInputMethodSubtype9+ + +listCurrentInputMethodSubtype(): Promise<Array<InputMethodSubtype>> + +Obtains all subtypes of this input method. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ---------------------- | +| Promise> | Promise used to return all subtypes of the current input method.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method manager service error. | + +**Example** + +```js +try { + inputMethodSetting.listCurrentInputMethodSubtype().then((data) => { + console.info('Succeeded in listing currentInputMethodSubtype.'); + }).catch((err) => { + console.error('Failed to listCurrentInputMethodSubtype: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('Failed to listCurrentInputMethodSubtype: ' + JSON.stringify(err)); +} +``` + +### getInputMethods9+ + +getInputMethods(enable: boolean, callback: AsyncCallback<Array<InputMethodProperty>>): void + +Obtains a list of activated or deactivated input methods. In the current version, an activated input method is the input method in use, and a deactivated one is any of the installed input methods except the one in use. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -342,25 +1073,38 @@ Obtains a list of activated or deactivated input methods. This API uses an async | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ----------------------------- | | enable | boolean | Yes | Whether to return a list of activated input methods. The value **true** means to return a list of activated input methods, and **false** means to return a list of deactivated input methods. | -| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return a list of activated or deactivated input methods.| +| callback | AsyncCallback<Array<[InputMethodProperty](#inputmethodproperty8)>> | Yes | Callback used to return a list of activated or deactivated input methods.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method manager service error. | **Example** ```js -InputMethodSetting.listInputMethod(true, (err,data) => { - if (err) { - console.error('listInputMethod failed because: ' + JSON.stringify(err)); - return; - } - console.log('listInputMethod success'); - }); +try { + inputMethodSetting.getInputMethods(true, (err,data) => { + if (err !== undefined) { + console.error('Failed to getInputMethods: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in getting inputMethods.'); + }); +} catch (err) { + console.error('Failed to getInputMethods: ' + JSON.stringify(err)); +} ``` -### listInputMethod9+ +### getInputMethods9+ -listInputMethod(enable: boolean): Promise<Array<InputMethodProperty>> +getInputMethods(enable: boolean): Promise<Array<InputMethodProperty>> -Obtains a list of activated or deactivated input methods. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Obtains a list of activated or deactivated input methods. In the current version, an activated input method is the input method in use, and a deactivated one is any of the installed input methods except the one in use. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -370,6 +1114,15 @@ Obtains a list of activated or deactivated input methods. This API uses a promis | ------ | ------- | ---- | ----------------------- | | enable | boolean | Yes | Whether to return a list of activated input methods. The value **true** means to return a list of activated input methods, and **false** means to return a list of deactivated input methods.| +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800001 | Package manager error. | +| 12800008 | Input method manager service error. | + **Return value** | Type | Description | @@ -379,18 +1132,100 @@ Obtains a list of activated or deactivated input methods. This API uses a promis **Example** ```js -InputMethodSetting.listInputMethod(true).then((data) => { - console.info('listInputMethod success'); +try { + inputMethodSetting.getInputMethods(true).then((data) => { + console.info('Succeeded in getting inputMethods.'); + }).catch((err) => { + console.error('Failed to getInputMethods: ' + JSON.stringify(err)); + }) +} catch(err) { + console.error('Failed to getInputMethods: ' + JSON.stringify(err)); +} +``` + +### showOptionalInputMethods9+ + +showOptionalInputMethods(callback: AsyncCallback<boolean>): void + +Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800008 | Input method manager service error. | + +**Example** + +```js +try { + inputMethodSetting.showOptionalInputMethods((err, data) => { + if (err !== undefined) { + console.error('Failed to showOptionalInputMethods: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in showing optionalInputMethods.'); + }); +} catch (err) { + console.error('Failed to showOptionalInputMethods: ' + JSON.stringify(err)); +} +``` + +### showOptionalInputMethods9+ + +showOptionalInputMethods(): Promise<boolean> + +Displays a dialog box for selecting an input method. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.CONNECT_IME_ABILITY (available only to system applications) + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------------------- | +| 12800008 | Input method manager service error. | + +**Example** + +```js +inputMethodSetting.showOptionalInputMethods().then((data) => { + console.info('Succeeded in showing optionalInputMethods.'); }).catch((err) => { - console.error('listInputMethod promise err: ' + err); + console.error('Failed to showOptionalInputMethods: ' + JSON.stringify(err)); }) ``` -### listInputMethod +### listInputMethod(deprecated) listInputMethod(callback: AsyncCallback<Array<InputMethodProperty>>): void -Obtains a list of installed input methods. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Obtains a list of installed input methods. 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 [getInputMethods](#getinputmethods9). **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -398,25 +1233,29 @@ Obtains a list of installed input methods. This API uses an asynchronous callbac | Name | Type | Mandatory| Description | | -------- | -------------------------------------------------- | ---- | ---------------------- | -| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return the list of installed input methods.| +| callback | AsyncCallback<Array<[InputMethodProperty](#inputmethodproperty8)>> | Yes | Callback used to return the list of installed input methods.| **Example** ```js -InputMethodSetting.listInputMethod((err,data) => { - if (err) { - console.error('listInputMethod failed because: ' + JSON.stringify(err)); +inputMethodSetting.listInputMethod((err,data) => { + if (err !== undefined) { + console.error('Failed to listInputMethod: ' + JSON.stringify(err)); return; } - console.log('listInputMethod success'); + console.log('Succeeded in listing inputMethod.'); }); ``` -### listInputMethod +### listInputMethod(deprecated) listInputMethod(): Promise<Array<InputMethodProperty>> -Obtains a list of installed input methods. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Obtains a list of installed input methods. 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 [getInputMethods](#getinputmethods9-1). **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -429,18 +1268,22 @@ Obtains a list of installed input methods. This API uses a promise to return the **Example** ```js -InputMethodSetting.listInputMethod().then((data) => { - console.info('listInputMethod success'); +inputMethodSetting.listInputMethod().then((data) => { + console.info('Succeeded in listing inputMethod.'); }).catch((err) => { - console.error('listInputMethod promise err: ' + err); + console.error('Failed to listInputMethod: ' + JSON.stringify(err)); }) ``` -### displayOptionalInputMethod +### displayOptionalInputMethod(deprecated) displayOptionalInputMethod(callback: AsyncCallback<void>): void -Displays a dialog box for selecting an input method. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Displays a dialog box for selecting an input method. 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 [showOptionalInputMethods()](#showoptionalinputmethods9). **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -448,27 +1291,31 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | **Example** ```js -InputMethodSetting.displayOptionalInputMethod((err) => { - if (err) { - console.error('displayOptionalInputMethod failed because: ' + JSON.stringify(err)); +inputMethodSetting.displayOptionalInputMethod((err) => { + if (err !== undefined) { + console.error('Failed to displayOptionalInputMethod: ' + JSON.stringify(err)); return; } - console.info('displayOptionalInputMethod success'); + console.info('Succeeded in displaying optionalInputMethod.'); }); ``` -### displayOptionalInputMethod +### displayOptionalInputMethod(deprecated) - displayOptionalInputMethod(): Promise<void> +displayOptionalInputMethod(): Promise<void> - Displays a dialog box for selecting an input method. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Displays a dialog box for selecting an input method. This API uses a promise to return the result. - **System capability**: SystemCapability.MiscServices.InputMethodFramework +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [showOptionalInputMethods()](#showoptionalinputmethods9-1). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -479,9 +1326,9 @@ InputMethodSetting.displayOptionalInputMethod((err) => { **Example** ```js -InputMethodSetting.displayOptionalInputMethod().then(() => { - console.info('displayOptionalInputMethod success.(promise)'); +inputMethodSetting.displayOptionalInputMethod().then(() => { + console.info('Succeeded in displaying optionalInputMethod.'); }).catch((err) => { - console.error('displayOptionalInputMethod promise err: ' + err); + console.error('Failed to displayOptionalInputMethod: ' + JSON.stringify(err)); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 7ae35566725ea5fd3d489c29ea8b4d330695a534..2c87f74698434a68279b5e1c627e2a7352819a38 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -1,10 +1,10 @@ -# Input Method Engine +# @ohos.inputmethodengine -The **inputMethodEngine** module streamlines the interaction between applications and input methods. By calling APIs of this module, applications can accept text input through the input methods, be bound to input method services, request the keyboard to display or hide, listen for the input method status, and much more. +The **inputMethodEngine** module streamlines the interaction between input methods and applications. By calling APIs of this module, applications can be bound to input method services to accept text input through the input methods, request the keyboard to display or hide, listen for the input method status, and much more. > **NOTE** > -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -12,95 +12,143 @@ The **inputMethodEngine** module streamlines the interaction between application import inputMethodEngine from '@ohos.inputmethodengine'; ``` -## inputMethodEngine +## Constants -Provides the constants. +Provides the constant values of function keys, edit boxes, and the cursor. **System capability**: SystemCapability.MiscServices.InputMethodFramework -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| ENTER_KEY_TYPE_UNSPECIFIED | number | Yes| No| No function is specified for the Enter key.| -| ENTER_KEY_TYPE_GO | number | Yes| No| The Enter key takes the user to the target.| -| ENTER_KEY_TYPE_SEARCH | number | Yes| No| The Enter key takes the user to the results of their searching.| -| ENTER_KEY_TYPE_SEND | number | Yes| No| The Enter key sends the text to its target.| -| ENTER_KEY_TYPE_NEXT | number | Yes| No| The Enter key takes the user to the next field.| -| ENTER_KEY_TYPE_DONE | number | Yes| No| The Enter key takes the user to the next line.| -| ENTER_KEY_TYPE_PREVIOUS | number | Yes| No| The Enter key takes the user to the previous field.| -| PATTERN_NULL | number | Yes| No| Any type of edit box.| -| PATTERN_TEXT | number | Yes| No| Text edit box.| -| PATTERN_NUMBER | number | Yes| No| Number edit box.| -| PATTERN_PHONE | number | Yes| No| Phone number edit box.| -| PATTERN_DATETIME | number | Yes| No| Date edit box.| -| PATTERN_EMAIL | number | Yes| No| Email edit box.| -| PATTERN_URI | number | Yes| No| URI edit box.| -| PATTERN_PASSWORD | number | Yes| No| Password edit box.| -| OPTION_ASCII | number | Yes| No| ASCII values are allowed.| -| OPTION_NONE | number | Yes| No| No input attribute is specified.| -| OPTION_AUTO_CAP_CHARACTERS | number | Yes| No| Characters are allowed.| -| OPTION_AUTO_CAP_SENTENCES | number | Yes| No| Sentences are allowed.| -| OPTION_AUTO_WORDS | number | Yes| No| Words are allowed.| -| OPTION_MULTI_LINE | number | Yes| No| Multiple lines are allowed.| -| OPTION_NO_FULLSCREEN | number | Yes| No| Half-screen style.| -| FLAG_SELECTING | number | Yes| No| The edit box is being selected.| -| FLAG_SINGLE_LINE | number | Yes| No| The edit box allows only single-line input.| -| DISPLAY_MODE_PART | number | Yes| No| The edit box is displayed in half-screen mode.| -| DISPLAY_MODE_FULL | number | Yes| No| The edit box is displayed in full screen.| -| CURSOR_UP9+ | number | Yes| No| The caret moves upward.| -| CURSOR_DOWN9+ | number | Yes| No| The caret moves downward.| -| CURSOR_LEFT9+ | number | Yes| No| The caret moves leftward.| -| CURSOR_RIGHT9+ | number | Yes| No| The caret moves rightward.| -| WINDOW_TYPE_INPUT_METHOD_FLOAT9+ | number | Yes| No| The input method is displayed in a floating window.| - -## inputMethodEngine.getInputMethodEngine +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| ENTER_KEY_TYPE_UNSPECIFIED | number | 0 | No function is specified for the Enter key.| +| ENTER_KEY_TYPE_GO | number | 2 | The Enter key takes the user to the target.| +| ENTER_KEY_TYPE_SEARCH | number | 3 | The Enter key takes the user to the results of their searching.| +| ENTER_KEY_TYPE_SEND | number | 4 | The Enter key sends the text to its target.| +| ENTER_KEY_TYPE_NEXT | number | 5 | The Enter key takes the user to the next field.| +| ENTER_KEY_TYPE_DONE | number | 6 | The Enter key takes the user to the next line.| +| ENTER_KEY_TYPE_PREVIOUS | number | 7 | The Enter key takes the user to the previous field.| +| PATTERN_NULL | number | -1 | Any type of edit box.| +| PATTERN_TEXT | number | 0 | Text edit box.| +| PATTERN_NUMBER | number | 2 | Number edit box.| +| PATTERN_PHONE | number | 3 | Phone number edit box.| +| PATTERN_DATETIME | number | 4 | Date edit box.| +| PATTERN_EMAIL | number | 5 | Email edit box.| +| PATTERN_URI | number | 6 | URI edit box.| +| PATTERN_PASSWORD | number | 7 | Password edit box.| +| OPTION_ASCII | number | 20 | ASCII values are allowed.| +| OPTION_NONE | number | 0 | No input attribute is specified.| +| OPTION_AUTO_CAP_CHARACTERS | number | 2 | Characters are allowed.| +| OPTION_AUTO_CAP_SENTENCES | number | 8 | Sentences are allowed.| +| OPTION_AUTO_WORDS | number | 4 | Words are allowed.| +| OPTION_MULTI_LINE | number | 1 | Multiple lines are allowed.| +| OPTION_NO_FULLSCREEN | number | 10 | Half-screen style.| +| FLAG_SELECTING | number | 2 | The edit box is being selected.| +| FLAG_SINGLE_LINE | number | 1 | The edit box allows only single-line input.| +| DISPLAY_MODE_PART | number | 0 | The edit box is displayed in half-screen mode.| +| DISPLAY_MODE_FULL | number | 1 | The edit box is displayed in full screen.| +| CURSOR_UP9+ | number | 1 | The caret moves upward.| +| CURSOR_DOWN9+ | number | 2 | The caret moves downward.| +| CURSOR_LEFT9+ | number | 3 | The caret moves leftward.| +| CURSOR_RIGHT9+ | number | 4 | The caret moves rightward.| +| WINDOW_TYPE_INPUT_METHOD_FLOAT9+ | number | 2105 | The input method is displayed in a floating window.| + +## inputMethodEngine.getInputMethodAbility9+ + +getInputMethodAbility(): InputMethodAbility + +Obtains an **InputMethodEngine** instance. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| --------------------------------------- | ------------ | +| [InputMethodAbility](#inputmethodability) | **InputMethodEngine** instance obtained.| + +**Example** + +```js +let InputMethodAbility = inputMethodEngine.getInputMethodAbility(); +``` + +## inputMethodEngine.getKeyboardDelegate9+ + +getKeyboardDelegate(): KeyboardDelegate + +Obtains a **KeyboardDelegate** instance. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ------------------------------------- | ---------------- | +| [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance obtained.| + +**Example** + +```js +let KeyboardDelegate = inputMethodEngine.getKeyboardDelegate(); +``` + +## inputMethodEngine.getInputMethodEngine(deprecated) getInputMethodEngine(): InputMethodEngine Obtains an **InputMethodEngine** instance. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getInputMethodAbility()](#inputmethodenginegetinputmethodability9). + **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type | Description | | --------------------------------------- | ------------ | -| [InputMethodEngine](#InputMethodEngine) | **InputMethodEngine** instance obtained.| +| [InputMethodEngine](#inputmethodengine-1) | **InputMethodEngine** instance obtained.| **Example** - ```js - var InputMethodEngine = inputMethodEngine.getInputMethodEngine(); - ``` +```js +let InputMethodEngine = inputMethodEngine.getInputMethodEngine(); +``` -## inputMethodEngine.createKeyboardDelegate +## inputMethodEngine.createKeyboardDelegate(deprecated) createKeyboardDelegate(): KeyboardDelegate Obtains a **KeyboardDelegate** instance. +> **NOTE** +> +>This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getKeyboardDelegate()](#inputmethodenginegetkeyboarddelegate9). + **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** | Type | Description | | ------------------------------------- | ---------------- | -| [KeyboardDelegate](#KeyboardDelegate) | **KeyboardDelegate** instance obtained.| +| [KeyboardDelegate](#keyboarddelegate) | **KeyboardDelegate** instance obtained.| **Example** - ```js - var KeyboardDelegate = inputMethodEngine.createKeyboardDelegate(); - ``` +```js +let keyboardDelegate = inputMethodEngine.createKeyboardDelegate(); +``` -## InputMethodEngine +## InputMethodEngine -In the following API examples, you must first use [getInputMethodEngine](#getInputMethodEngine) to obtain an **InputMethodEngine** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getInputMethodEngine](#inputmethodenginegetinputmethodenginedeprecated)** to obtain an **InputMethodEngine** instance, and then call the APIs using the obtained instance. -### on('inputStart') +### on('inputStart') on(type: 'inputStart', callback: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void -Listens for the input method binding event. This API uses a callback to return the result. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. +Enables listening for the input method binding event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -108,23 +156,23 @@ Listens for the input method binding event. This API uses a callback to return t | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'inputStart'**, which indicates listening for the input method binding event.| -| callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | Yes| Callback used to return the result.| +| type | string | Yes | Listening type.
The value **'inputStart'** indicates the input method binding event.| +| callback | (kbController: [KeyboardController](#keyboardcontroller), textInputClient: [TextInputClient](#textinputclient)) => void | Yes| Callback used to return the **KeyboardController** and **TextInputClient** instances.| **Example** - ```js - InputMethodEngine.on('inputStart', (kbController, textInputClient) => { - KeyboardController = kbController; - TextInputClient = textInputClient; - }); - ``` +```js +inputMethodEngine.getInputMethodEngine().on('inputStart', (kbController, textClient) => { + let keyboardController = kbController; + let textInputClient = textClient; +}); +``` ### off('inputStart') off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void -Cancels listening for the input method binding event. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. +Cancels listening for the input method binding event. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -132,24 +180,119 @@ Cancels listening for the input method binding event. An exception is thrown in | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ------------------------ | -| type | string | Yes | Listening type.
Set it to **'inputStart'**, which indicates listening for the input method binding event.| -| callback | [KeyboardController](#KeyboardController), [TextInputClient](#TextInputClient) | No| Callback used to return the result.| +| type | string | Yes | Listening type.
The value **'inputStart'** indicates the input method binding event.| +| callback | (kbController: [KeyboardController](#keyboardcontroller), textInputClient: [TextInputClient](#textinputclient)) => void | No| Callback used to return the **KeyboardController** and **TextInputClient** instances.| + +**Example** + +```js +inputMethodEngine.getInputMethodEngine().off('inputStart', (kbController, textInputClient) => { + console.log('delete inputStart notification.'); +}); +``` + +### on('keyboardShow'|'keyboardHide') + +on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void + +Enables listening for a keyboard event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
- The value **'keyboardShow'** indicates the keyboard display event.
- The value **'keyboardHide'** indicates the keyboard hiding event. | +| callback | () => void | Yes | Callback used to return the result. | + +**Example** + +```js +inputMethodEngine.getInputMethodEngine().on('keyboardShow', () => { + console.log('inputMethodEngine keyboardShow.'); +}); +inputMethodEngine.getInputMethodEngine().on('keyboardHide', () => { + console.log('inputMethodEngine keyboardHide.'); +}); +``` + +### off('keyboardShow'|'keyboardHide') + +off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void + +Disables listening for a keyboard event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
- The value **'keyboardShow'** indicates the keyboard display event.
- The value **'keyboardHide'** indicates the keyboard hiding event.| +| callback | () => void | No | Callback used to return the result.| + +**Example** + +```js +inputMethodEngine.getInputMethodEngine().off('keyboardShow'); +inputMethodEngine.getInputMethodEngine().off('keyboardHide'); +``` + +## InputMethodAbility + +In the following API examples, you must first use **[getInputMethodAbility](#inputmethodenginegetinputmethodability9)** to obtain an **InputMethodAbility** instance, and then call the APIs using the obtained instance. + +### on('inputStart')9+ + +on(type: 'inputStart', callback: (kbController: KeyboardController, inputClient: InputClient) => void): void + +Enables listening for the input method binding event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'inputStart'** indicates the input method binding event.| +| callback | (kbController: [KeyboardController](#keyboardcontroller), inputClient: [InputClient](#inputclient9)) => void | Yes| Callback used to return the result.| + +**Example** + +```js +inputMethodEngine.getInputMethodAbility().on('inputStart', (kbController, client) => { + let keyboardController = kbController; + let inputClient = client; +}); +``` +### off('inputStart')9+ + +off(type: 'inputStart', callback?: (kbController: KeyboardController, inputClient: InputClient) => void): void + +Cancels listening for the input method binding event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| type | string | Yes | Listening type.
The value **'inputStart'** indicates the input method binding event.| +| callback | (kbController: [KeyboardController](#keyboardcontroller), inputClient: [InputClient](#inputclient9)) => void | No| Callback used to return the result.| **Example** - ```js - InputMethodEngine.off('inputStart', (kbController, textInputClient) => { - console.log('delete inputStart notification.'); - }); - ``` +```js +inputMethodEngine.getInputMethodAbility().off('inputStart'); +``` ### on('inputStop')9+ on(type: 'inputStop', callback: () => void): void -Listens for the input method stop event. This API uses a callback to return the result. +Enables listening for the input method unbinding event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -157,22 +300,22 @@ Listens for the input method stop event. This API uses a callback to return the | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'inputStop'**, which indicates listening for the input method stop event.| -| callback | void | Yes | Callback used to return the result. | +| type | string | Yes | Listening type.
The value **'inputStop'** indicates the input method unbinding event.| +| callback | () => void | Yes | Callback used to return the result. | **Example** - ```js -InputMethodEngine.getInputMethodEngine().on('inputStop', () => { - console.log('inputMethodEngine inputStop'); +```js +inputMethodEngine.getInputMethodAbility().on('inputStop', () => { + console.log('inputMethodAbility inputStop'); }); - ``` +``` ### off('inputStop')9+ off(type: 'inputStop', callback: () => void): void -Cancels listening for the input method stop event. This API uses a callback to return the result. +Cancels listening for the input method stop event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -180,22 +323,22 @@ Cancels listening for the input method stop event. This API uses a callback to r | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'inputStop'**, which indicates listening for the input method stop event.| -| callback | void | Yes | Callback used to return the result. | +| type | string | Yes | Listening type.
The value **'inputStop'** indicates the input method unbinding event.| +| callback | () => void | Yes | Callback used to return the result. | **Example** - ```js -InputMethodEngine.getInputMethodEngine().off('inputStop', () => { - console.log('inputMethodEngine delete inputStop notification.'); +```js +inputMethodEngine.getInputMethodAbility().off('inputStop', () => { + console.log('inputMethodAbility delete inputStop notification.'); }); - ``` +``` ### on('setCallingWindow')9+ -on(type: 'setCallingWindow', callback: (wid:number) => void): void +on(type: 'setCallingWindow', callback: (wid: number) => void): void -Listens for the window invocation setting event. This API uses a callback to return the result. +Enables listening for the window invocation setting event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -203,22 +346,22 @@ Listens for the window invocation setting event. This API uses a callback to ret | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'setCallingWindow'**, which indicates listening for the window invocation setting event.| -| callback | number | Yes | Window ID of the caller. | +| type | string | Yes | Listening type.
The value **'setCallingWindow'** indicates the window invocation setting event.| +| callback | (wid: number) => void | Yes | Callback used to return the window ID of the caller. | **Example** - ```js -InputMethodEngine.getInputMethodEngine().on('setCallingWindow', (wid) => { - console.log('inputMethodEngine setCallingWindow'); +```js +inputMethodEngine.getInputMethodAbility().on('setCallingWindow', (wid) => { + console.log('inputMethodAbility setCallingWindow'); }); - ``` +``` ### off('setCallingWindow')9+ off(type: 'setCallingWindow', callback: (wid:number) => void): void -Cancels listening for the window invocation setting event. This API uses a callback to return the result. +Disables listening for the window invocation setting event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -226,22 +369,22 @@ Cancels listening for the window invocation setting event. This API uses a callb | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'setCallingWindow'**, which indicates listening for the window invocation setting event.| -| callback | number | Yes | Window ID of the caller. | +| type | string | Yes | Listening type.
The value **'setCallingWindow'** indicates the window invocation setting event.| +| callback | (wid:number) => void | Yes | Callback used to return the window ID of the caller. | **Example** - ```js -InputMethodEngine.getInputMethodEngine().off('setCallingWindow', () => { - console.log('inputMethodEngine delete setCallingWindow notification.'); +```js +inputMethodEngine.getInputMethodAbility().off('setCallingWindow', () => { + console.log('inputMethodAbility delete setCallingWindow notification.'); }); - ``` +``` -### on('keyboardShow'|'keyboardHide') +### on('keyboardShow'|'keyboardHide')9+ on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void -Listens for an input method event. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. +Enables listening for a keyboard event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -249,25 +392,25 @@ Listens for an input method event. This API requires two parameters, the first o | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the keyboard.
- The value **'keyboardHide'** means to listen for hiding of the keyboard. | -| callback | void | No | Callback used to return the result. | +| type | string | Yes | Listening type.
- The value **'keyboardShow'** indicates the keyboard display event.
- The value **'keyboardHide'** indicates the keyboard hiding event.| +| callback | () => void | Yes | Callback used to return the result. | **Example** - ```js - InputMethodEngine.on('keyboardShow', () => { - console.log('inputMethodEngine keyboardShow.'); - }); - InputMethodEngine.on('keyboardHide', () => { - console.log('inputMethodEngine keyboardHide.'); - }); - ``` +```js +inputMethodEngine.getInputMethodAbility().on('keyboardShow', () => { + console.log('InputMethodAbility keyboardShow.'); +}); +inputMethodEngine.getInputMethodAbility().on('keyboardHide', () => { + console.log('InputMethodAbility keyboardHide.'); +}); +``` -### off('keyboardShow'|'keyboardHide') +### off('keyboardShow'|'keyboardHide')9+ off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void -Cancels listening for an input method event. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. +Disables listening for a keyboard event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -275,30 +418,75 @@ Cancels listening for an input method event. An exception is thrown in the follo | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the keyboard.
- The value **'keyboardHide'** means to listen for hiding of the keyboard.| -| callback | void | No | Callback used to return the result. | +| type | string | Yes | Listening type.
The value **'keyboardShow'** indicates the keyboard display event.
The value **'keyboardHide'** indicates the keyboard hiding event.| +| callback | () => void | No | Callback used to return the result. | + +**Example** + +```js +inputMethodEngine.getInputMethodAbility().off('keyboardShow', () => { + console.log('InputMethodAbility delete keyboardShow notification.'); +}); +inputMethodEngine.getInputMethodAbility().off('keyboardHide', () => { + console.log('InputMethodAbility delete keyboardHide notification.'); +}); +``` + +### on('setSubtype')9+ + +on(type: 'setSubtype', callback: (inputMethodSubtype: InputMethodSubtype) => void): void + +Enables listening for the input method subtype setting event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'setSubtype'** indicates the input method subtype setting event.| +| callback | (inputMethodSubtype: [InputMethodSubtype](js-apis-inputmethod-subtype.md)) => void | Yes | Callback used to return the input method subtype. | **Example** - ```js - InputMethodEngine.off('keyboardShow', () => { - console.log('inputMethodEngine delete keyboardShow notification.'); - }); - InputMethodEngine.off('keyboardHide', () => { - console.log('inputMethodEngine delete keyboardHide notification.'); - }); - ``` +```js +inputMethodEngine.getInputMethodAbility().on('setSubtype', (inputMethodSubtype) => { + console.log('InputMethodAbility setSubtype.'); +}); +``` + +### off('setSubtype')9+ + +off(type: 'setSubtype', callback?: (inputMethodSubtype: InputMethodSubtype) => void): void + +Disables listening for the input method subtype setting event. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'setSubtype'** indicates the input method subtype setting event.| +| callback | (inputMethodSubtype: [InputMethodSubtype](js-apis-inputmethod-subtype.md)) => void | No | Callback used to return the input method subtype. | + +**Example** + +```js +inputMethodEngine.getInputMethodAbility().off('setSubtype', () => { + console.log('InputMethodAbility delete setSubtype notification.'); +}); +``` -## KeyboardDelegate +## KeyboardDelegate -In the following API examples, you must first use [createKeyboardDelegate](#createKeyboardDelegate) to obtain a **KeyboardDelegate** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[getKeyboardDelegate](#inputmethodenginegetkeyboarddelegate9)** to obtain a **KeyboardDelegate** instance, and then call the APIs using the obtained instance. ### on('keyDown'|'keyUp') on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void -Listens for a hard keyboard even. This API uses a callback to return the key information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. +Enables listening for a keyboard event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -306,75 +494,71 @@ Listens for a hard keyboard even. This API uses a callback to return the key inf | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| -| callback | [KeyEvent](#KeyEvent) | Yes| Callback used to return the key information.| - - +| type | string | Yes | Listening type.
The value **'keyDown'** indicates the keydown event.
The value **'keyUp'** indicates the keyup event.| +| callback | (event: [KeyEvent](#keyevent)) => boolean | Yes| Callback used to return the key information.| **Example** - ```js - KeyboardDelegate.on('keyUp', (keyEvent) => { - console.info('inputMethodEngine keyCode.(keyUp):' + JSON.stringify(keyEvent.keyCode)); - console.info('inputMethodEngine keyAction.(keyUp):' + JSON.stringify(keyEvent.keyAction)); - return true; - }); - KeyboardDelegate.on('keyDown', (keyEvent) => { - console.info('inputMethodEngine keyCode.(keyDown):' + JSON.stringify(keyEvent.keyCode)); - console.info('inputMethodEngine keyAction.(keyDown):' + JSON.stringify(keyEvent.keyAction)); - return true; - }); - ``` +```js +inputMethodEngine.getKeyboardDelegate().on('keyUp', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyUp):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyUp):' + JSON.stringify(keyEvent.keyAction)); + return true; +}); +inputMethodEngine.getKeyboardDelegate().on('keyDown', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyDown):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyDown):' + JSON.stringify(keyEvent.keyAction)); + return true; +}); +``` ### off('keyDown'|'keyUp') off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void -Cancels listening for a hard keyboard even. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. +Disables listening for a keyboard event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| -| callback | [KeyEvent](#KeyEvent) | No | Callback used to return the key information. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'keyDown'** indicates the keydown event.
The value **'keyUp'** indicates the keyup event.| +| callback | (event: [KeyEvent](#keyevent)) => boolean | No | Callback used to return the key information. | **Example** - ```js - KeyboardDelegate.off('keyUp', (keyEvent) => { - console.log('delete keyUp notification.'); - return true; - }); - KeyboardDelegate.off('keyDown', (keyEvent) => { - console.log('delete keyDown notification.'); - return true; - }); - ``` +```js +inputMethodEngine.getKeyboardDelegate().off('keyUp', (keyEvent) => { + console.log('delete keyUp notification.'); + return true; +}); +inputMethodEngine.getKeyboardDelegate().off('keyDown', (keyEvent) => { + console.log('delete keyDown notification.'); + return true; +}); +``` ### on('cursorContextChange') on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void -Listens for cursor context changes. This API uses a callback to return the cursor information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. - - **System capability**: SystemCapability.MiscServices.InputMethodFramework - - **Parameters** +Enables listening for the cursor change event. This API uses an asynchronous callback to return the result. -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| -| callback | number | Yes | Callback used to return the cursor information. | +**System capability**: SystemCapability.MiscServices.InputMethodFramework +**Parameters** +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'cursorContextChange'** indicates the cursor change event.| +| callback | (x: number, y: number, height: number) => void | Yes | Callback used to return the cursor information.
- **x**: x coordinate of the top of the cursor.
- **y**: x coordinate of the bottom of the cursor.
- **height**: height of the cursor.| - **Example** +**Example** ```js -KeyboardDelegate.on('cursorContextChange', (x, y, height) => { +inputMethodEngine.getKeyboardDelegate().on('cursorContextChange', (x, y, height) => { console.log('inputMethodEngine cursorContextChange x:' + x); console.log('inputMethodEngine cursorContextChange y:' + y); console.log('inputMethodEngine cursorContextChange height:' + height); @@ -383,24 +567,24 @@ KeyboardDelegate.on('cursorContextChange', (x, y, height) => { ### off('cursorContextChange') -off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) => void): void +off(type: 'cursorContextChange', callback?: (x: number, y: number, height: number) => void): void -Cancels listening for cursor context changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. +Cancels listening for cursor context changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'cursorContextChange'**, which indicates listening for cursor context changes.| -| callback | number | No | Callback used to return the cursor information. | +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'cursorContextChange'** indicates the cursor change event.| +| callback | (x: number, y:number, height:number) => void | No | Callback used to return the cursor information.
- **x**: x coordinate of the top of the cursor.
- **y**: x coordinate of the bottom of the cursor.
- **height**: height of the cursor.
| **Example** ```js -KeyboardDelegate.off('cursorContextChange', (x, y, height) => { +inputMethodEngine.getKeyboardDelegate().off('cursorContextChange', (x, y, height) => { console.log('delete cursorContextChange notification.'); }); ``` @@ -408,21 +592,21 @@ KeyboardDelegate.off('cursorContextChange', (x, y, height) => { on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void -Listens for text selection changes. This API uses a callback to return the text selection information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. +Enables listening for the text selection change event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| -| callback | number | Yes | Callback used to return the text selection information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'selectionChange'** indicates the text selection change event.| +| callback | (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void | Yes | Callback used to return the text selection information.
- **oldBegin**: start of the selected text before the change.
- **oldEnd**: end of the selected text before the change.
- **newBegin**: start of the selected text after the change.
- **newEnd**: end of the selected text after the change.| - **Example** +**Example** ```js -KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { +inputMethodEngine.getKeyboardDelegate().on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { console.log('inputMethodEngine beforeEach selectionChange oldBegin:' + oldBegin); console.log('inputMethodEngine beforeEach selectionChange oldEnd:' + oldEnd); console.log('inputMethodEngine beforeEach selectionChange newBegin:' + newBegin); @@ -434,21 +618,21 @@ KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void -Cancels listening for text selection changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. +Cancels listening for text selection changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'selectionChange'**, which indicates listening for text selection changes.| -| callback | number | No | Callback used to return the text selection information. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
The value **'selectionChange'** indicates the text selection change event.| +| callback | (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void | No | Callback used to return the text selection information.
- **oldBegin**: start of the selected text before the change.
- **oldEnd**: end of the selected text before the change.
- **newBegin**: start of the selected text after the change.
- **newEnd**: end of the selected text after the change.
| - **Example** +**Example** ```js -KeyboardDelegate.off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { +inputMethodEngine.getKeyboardDelegate().off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { console.log('delete selectionChange notification.'); }); ``` @@ -458,21 +642,21 @@ KeyboardDelegate.off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => on(type: 'textChange', callback: (text: string) => void): void -Listens for text changes. This API uses a callback to return the current text content. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. +Enables listening for the text change event. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| -| callback | string | Yes | Callback used to return the current text content. | +| type | string | Yes | Listening type.
The value **'textChange'** indicates the text change event.| +| callback | (text: string) => void | Yes | Callback used to return the text content. | - **Example** +**Example** ```js -KeyboardDelegate.on('textChange', (text) => { +inputMethodEngine.getKeyboardDelegate().on('textChange', (text) => { console.log('inputMethodEngine textChange. text:' + text); }); ``` @@ -481,34 +665,34 @@ KeyboardDelegate.on('textChange', (text) => { off(type: 'textChange', callback?: (text: string) => void): void -Cancels listening for text changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. +Cancels listening for text changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
Set it to **'textChange'**, which indicates listening for text changes.| -| callback | string | No | Callback used to return the current text content. | +| type | string | Yes | Listening type.
The value **'textChange'** indicates the text change event.| +| callback | (text: string) => void | No | Callback used to return the text content.| - **Example** +**Example** ```js -keyboardDelegate.off('textChange', (text) => { +inputMethodEngine.getKeyboardDelegate().off('textChange', (text) => { console.log('delete textChange notification. text:' + text); }); ``` -## KeyboardController +## KeyboardController -In the following API examples, you must first use [inputStart](#inputStart) to obtain a **KeyboardController** instance, and then call the APIs using the obtained instance. +In the following API examples, you must first use **[on('inputStart')](#oninputstart9)** to obtain a **KeyboardController** instance, and then call the APIs using the obtained instance. -### hideKeyboard +### hide9+ -hideKeyboard(callback: AsyncCallback<void>): void +hide(callback: AsyncCallback<void>): void -Hides the keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Hides the keyboard. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -516,26 +700,33 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | -------- | -| callback | AsyncCallback<void> | No | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| -**Example** +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + +**Example** ```js -KeyboardController.hideKeyboard((err) => { - if (err === undefined) { - console.error('hideKeyboard callback result---err: ' + err.msg); +keyboardController.hide((err) => { + if (err !== undefined) { + console.error('Failed to hide keyboard: ' + JSON.stringify(err)); return; } - console.log('hideKeyboard callback.'); + console.log('Succeeded in hiding keyboard.'); }); ``` -### hideKeyboard +### hide9+ -hideKeyboard(): Promise<void> +hide(): Promise<void> -Hides the keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Hides the keyboard. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -545,116 +736,135 @@ Hides the keyboard. This API uses a promise to return the result. If any paramet | ---------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + **Example** ```js -async function InputMethodEngine() { - await KeyboardController.hideKeyboard().then(() => { - console.info('hideKeyboard promise.'); - }).catch((err) => { - console.info('hideKeyboard promise err: ' + err.msg); - }); -} +keyboardController.hide().then(() => { + console.info('Succeeded in hiding keyboard.'); +}).catch((err) => { + console.info('Failed to hide keyboard: ' + JSON.stringify(err)); +}); ``` -## TextInputClient +### hideKeyboard(deprecated) -In the following API examples, you must first use [inputStart](#inputStart) to obtain a **TextInputClient** instance, and then call the APIs using the obtained instance. - -### getForward +hideKeyboard(callback: AsyncCallback<void>): void -getForward(length:number, callback: AsyncCallback<string>): void +Hides the keyboard. This API uses an asynchronous callback to return the result. -Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [hide](#hide9). **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| length | number | Yes| Text length.| -| callback | AsyncCallback<string> | Yes| Callback used to return the text.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | -------- | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** - ```js - var length = 1; - TextInputClient.getForward(length, (err, text) => { - if (err === undefined) { - console.error('getForward callback result---err: ' + err.msg); - return; - } - console.log('getForward callback result---text: ' + text); - }); - ``` - -### getForward +```js +keyboardController.hideKeyboard((err) => { + if (err !== undefined) { + console.error('Failed to hide Keyboard: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in hiding keyboard.'); +}); +``` -getForward(length:number): Promise<string> +### hideKeyboard(deprecated) -Obtains the specific-length text before the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. +hideKeyboard(): Promise<void> -**System capability**: SystemCapability.MiscServices.InputMethodFramework +Hides the keyboard. 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 [hide](#hide9-1). -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| length | number | Yes| Text length.| +**System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | Promise used to return the text. | +| Type | Description | +| ---------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** - ```js - async function InputMethodEngine() { - var length = 1; - await TextInputClient.getForward(length).then((text) => { - console.info('getForward promise result---res: ' + text); - }).catch((err) => { - console.error('getForward promise err: ' + err.msg); - }); - } - ``` +```js +keyboardController.hideKeyboard().then(() => { + console.info('Succeeded in hiding keyboard.'); +}).catch((err) => { + console.info('Failed to hide Keyboard: ' + JSON.stringify(err)); +}); +``` + +## InputClient9+ -### getBackward +In the following API examples, you must first use **[on('inputStart')](#oninputstart9)** to obtain an **InputClient** instance, and then call the APIs using the obtained instance. -getBackward(length:number, callback: AsyncCallback<string>): void +### sendKeyFunction9+ + +sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void -Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Sends the function key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework -**Parameters** + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| length | number | Yes| Text length.| -| callback | AsyncCallback<string> | Yes| Callback used to return the text.| +| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| -**Example** +**Error codes** - ```js - var length = 1; - TextInputClient.getBackward(length, (err, text) => { - if (err === undefined) { - console.error('getBackward callback result---err: ' + err.msg); - return; - } - console.log('getBackward callback result---text: ' + text); - }); - ``` +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). -### getBackward +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | -getBackward(length:number): Promise<string> + **Example** + +```js +let action = 1; +try { + inputClient.sendKeyFunction(action, (err, result) => { + if (err !== undefined) { + console.error('Failed to sendKeyFunction: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in sending key function. '); + } else { + console.error('Failed to sendKeyFunction. '); + } + }); +} catch (err) { + console.error('sendKeyFunction err: ' + JSON.stringify(err)); +} +``` + +### sendKeyFunction9+ + +sendKeyFunction(action: number): Promise<boolean> -Obtains the specific-length text after the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. +Sends the function key. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -662,32 +872,46 @@ Obtains the specific-length text after the cursor. This API uses a promise to re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| length | number | Yes| Text length.| +| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| **Return value** | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<string> | Promise used to return the text. | +| Promise<boolean> | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **Example** - ```js - async function InputMethodEngine() { - var length = 1; - await TextInputClient.getBackward(length).then((text) => { - console.info('getBackward promise result---res: ' + text); - }).catch((err) => { - console.error('getBackward promise err: ' + err.msg); - }); - } - ``` +```js +let action = 1; +try { + inputClient.sendKeyFunction(action).then((result) => { + if (result) { + console.info('Succeeded in sending key function. '); + } else { + console.error('Failed to sendKeyFunction. '); + } + }).catch((err) => { + console.error('Failed to sendKeyFunction:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Failed to sendKeyFunction: ' + JSON.stringify(err)); +} +``` -### deleteForward +### getForward9+ -deleteForward(length:number, callback: AsyncCallback<boolean>): void +getForward(length:number, callback: AsyncCallback<string>): void -Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -696,98 +920,124 @@ Deletes the fixed-length text before the cursor. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | length | number | Yes| Text length.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the obtained text. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | **Example** - ```js - var length = 1; - TextInputClient.deleteForward(length, (err, result) => { - if (err === undefined) { - console.error('deleteForward callback result---err: ' + err.msg); - return; - } - if (result) { - console.info('Success to deleteForward.(callback) '); - } else { - console.error('Failed to deleteForward.(callback) '); - } - }); - ``` -### deleteForward +```js +let length = 1; +try { + inputClient.getForward(length, (err, text) => { + if (err !== undefined) { + console.error('Failed to getForward: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in getting forward, text: ' + text); + }); +} catch (err) { + console.error('Failed to getForward: ' + JSON.stringify(err)); +} +``` + +### getForward9+ -deleteForward(length:number): Promise<boolean> +getForward(length:number): Promise<string> -Deletes the fixed-length text before the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. +Obtains the specific-length text before the cursor. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------- | -| length | number | Yes | Text length.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| -**Return value** +**Return value** -| Type | Description | -| ---------------------- | -------------- | -| Promise<boolean> | Promise used to return the result.| +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise used to return the specific-length text before the cursor. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | **Example** ```js -async function InputMethodEngine() { - var length = 1; - await TextInputClient.deleteForward(length).then((result) => { - if (result) { - console.info('Success to deleteForward.(promise) '); - } else { - console.error('Failed to deleteForward.(promise) '); - } +let length = 1; +try { + inputClient.getForward(length).then((text) => { + console.info('Succeeded in getting forward, text: ' + text); }).catch((err) => { - console.error('deleteForward promise err: ' + err.msg); + console.error('Failed to getForward: ' + JSON.stringify(err)); }); +} catch (err) { + console.error('Failed to getForward: ' + JSON.stringify(err)); } ``` -### deleteBackward +### getBackward9+ -deleteBackward(length:number, callback: AsyncCallback<boolean>): void +getBackward(length:number, callback: AsyncCallback<string>): void -Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | -------------- | -| length | number | Yes | Text length. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| +| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the obtained text. Otherwise, **err** is an error object.| - **Example** +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**Example** ```js -var length = 1; -TextInputClient.deleteBackward(length, (err, result) => { - if (err === undefined) { - console.error('deleteBackward callback result---err: ' + err.msg); - return; - } - if (result) { - console.info('Success to deleteBackward.(callback) '); - } else { - console.error('Failed to deleteBackward.(callback) '); - } -}); +let length = 1; +try { + inputClient.getBackward(length, (err, text) => { + if (err !== undefined) { + console.error('Failed to getForward: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in getting backward, text: ' + text); + }); +} catch (err) { + console.error('Failed to getForward: ' + JSON.stringify(err)); +} ``` -### deleteBackward +### getBackward9+ -deleteBackward(length:number): Promise<boolean> +getBackward(length:number): Promise<string> -Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Obtains the specific-length text after the cursor. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -801,60 +1051,175 @@ Deletes the fixed-length text after the cursor. This API uses an asynchronous ca | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. | +| Promise<string> | Promise used to return the specific-length text after the cursor. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | ------------------------------ | +| 12800003 | Input method client error. | +| 12800006 | Input method controller error. | + +**Example** + +```js +let length = 1; +try { + inputClient.getBackward(length).then((text) => { + console.info('Succeeded in getting backward, text: ' + text); + }).catch((err) => { + console.error('Failed to getForward: ' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Failed to getForward: ' + JSON.stringify(err)); +} +``` + +### deleteForward9+ + +deleteForward(length:number, callback: AsyncCallback<boolean>): void + +Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | + +**Example** + +```js +let length = 1; +try { + inputClient.deleteForward(length, (err, result) => { + if (err !== undefined) { + console.error('Failed to delete forward: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in deleting forward. '); + } else { + console.error('Failed to delete forward: ' + JSON.stringify(err)); + } + }); +} catch (err) { + console.error('Failed to delete forward: ' + JSON.stringify(err)); +} +``` + +### deleteForward9+ + +deleteForward(length:number): Promise<boolean> + +Deletes the fixed-length text before the cursor. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| length | number | Yes | Text length.| + +**Return value** + +| Type | Description | +| ---------------------- | -------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **Example** ```js -async function InputMethodEngine() { - var length = 1; - await TextInputClient.deleteBackward(length).then((result) => { +let length = 1; +try { + inputClient.deleteForward(length).then((result) => { if (result) { - console.info('Success to deleteBackward.(promise) '); + console.info('Succeeded in deleting forward. '); } else { - console.error('Failed to deleteBackward.(promise) '); + console.error('Failed to delete Forward. '); } }).catch((err) => { - console.error('deleteBackward promise err: ' + err.msg); + console.error('Failed to delete Forward: ' + JSON.stringify(err)); }); +} catch (err) { + console.error('Failed to delete Forward: ' + JSON.stringify(err)); } ``` -### sendKeyFunction -sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void +### deleteBackward9+ + +deleteBackward(length:number, callback: AsyncCallback<boolean>): void -Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework - **Parameters** +**Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| action | number | Yes| Edit box attribute.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | -------------- | +| length | number | Yes | Text length. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| - **Example** +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | + +**Example** ```js -TextInputClient.sendKeyFunction(keyFunction, (err, result) => { - if (err === undefined) { - console.error('sendKeyFunction callback result---err: ' + err.msg); - return; - } - if (result) { - console.info('Success to sendKeyFunction.(callback) '); - } else { - console.error('Failed to sendKeyFunction.(callback) '); - } -}); +let length = 1; +try { + inputClient.deleteBackward(length, (err, result) => { + if (err !== undefined) { + console.error('Failed to delete Backward: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in deleting backward. '); + } else { + console.error('Failed to delete Backward: ' + JSON.stringify(err)); + } + }); +} catch (err) { + console.error('deleteBackward err: ' + JSON.stringify(err)); +} ``` -### sendKeyFunction +### deleteBackward9+ -sendKeyFunction(action:number): Promise<boolean> +deleteBackward(length:number): Promise<boolean> -Sets the Enter key to send the text to its target. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -862,35 +1227,43 @@ Sets the Enter key to send the text to its target. This API uses a promise to re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| action | number | Yes| Edit box attribute.| +| length | number | Yes| Text length.| **Return value** | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. | +| Promise<boolean> | Promise used to return the result. The value **true** means that the deletion is successful, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **Example** - ```js - async function InputMethodEngine() { - await client.sendKeyFunction(keyFunction).then((result) => { - if (result) { - console.info('Success to sendKeyFunction.(promise) '); - } else { - console.error('Failed to sendKeyFunction.(promise) '); - } - }).catch((err) => { - console.error('sendKeyFunction promise err:' + err.msg); - }); - } - ``` - -### insertText +```js +let length = 1; +inputClient.deleteBackward(length).then((result) => { + if (result) { + console.info('Succeeded in deleting backward. '); + } else { + console.error('Failed to deleteBackward. '); + } +}).catch((err) => { + console.error('Failed to deleteBackward: ' + JSON.stringify(err)); +}); +``` + +### insertText9+ insertText(text:string, callback: AsyncCallback<boolean>): void -Inserts text. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. +Inserts text. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -899,29 +1272,38 @@ Inserts text. This API uses an asynchronous callback to return the result. If th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | text | string | Yes| Text to insert.| -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **Example** ```js -TextInputClient.insertText('test', (err, result) => { - if (err === undefined) { - console.error('insertText callback result---err: ' + err.msg); +inputClient.insertText('test', (err, result) => { + if (err !== undefined) { + console.error('Failed to insertText: ' + JSON.stringify(err)); return; } if (result) { - console.info('Success to insertText.(callback) '); + console.info('Succeeded in inserting text. '); } else { - console.error('Failed to insertText.(callback) '); + console.error('Failed to insertText. '); } }); ``` -### insertText +### insertText9+ insertText(text:string): Promise<boolean> -Inserts text. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. +Inserts text. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -935,29 +1317,40 @@ Inserts text. This API uses a promise to return the result. If the required para | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. | +| Promise<boolean> | Promise used to return the result. The value **true** means that the insertion is successful, and **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800002 | Input method engine error. | +| 12800003 | Input method client error. | **Example** - ```js - async function InputMethodEngine() { - await TextInputClient.insertText('test').then((result) => { - if (result) { - console.info('Success to insertText.(promise) '); - } else { - console.error('Failed to insertText.(promise) '); - } - }).catch((err) => { - console.error('insertText promise err: ' + err.msg); - }); - } - ``` - -### getEditorAttribute +```js +try { + inputClient.insertText('test').then((result) => { + if (result) { + console.info('Succeeded in inserting text. '); + } else { + console.error('Failed to insertText. '); + } + }).catch((err) => { + console.error('Failed to insertText: ' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Failed to insertText: ' + JSON.stringify(err)); +} +``` + +### getEditorAttribute9+ getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void -Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -965,26 +1358,34 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | -| callback | AsyncCallback<[EditorAttribute](#EditorAttribute)> | Yes| Attribute of the edit box. | +| callback | AsyncCallback<[EditorAttribute](#editorattribute)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the attribute of the edit box. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **Example** - ```js - TextInputClient.getEditorAttribute((err, editorAttribute) => { - if (err === undefined) { - console.error('getEditorAttribute callback result---err: ' + err.msg); - return; - } - console.log('editorAttribute.inputPattern(callback): ' + JSON.stringify(editorAttribute.inputPattern)); - console.log('editorAttribute.enterKeyType(callback): ' + JSON.stringify(editorAttribute.enterKeyType)); - }); - ``` +```js +inputClient.getEditorAttribute((err, editorAttribute) => { + if (err !== undefined) { + console.error('Failed to getEditorAttribute: ' + JSON.stringify(err)); + return; + } + console.log('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.log('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}); +``` -### getEditorAttribute +### getEditorAttribute9+ getEditorAttribute(): Promise<EditorAttribute> -Obtains the attribute of the edit box. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. +Obtains the attribute of the edit box. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -992,26 +1393,32 @@ Obtains the attribute of the edit box. This API uses a promise to return the res | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<[EditorAttribute](#EditorAttribute)> | Promise used to return the attribute of the edit box. | +| Promise<[EditorAttribute](#editorattribute)> | Promise used to return the attribute of the edit box. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **Example** - ```js - async function InputMethodEngine() { - await TextInputClient.getEditorAttribute().then((editorAttribute) => { - console.info('editorAttribute.inputPattern(promise): ' + JSON.stringify(editorAttribute.inputPattern)); - console.info('editorAttribute.enterKeyType(promise): ' + JSON.stringify(editorAttribute.enterKeyType)); - }).catch((err) => { - console.error('getEditorAttribute promise err: ' + err.msg); - }); - } - ``` +```js +inputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}).catch((err) => { + console.error('Failed to getEditorAttribute: ' + JSON.stringify(err)); +}); +``` ### moveCursor9+ moveCursor(direction: number, callback: AsyncCallback<void>): void -Moves the cursor. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. +Moves the cursor. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1020,24 +1427,37 @@ Moves the cursor. This API uses an asynchronous callback to return the result. I | Name | Type | Mandatory| Description | | --------- | ------------------------- | ---- | -------------- | | direction | number | Yes | Direction in which the cursor moves.| -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error object. | + +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | **Example** ```js -TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => { - if (err === undefined) { - console.error('moveCursor callback result---err: ' + err.msg); - return; - } -}); +try { + inputClient.moveCursor(inputMethodEngine.CURSOR_UP, (err) => { + if (err !== undefined) { + console.error('Failed to moveCursor: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in moving cursor.'); + }); +} catch (err) { + console.error('Failed to moveCursor: ' + JSON.stringify(err)); +} ``` ### moveCursor9+ moveCursor(direction: number): Promise<void> -Moves the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. +Moves the cursor. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1053,21 +1473,31 @@ Moves the cursor. This API uses a promise to return the result. If the required | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Input Method Framework Error Codes](../errorcodes/errorcode-inputmethod-framework.md). + +| Error Code ID| Error Message | +| -------- | -------------------------- | +| 12800003 | Input method client error. | + **Example** - ```js -async function InputMethodEngine() { - await TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then(async (err) => { - console.log('moveCursor success'); +```js +try { + inputClient.moveCursor(inputMethodEngine.CURSOR_UP).then(() => { + console.log('Succeeded in moving cursor.'); }).catch((err) => { - console.error('moveCursor success err: ' + err.msg); + console.error('Failed to moveCursor: ' + JSON.stringify(err)); }); +} catch (err) { + console.log('Failed to moveCursor: ' + JSON.stringify(err)); } - ``` +``` -## EditorAttribute +## EditorAttribute -Describes the attribute of the edit box. +Attribute of the edit box. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -1076,7 +1506,7 @@ Describes the attribute of the edit box. | enterKeyType | number | Yes | No | Function attribute of the edit box.| | inputPattern | number | Yes | No | Text attribute of the edit box.| -## KeyEvent +## KeyEvent Describes the attribute of a key. @@ -1086,3 +1516,502 @@ Describes the attribute of a key. | --------- | -------- | ---- | ---- | ------------ | | keyCode | number | Yes | No | Key value.| | keyAction | number | Yes | No | Key status.| + +## TextInputClient(deprecated) + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [InputClient](#inputclient9). + +In the following API examples, you must first use **[on('inputStart')](#oninputstart)** to obtain a **TextInputClient** instance, and then call the APIs using the obtained instance. + +### getForward(deprecated) + +getForward(length:number, callback: AsyncCallback<string>): void + +Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getForward](#getforward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| +| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the obtained text. Otherwise, **err** is an error object.| + +**Example** + +```js +let length = 1; +textInputClient.getForward(length, (err, text) => { + if (err !== undefined) { + console.error('Failed to getForward: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in getting forward, text: ' + text); +}); +``` + +### getForward(deprecated) + +getForward(length:number): Promise<string> + +Obtains the specific-length text before the cursor. 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 [getForward](#getforward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise used to return the specific-length text before the cursor. | + +**Example** + +```js +let length = 1; +textInputClient.getForward(length).then((text) => { + console.info('Succeeded in getting forward, text: ' + text); +}).catch((err) => { + console.error('Failed to getForward: ' + JSON.stringify(err)); +}); +``` + +### getBackward(deprecated) + +getBackward(length:number, callback: AsyncCallback<string>): void + +Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getBackward](#getbackward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| +| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the obtained text. Otherwise, **err** is an error object.| + +**Example** + +```js +let length = 1; +textInputClient.getBackward(length, (err, text) => { + if (err !== undefined) { + console.error('Failed to getBackward: ' + JSON.stringify(err)); + return; + } + console.log('Succeeded in getting borward, text: ' + text); +}); +``` + +### getBackward(deprecated) + +getBackward(length:number): Promise<string> + +Obtains the specific-length text after the cursor. 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 [getBackward](#getbackward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<string> | Promise used to return the specific-length text after the cursor. | + +**Example** + +```js +let length = 1; +textInputClient.getBackward(length).then((text) => { + console.info('Succeeded in getting backward: ' + JSON.stringify(text)); +}).catch((err) => { + console.error('Failed to getBackward: ' + JSON.stringify(err)); +}); +``` + +### deleteForward(deprecated) + +deleteForward(length:number, callback: AsyncCallback<boolean>): void + +Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteForward](#deleteforward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| + +**Example** + +```js +let length = 1; +textInputClient.deleteForward(length, (err, result) => { + if (err !== undefined) { + console.error('Failed to deleteForward: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in deleting forward. '); + } else { + console.error('Failed to deleteForward. '); + } +}); +``` + +### deleteForward(deprecated) + +deleteForward(length:number): Promise<boolean> + +Deletes the fixed-length text before the cursor. 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 [deleteForward](#deleteforward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| length | number | Yes | Text length.| + +**Return value** + +| Type | Description | +| ---------------------- | -------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means that the deletion is successful, and **false** means the opposite.| + +**Example** + +```js +let length = 1; +textInputClient.deleteForward(length).then((result) => { + if (result) { + console.info('Succeeded in deleting forward. '); + } else { + console.error('Failed to delete forward. '); + } +}).catch((err) => { + console.error('Failed to delete forward: ' + JSON.stringify(err)); +}); +``` + +### deleteBackward(deprecated) + +deleteBackward(length:number, callback: AsyncCallback<boolean>): void + +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [deleteBackward](#deletebackward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + + **Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | -------------- | +| length | number | Yes | Text length. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| + + **Example** + +```js +let length = 1; +textInputClient.deleteBackward(length, (err, result) => { + if (err !== undefined) { + console.error('Failed to delete backward: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in deleting backward. '); + } else { + console.error('Failed to deleteBackward. '); + } +}); +``` + +### deleteBackward(deprecated) + +deleteBackward(length:number): Promise<boolean> + +Deletes the fixed-length text after the cursor. 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 [deleteBackward](#deletebackward9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| length | number | Yes| Text length.| + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the deletion is successful, and **false** means the opposite.| + +**Example** + +```js +let length = 1; +textInputClient.deleteBackward(length).then((result) => { + if (result) { + console.info('Succeeded in deleting backward. '); + } else { + console.error('Failed to deleteBackward. '); + } +}).catch((err) => { + console.error('Failed to deleteBackward: ' + JSON.stringify(err)); +}); +``` +### sendKeyFunction(deprecated) + +sendKeyFunction(action: number, callback: AsyncCallback<boolean>): void + +Sends the function key. 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 [sendKeyFunction](#sendkeyfunction9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + + **Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| + + **Example** + +```js +let action = 1; +textInputClient.sendKeyFunction(action, (err, result) => { + if (err !== undefined) { + console.error('Failed to sendKeyFunction: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in sending key function. '); + } else { + console.error('Failed to sendKeyFunction. '); + } +}); +``` + +### sendKeyFunction(deprecated) + +sendKeyFunction(action: number): Promise<boolean> + +Sends the function key. 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 [sendKeyFunction](#sendkeyfunction9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| action | number | Yes| Action of the function key.
**0**: invalid key.
**1**: confirm key (Enter key).| + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the setting is successful, and **false** means the opposite.| + +**Example** + +```js +let action = 1; +textInputClient.sendKeyFunction(action).then((result) => { + if (result) { + console.info('Succeeded in sending key function. '); + } else { + console.error('Failed to sendKeyFunction. '); + } +}).catch((err) => { + console.error('Failed to sendKeyFunction:' + JSON.stringify(err)); +}); +``` + +### insertText(deprecated) + +insertText(text:string, callback: AsyncCallback<boolean>): void + +Inserts text. 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 [insertText](#inserttext9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| text | string | Yes| Text to insert.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is **true**. Otherwise, **err** is an error object.| + +**Example** + +```js +textInputClient.insertText('test', (err, result) => { + if (err !== undefined) { + console.error('Failed to insertText: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Succeeded in inserting text. '); + } else { + console.error('Failed to insertText. '); + } +}); +``` + +### insertText(deprecated) + +insertText(text:string): Promise<boolean> + +Inserts text. 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 [insertText](#inserttext9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| text | string | Yes| Text to insert.| + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the insertion is successful, and **false** means the opposite.| + +**Example** + +```js +textInputClient.insertText('test').then((result) => { + if (result) { + console.info('Succeeded in inserting text. '); + } else { + console.error('Failed to insertText. '); + } +}).catch((err) => { + console.error('Failed to insertText: ' + JSON.stringify(err)); +}); +``` + +### getEditorAttribute(deprecated) + +getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void + +Obtains the attribute of the edit box. 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 [getEditorAttribute](#geteditorattribute9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory | Description | +| ------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ | +| callback | AsyncCallback<[EditorAttribute](#editorattribute)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the attribute of the edit box. Otherwise, **err** is an error object.| + +**Example** + +```js +textInputClient.getEditorAttribute((err, editorAttribute) => { + if (err !== undefined) { + console.error('Failed to getEditorAttribute: ' + JSON.stringify(err)); + return; + } + console.log('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.log('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}); +``` + +### getEditorAttribute(deprecated) + +getEditorAttribute(): Promise<EditorAttribute> + +Obtains the attribute of the edit box. 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 [getEditorAttribute](#geteditorattribute9). + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Return value** + +| Type | Description | +| ------------------------------- | ------------------------------------------------------------ | +| Promise<[EditorAttribute](#editorattribute)> | Promise used to return the attribute of the edit box. | + +**Example** + +```js +textInputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern: ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType: ' + JSON.stringify(editorAttribute.enterKeyType)); +}).catch((err) => { + console.error('Failed to getEditorAttribute: ' + 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 315e2d81f718bff6f6f1bc9b0ce813df11850da5..304fa76946de0e4279be5095bd1dae46f79c7ca6 100644 --- a/en/application-dev/reference/apis/js-apis-inputmonitor.md +++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md @@ -1,11 +1,11 @@ -# Input Monitor +# @ohos.multimodalInput.inputMonitor (Input Monitor) -The Input Monitor module implements listening for global touch events. +The **inputMonitor** module implements listening for events of input devices (namely, touchscreen and mouse). -> **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. +> **NOTE** > -> - The APIs of this module are system APIs and cannot be called by third-party applications. +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import @@ -16,80 +16,73 @@ import inputMonitor from '@ohos.multimodalInput.inputMonitor'; ``` -## Required Permissions - -ohos.permission.INPUT_MONITORING - - ## inputMonitor.on on(type: "touch", receiver: TouchEventReceiver): void Enables listening for global touch events. -This is a system API. - **Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------- | -| type | string | Yes | Type of the input event to listen for. The value is **touch**.| -| receiver | [TouchEventReceiver](#toucheventreceiver) | Yes | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------- | +| type | string | Yes | Type of the input device event. The value is **touch**.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | Yes | Callback used to return the touch event.| - **Example** +**Example** ```js try { - inputMonitor.on("touch", (data)=> { - console.info(`monitorOnTouchEvent success ${JSON.stringify(data)}`); - return false; - }); + inputMonitor.on("touch", (touchEvent) => { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; + }); } catch (error) { - console.info("onMonitor " + error.code + " " + error.message) + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` +## inputMonitor.on9+ + on(type: "mouse", receiver: Callback<MouseEvent>): void Enables listening for global mouse events. -This is a system API. - **Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------- | -| type | string | Yes | Type of the input event to listen for. The value is **mouse**.| -| receiver | Callback<MouseEvent> | Yes | Callback used to return the mouse event. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------- | ---- | ------------------- | +| type | string | Yes | Type of the input device event. The value is **mouse**.| +| receiver | Callback<MouseEvent> | Yes | Callback used to return the mouse event. | **Example** ```js try { - inputMonitor.on("mouse", (data)=> { - console.info(`monitorOnMouseEvent success ${JSON.stringify(data)}`); - return false; - }); + inputMonitor.on("mouse", (mouseEvent) => { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); + return false; + }); } catch (error) { - console.info("onMonitor " + error.code + " " + error.message) + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` + + ## inputMonitor.off off(type: "touch", receiver?: TouchEventReceiver): void -Stops listening for global touch events. - -This is a system API. +Disables listening for global touch events. **Required permissions**: ohos.permission.INPUT_MONITORING @@ -97,41 +90,48 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ----------------------------------------- | ---- | ------------------------------- | -| type | string | Yes | Type of the input event to listen for. The value is **touch**.| -| receiver | [TouchEventReceiver](#toucheventreceiver) | No | Callback used to return the touch event. | +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ------------------- | +| type | string | Yes | Type of the input device event. The value is **touch**.| +| receiver | [TouchEventReceiver](#toucheventreceiver) | No | Callback for which listening is disabled. If this parameter is not specified, listening will be disabled for all callbacks registered by the current application. | - **Example** +**Example** ```js -// Disable listening globally. +// Disable listening for a single callback function. +function callback(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; +}; try { - inputMonitor.off("touch"); + inputMonitor.on("touch", callback); + inputMonitor.off("touch", callback); + console.log(`Monitor off success`); } catch (error) { - console.info("offMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } -// Disable listening for this receiver. -callback:function(data) { - console.info(`call success ${JSON.stringify(data)}`); -}, -try { - inputMonitor.on("touch", this.callback); -} catch (error) { - console.info("onTouchMonitor " + error.code + " " + error.message) -}, +``` + +```js +// Cancel listening for all callback functions. +function callback(touchEvent) { + console.log(`Monitor on success ${JSON.stringify(touchEvent)}`); + return false; +}; try { - inputMonitor.off("touch",this.callback); + inputMonitor.on("touch", callback); + inputMonitor.off("touch"); + console.log(`Monitor off success`); } catch (error) { - console.info("offTouchMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` -off(type: "mouse", receiver?:Callback\):void +## inputMonitor.off9+ -Stops listening for global mouse events. +off(type: "mouse", receiver?: Callback<MouseEvent>): void -This is a system API. +Stops listening for global mouse events. **Required permissions**: ohos.permission.INPUT_MONITORING @@ -139,43 +139,48 @@ This is a system API. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ------------------------------- | -| type | string | Yes | Type of the input event to listen for. The value is **mouse**.| -| receiver | Callback<MouseEvent> | No | Callback used to return the mouse event. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------- | ---- | ------------------- | +| type | string | Yes | Type of the input device event. The value is **mouse**.| +| receiver | Callback<MouseEvent> | No | Callback for which listening is disabled. If this parameter is not specified, listening will be disabled for all callbacks registered by the current application.| **Example** ```js -// Disable listening globally. +// Disable listening for a single callback. +function callback(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); + return false; +}; try { - inputMonitor.off("mouse"); + inputMonitor.on("mouse", callback); + inputMonitor.off("mouse", callback); + console.log(`Monitor off success`); } catch (error) { - console.info("offMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } -// Disable listening for this receiver. -callback:function(data) { - console.info(`call success ${JSON.stringify(data)}`); -}, -try { - inputMonitor.on("mouse", this.callback); -} catch (error) { - console.info("onMouseMonitor " + error.code + " " + error.message) -}, +``` + +```js +// Disable listening for all callback functions. +function callback(mouseEvent) { + console.log(`Monitor on success ${JSON.stringify(mouseEvent)}`); + return false; +}; try { - inputMonitor.off("mouse", this.callback); + inputMonitor.on("mouse", callback); + inputMonitor.off("mouse"); + console.log(`Monitor off success`); } catch (error) { - console.info("offMouseMonitor " + error.code + " " + error.message) + console.log(`Monitor execute failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` - - ## TouchEventReceiver -Provides the callback of touch events. +Represents the callback used to return the touch event. -This is a system API. +**Required permissions**: ohos.permission.INPUT_MONITORING **System capability**: SystemCapability.MultimodalInput.Input.InputMonitor @@ -183,24 +188,26 @@ This is a system API. | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | -| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | Yes | Callback used to return the touch event.| +| touchEvent | [TouchEvent](../arkui-js/js-components-common-events.md) | Yes | Touch event.| **Return value** -| Type | Description | -| ------- | -------------------------------------- | -| Boolean | Result indicating whether the touch event has been consumed by the input monitor. The value **true** indicates that the touch event has been consumed, and the value **false** indicates the opposite.| +| Type | Description | +| ------- | ---------------------------------------- | +| Boolean | Result indicating whether the touch event will be dispatched to the window. The value **true** indicates that the touch event will be dispatched to the window, and the value **false** indicates the opposite.| - **Example** +**Example** ```js try { - inputMonitor.on("touch", (event) => { - // If true is returned, all subsequent events of this operation will be consumed by the listener, instead of being distributed to the window. - return false; + inputMonitor.on("touch", touchEvent => { + if (touchEvent.touches.length == 3) {// Three fingers are pressed. + return true; + } else { + return false; + } }); - inputMonitor.off("touch"); } catch (error) { - console.info("offMonitor " + error.code + " " + error.message) + console.log(`Monitor on failed, error: ${JSON.stringify(error, [`code`, `message`])}`); } ``` diff --git a/en/application-dev/reference/apis/js-apis-installer.md b/en/application-dev/reference/apis/js-apis-installer.md index 16db4d23910c6ee9a4b2862a6eb95f1b9f5f82f1..3dc9a22442c07759d3b594297f7828cb7d5cc95b 100644 --- a/en/application-dev/reference/apis/js-apis-installer.md +++ b/en/application-dev/reference/apis/js-apis-installer.md @@ -1,9 +1,8 @@ -# BundleInstaller +# @ohos.bundle.installer (installer) -The **BundleInstaller** module provides APIs for you to install, uninstall, and recover bundles on devices. +The **bundle.installer** module provides APIs for you to install, uninstall, and recover bundles on devices. > **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 @@ -18,7 +17,7 @@ import installer from '@ohos.bundle.installer'; | ------------------------------ | ----------- | ---------------- | | ohos.permission.INSTALL_BUNDLE | system_core | Permission to install or uninstall bundles.| -For details, see in [Permission Levels](../../security/accesstoken-overview.md#permission-levels). +For details, see [Permission Levels](../../security/accesstoken-overview.md#permission-levels). ## BundleInstaller.getBundleInstaller @@ -36,10 +35,6 @@ Obtains a **BundleInstaller** object. This API uses an asynchronous callback to | -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | callback | AsyncCallback\<[BundleInstaller](js-apis-installer.md#BundleInstaller)> | Yes | Callback used to return the result. If the operation is successful, **err** is undefined and **data** is the **BundleInstaller** object obtained; otherwise, **err** is an error object.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts @@ -73,10 +68,6 @@ Obtains a **BundleInstaller** object. This API uses an asynchronous callback to | ------------------------------------------------------------ | ------------------------------------ | | Promise\<[BundleInstaller](js-apis-installer.md#BundleInstaller)> | Promise used to return the **BundleInstaller** object obtained.| -**Error codes** - -For details about the error codes, see [Bundle Error Codes](../errorcodes/errorcode-bundle.md). - **Example** ```ts @@ -278,10 +269,10 @@ Defines the hash parameters for bundle installation and uninstall. **System API**: This is a system API and cannot be called by third-party applications. -| Name | Type | Description | -| ---------- | ------ | ---------------- | -| moduleName | string | Module name of the bundle.| -| hashValue | string | Hash value. | +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---------------- | ---------------- | +| moduleName | string | Yes| Module name of the bundle.| +| hashValue | string | Yes| Hash value. | ## InstallParam @@ -291,10 +282,10 @@ Defines the parameters that need to be specified for bundle installation, uninst **System API**: This is a system API and cannot be called by third-party applications. -| Name | Type | Description | -| ------------------------------ | ------------------------------ | ------------------ | -| userId | number | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#queryosaccountlocalidfromprocess9) to obtain the user of the current process.| -| installFlag | number | Installation flag. The value **0** means initial installation and **1** means overwrite installation.| -| isKeepData | boolean | Whether to retain the data directory during bundle uninstall.| -| hashParams | Array<[HashParam](#hashparam)> | Hash parameters. | -| crowdtestDeadline| number |End date of crowdtesting.| +| Name | Type | Mandatory | Description | +| ------------------------------ | ------------------------------ | ------------------ | ------------------ | +| userId | number | Yes | User ID. You can use [queryOsAccountLocalIdFromProcess](js-apis-osAccount.md#queryosaccountlocalidfromprocess9) to obtain the user of the current process.| +| installFlag | number | Yes | Installation flag. The value **0** means initial installation and **1** means overwrite installation.| +| isKeepData | boolean | Yes | Whether to retain the data directory during bundle uninstall.| +| hashParams | Array<[HashParam](#hashparam)> | Yes| Hash parameters. | +| crowdtestDeadline| number | Yes |End date of crowdtesting.| diff --git a/en/application-dev/reference/apis/js-apis-intl.md b/en/application-dev/reference/apis/js-apis-intl.md index 79cdf3ac5627984eba2f03e7eb37b9cc7137de4a..d4f3449adae43eed9b19236aec0d0308feed89e8 100644 --- a/en/application-dev/reference/apis/js-apis-intl.md +++ b/en/application-dev/reference/apis/js-apis-intl.md @@ -1,20 +1,20 @@ -# Internationalization – Intl +# @ohos.intl (Internationalization) -This module provides basic I18N capabilities, such as time and date formatting, number formatting, and string sorting, through the standard I18N APIs defined in ECMA 402. - -The [I18N](js-apis-i18n.md) module provides enhanced I18N capabilities through supplementary APIs that are not defined in ECMA 402. It works with the Intl module to provide a complete suite of I18N capabilities. +The **intl** module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n APIs defined in ECMA 402. +The [i18n](js-apis-i18n.md) module provides enhanced i18n capabilities through supplementary interfaces that are not defined in ECMA 402. It works with the intl module to provide a complete suite of i18n capabilities. > **NOTE** -> -> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> - This module provides basic i18n capabilities, such as time and date formatting, number formatting, and string sorting, through the standard i18n interfaces defined in ECMA 402. For details about the enhanced i18n capabilities, see [i18n](js-apis-i18n.md). ## Modules to Import -``` +```js import Intl from '@ohos.intl'; ``` - +Importing an incorrect bundle can lead to unexpected API behavior. ## Locale @@ -23,16 +23,16 @@ import Intl from '@ohos.intl'; **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | language | string | Yes | No | Language associated with the locale, for example, **zh**. | | script | string | Yes | No | Script type of the language, for example, **Hans**. | | region | string | Yes | No | Region associated with the locale, for example, **CN**. | | baseName | string | Yes | No | Basic key information about the locale, which consists of the language, script, and region, for example, **zh-Hans-CN**. | | caseFirst | string | Yes | No | Whether case is taken into account for the locale's collation rules. The value can be **upper**, **lower**, or **false**.| -| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| +| calendar | string | Yes | No | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| | collation | string | Yes | No | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, **h24**.| +| hourCycle | string | Yes | No | Time system for the locale. The value can be any of the following: **h12**, **h23**, **h11**, or **h24**.| | numberingSystem | string | Yes | No | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | No | Whether to apply special collation rules for numeric characters. | @@ -41,13 +41,16 @@ import Intl from '@ohos.intl'; constructor() -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var locale = new Intl.Locale(); + ```js + // The default constructor uses the current system locale to create a Locale object. + let locale = new Intl.Locale() + // Return the current system locale. + let localeID = locale.toString() ``` @@ -55,20 +58,22 @@ Creates a Locale object. constructor(locale: string, options?: LocaleOptions) -Creates a Locale object. +Creates a **Locale** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------------- | ---- | ---------------------------- | -| locale | string | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [LocaleOptions](#localeoptions9) | No | Options for creating the **Locale** object. | +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string | Yes | A string containing locale information, including the language, optional script, and region. For details about the international standards and combination modes for the language, script, and country or region, see [intl Development](../../internationalization/intl-guidelines.md#setting-locale-information).| +| options9+ | [LocaleOptions](#localeoptions6) | No | Options for creating the **Locale** object. | **Example** - ``` - var locale = new Intl.Locale("zh-CN"); + ```js + // Create a Locale object named zh-CN. + let locale = new Intl.Locale("zh-CN") + let localeID = locale.toString() // localeID = "zh-CN" ``` @@ -76,20 +81,21 @@ Creates a Locale object. toString(): string -Converts locale information to a string. +Obtains the string representation of a **Locale** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ------ | ----------- | -| string | String containing locale information.| +| string | String representation of the **Locale** object.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.toString(); + ```js + // Create a Locale object named en-GB. + let locale = new Intl.Locale("en-GB"); + let localeID = locale.toString(); // localeID = "en-GB" ``` @@ -101,16 +107,25 @@ Maximizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the maximized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.maximize(); + ```js + // Create a Locale object named zh. + let locale = new Intl.Locale("zh"); + // Complete the script and region of the Locale object. + let maximizedLocale = locale.maximize(); + let localeID = maximizedLocale.toString(); // localeID = "zh-Hans-CN" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Complete the script of the Locale object. + maximizedLocale = locale.maximize(); + localeID = maximizedLocale.toString(); // localeID = "en-Latn-US" ``` @@ -122,30 +137,39 @@ Minimizes information of the **Locale** object. If the script and locale informa **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ----------------- | ---------- | | [Locale](#locale) | **Locale** object with the minimized information.| **Example** - ``` - var locale = new Intl.Locale("zh-CN"); - locale.minimize(); + ```js + // Create a Locale object named zh-Hans-CN. + let locale = new Intl.Locale("zh-Hans-CN"); + // Remove the script and region of the Locale object. + let minimizedLocale = locale.minimize(); + let localeID = minimizedLocale.toString(); // localeID = "zh" + + // Create a Locale object named en-US. + locale = new Intl.Locale("en-US"); + // Remove the region of the Locale object. + minimizedLocale = locale.minimize(); + localeID = minimizedLocale.toString(); // localeID = "en" ``` -## LocaleOptions9+ +## LocaleOptions6+ Represents the locale options. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | -| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, **islamicc**.| -| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**,**search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| calendar | string | Yes | Yes | Calendar for the locale. The value can be any of the following: **buddhist**, **chinese**, **coptic**, **dangi**, **ethioaa**, **ethiopic**, **gregory**, **hebrew**, **indian**, **islamic**, **islamic-umalqura**, **islamic-tbla**, **islamic-civil**, **islamic-rgsa**, **iso8601**, **japanese**, **persian**, **roc**, or **islamicc**.| +| collation | string | Yes | Yes | Collation rule. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **emoji**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **search**, **searchjl**, **standard**, **stroke**, **trad**, **unihan**, **zhuyin**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | numeric | boolean | Yes | Yes | Whether to use the 12-hour clock. | | caseFirst | string | Yes | Yes | Whether upper case or lower case is sorted first. The value can be **upper**, **lower**, or **false**.| @@ -163,8 +187,9 @@ Creates a **DateTimeOptions** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var datefmt= new Intl.DateTimeFormat(); + ```js + // Use the current system locale to create a DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(); ``` @@ -178,20 +203,22 @@ Creates a **DateTimeOptions** object for the specified locale. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [DateTimeOptions](#datetimeoptions9) | No | Options for creating a **DateTimeFormat** object. | +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [DateTimeOptions](#datetimeoptions6) | No | Options for creating a **DateTimeFormat** object. | **Example** - ``` - var datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use locale zh-CN to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + let datefmt= new Intl.DateTimeFormat("zh-CN", { dateStyle: 'full', timeStyle: 'medium' }); ``` **Example** - ``` - var datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); + ```js + // Use the locale list ["ban", "zh"] to create a DateTimeFormat object. Because ban is an invalid locale ID, locale zh is used to create the DateTimeFormat object. + let datefmt= new Intl.DateTimeFormat(["ban", "zh"], { dateStyle: 'full', timeStyle: 'medium' }); ``` @@ -209,17 +236,22 @@ Formats the specified date and time. | ---- | ---- | ---- | ------- | | date | Date | Yes | Date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ------------ | | string | A string containing the formatted date and time.| **Example** - ``` - var date = new Date(2021, 11, 17, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.format(date); + ```js + let date = new Date(2021, 11, 17, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDate = datefmt.format(date); // formattedDate "17/12/2021" + + // Use locale en-GB to create a DateTimeFormat object. Set dateStyle to full and timeStyle to medium. + datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + formattedDate = datefmt.format(date); // formattedDate "Friday, 17 December 2021 at 03:24:00" ``` @@ -238,18 +270,19 @@ Formats the specified date range. | startDate | Date | Yes | Start date and time to be formatted.| | endDate | Date | Yes | End date and time to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | -------------- | | string | A string containing the formatted date and time range.| **Example** - ``` - var startDate = new Date(2021, 11, 17, 3, 24, 0); - var endDate = new Date(2021, 11, 18, 3, 24, 0); - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.formatRange(startDate, endDate); + ```js + let startDate = new Date(2021, 11, 17, 3, 24, 0); + let endDate = new Date(2021, 11, 18, 3, 24, 0); + // Use locale en-GB to create a DateTimeFormat object. + let datefmt = new Intl.DateTimeFormat("en-GB"); + let formattedDateRange = datefmt.formatRange(startDate, endDate); // formattedDateRange = "17/12/2021-18/12/2021" ``` @@ -261,31 +294,34 @@ Obtains the formatting options for **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------------------- | -| [DateTimeOptions](#datetimeoptions9) | Formatting options for **DateTimeFormat** objects.| +| Type | Description | +| ------------------------------------ | ----------------------------- | +| [DateTimeOptions](#datetimeoptions6) | Formatting options for **DateTimeFormat** objects.| **Example** - ``` - var datefmt = new Intl.DateTimeFormat("en-GB"); - datefmt.resolvedOptions(); + ```js + let datefmt = new Intl.DateTimeFormat("en-GB", { dateStyle: 'full', timeStyle: 'medium' }); + // Obtain the options of the DateTimeFormat object. + let options = datefmt.resolvedOptions(); + let dateStyle = options.dateStyle; // dateStyle = "full" + let timeStyle = options.timeStyle; // timeStyle = "medium" ``` -## DateTimeOptions9+ +## DateTimeOptions6+ Provides the options for the **DateTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | dateStyle | string | Yes | Yes | Date display format. The value can be **long**, **short**, **medium**, or **full**.| | timeStyle | string | Yes | Yes | Time display format. The value can be **long**, **short**, **medium**, or **full**.| -| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, **h24**.| +| hourCycle | string | Yes | Yes | Time system for the locale. The value can be any of the following: **h11**, **h12**, **h23**, or **h24**.| | timeZone | string | Yes | Yes | Time zone represented by a valid IANA time zone ID. | | numberingSystem | string | Yes | Yes | Numbering system for the locale. The value can be any of the following: **adlm**, **ahom**, **arab**, **arabext**, **bali**, **beng**, **bhks**, **brah**, **cakm**, **cham**, **deva**, **diak**, **fullwide**, **gong**, **gonm**, **gujr**, **guru**, **hanidec**, **hmng**, **hmnp**, **java**, **kali**, **khmr**, **knda**, **lana**, **lanatham**, **laoo**, **latn**, **lepc**, **limb**, **mathbold**, **mathdbl**, **mathmono**, **mathsanb**, **mathsans**, **mlym**, **modi**, **mong**, **mroo**, **mtei**, **mymr**, **mymrshan**, **mymrtlng**, **newa**, **nkoo**, **olck**, **orya**, **osma**, **rohg**, **saur**, **segment**, **shrd**, **sind**, **sinh**, **sora**, **sund**, **takr**, **talu**, **tamldec**, **telu**, **thai**, **tibt**, **tirh**, **vaii**, **wara**, **wcho**.| | hour12 | boolean | Yes | Yes | Whether to use the 12-hour clock. | @@ -315,8 +351,9 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var numfmt = new Intl.NumberFormat(); + ```js + // Use the current system locale to create a NumberFormat object. + let numfmt = new Intl.NumberFormat(); ``` @@ -328,15 +365,17 @@ Creates a **NumberFormat** object for the specified locale. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [NumberOptions](#numberoptions9) | No | Options for creating a **NumberFormat** object. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | -------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [NumberOptions](#numberoptions6) | No | Options for creating a **NumberFormat** object. | **Example** - ``` - var numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); + ```js + // Use locale en-GB to create a NumberFormat object. Set style to decimal and notation to scientific. + let numfmt = new Intl.NumberFormat("en-GB", {style:'decimal', notation:"scientific"}); ``` @@ -354,7 +393,7 @@ Formats a number. | ------ | ------ | ---- | ---- | | number | number | Yes | Number to be formatted.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | @@ -362,9 +401,10 @@ Formats a number. **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.format(1223); + ```js + // Use locale list ["en-GB", "zh"] to create a NumberFormat object. Because en-GB is a valid locale ID, it is used to create the NumberFormat object. + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + let formattedNumber = numfmt.format(1223); // formattedNumber = 1.223E3 ``` @@ -376,27 +416,30 @@ Obtains the options of the **NumberFormat** object. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ------------------------------- | --------------------------- | -| [NumberOptions](#numberoptions9) | Formatting options for **NumberFormat** objects.| +| Type | Description | +| -------------------------------- | --------------------------- | +| [NumberOptions](#numberoptions6) | Formatting options for **NumberFormat** objects.| **Example** - ``` - var numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); - numfmt.resolvedOptions(); + ```js + let numfmt = new Intl.NumberFormat(["en-GB", "zh"], {style:'decimal', notation:"scientific"}); + // Obtain the options of the NumberFormat object. + let options = numfmt.resolvedOptions(); + let style = options.style; // style = decimal + let notation = options.notation // notation = scientific ``` -## NumberOptions9+ +## NumberOptions6+ -Provides the device capability. +Defines the device capability. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------- | ---- | ---- | ---------------------------------------- | | locale | string | Yes | No | Locale, for example, **zh-Hans-CN**. | | currency | string | Yes | Yes | Currency unit, for example, **EUR**, **CNY**, or **USD**. | @@ -426,13 +469,14 @@ Provides the device capability. constructor() -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var collator = new Intl.Collator(); + ```js + // Use the system locale to create a Collator object. + let collator = new Intl.Collator(); ``` @@ -440,20 +484,21 @@ Creates a Collator object. constructor(locale: string | Array<string>, options?: CollatorOptions) -Creates a Collator object. +Creates a **Collator** object. **System capability**: SystemCapability.Global.I18n **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [CollatorOptions](#collatoroptions9) | No | Options for creating a **Collator** object. | +| Name | Type | Mandatory | Description | +| -------------------- | ------------------------------------ | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [CollatorOptions](#collatoroptions8) | No | Options for creating a **Collator** object. | **Example** - ``` - var collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); + ```js + // Use locale zh-CN to create a Collator object. Set localeMatcher to lookup and usage to sort. + let collator = new Intl.Collator("zh-CN", {localeMatcher: "lookup", usage: "sort"}); ``` @@ -472,16 +517,18 @@ Compares two strings based on the sorting policy of the **Collator** object. | first | string | Yes | First string to compare. | | second | string | Yes | Second string to compare.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | number | Comparison result. If the value is a negative number, the first string is before the second string. If the value of number is **0**, the first string is equal to the second string. If the value of number is a positive number, the first string is after the second string.| **Example** - ``` - var collator = new Intl.Collator("zh-Hans"); - collator.compare("first", "second"); + ```js + // Use locale en-GB to create a Collator object. + let collator = new Intl.Collator("en-GB"); + // Compare the sequence of the first and second strings. + let compareResult = collator.compare("first", "second"); // compareResult = -1 ``` @@ -493,31 +540,33 @@ Returns properties reflecting the locale and collation options of a **Collator** **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** -| Type | Description | -| ----------------------------------- | ----------------- | -| [CollatorOptions](#collatoroptions9) | Properties of the **Collator** object.| +| Type | Description | +| ------------------------------------ | ----------------- | +| [CollatorOptions](#collatoroptions8) | Properties of the **Collator** object.| **Example** - - ``` - var collator = new Intl.Collator("zh-Hans"); - var options = collator.resolvedOptions(); + ```js + let collator = new Intl.Collator("zh-Hans", { usage: 'sort', ignorePunctuation: true }); + // Obtain the options of the Collator object. + let options = collator.resolvedOptions(); + let usage = options.usage; // usage = "sort" + let ignorePunctuation = options.ignorePunctuation // ignorePunctuation = true ``` -## CollatorOptions9+ +## CollatorOptions8+ Represents the properties of a **Collator** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ----------------- | ------- | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | usage | string | Yes | Yes | Whether the comparison is for sorting or for searching. The value can be **sort** or **search**. | -| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **variant**.| +| sensitivity | string | Yes | Yes | Differences in the strings that lead to non-zero return values. The value can be **base**, **accent**, **case**, or **letiant**.| | ignorePunctuation | boolean | Yes | Yes | Whether punctuation is ignored. The value can be **true** or **false**. | | collation | string | Yes | Yes | Rule for sorting regions. The value can be any of the following: **big5han**, **compat**, **dict**, **direct**, **ducet**, **eor**, **gb2312**, **phonebk**, **phonetic**, **pinyin**, **reformed**, **searchjl**, **stroke**, **trad**, **unihan**, **zhuyin**.| | numeric | boolean | Yes | Yes | Whether numeric collation is used. The value can be **true** or **false**. | @@ -531,13 +580,14 @@ Represents the properties of a **Collator** object. constructor() -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var pluralRules = new Intl.PluralRules(); + ```js + // Use the system locale to create a PluralRules object. + let pluralRules = new Intl.PluralRules(); ``` @@ -545,19 +595,21 @@ Create a **PluralRules** object. constructor(locale: string | Array<string>, options?: PluralRulesOptions) -Create a **PluralRules** object. +Creates a **PluralRules** object to obtain the singular-plural type of numbers. **System capability**: SystemCapability.Global.I18n -Parameters -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [PluralRulesOptions](#pluralrulesoptions9) | No | Options for creating a **PluralRules** object. | +**Parameters** + +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [PluralRulesOptions](#pluralrulesoptions8) | No | Options for creating a **PluralRules** object. | **Example** - ``` - var pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); + ```js + // Use locale zh-CN to create a PluralRules object. Set localeMatcher to lookup and type to cardinal. + let pluralRules= new Intl.PluralRules("zh-CN", {"localeMatcher": "lookup", "type": "cardinal"}); ``` @@ -575,26 +627,33 @@ Obtains a string that represents the singular-plural type of the specified numbe | ---- | ------ | ---- | ------------ | | n | number | Yes | Number for which the singular-plural type is to be obtained.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------------------------------------- | | string | Singular-plural type. The value can be any of the following: **one**, **two**, **few**, **many**, **others**.| **Example** - ``` - var pluralRules = new Intl.PluralRules("zh-Hans"); - pluralRules.select(1); + ```js + // Use locale zh-Hans to create a PluralRules object. + let zhPluralRules = new Intl.PluralRules("zh-Hans"); + // Determine the singular-plural type corresponding to number 1 in locale zh-Hans. + let plural = zhPluralRules.select(1); // plural = other + + // Use locale en-US to create a PluralRules object. + let enPluralRules = new Intl.PluralRules("en-US"); + // Determine the singular-plural type corresponding to number 1 in locale en-US. + plural = enPluralRules.select(1); // plural = one ``` -## PluralRulesOptions9+ +## PluralRulesOptions8+ Represents the properties of a **PluralRules** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------------------ | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | type | string | Yes | Yes | Sorting type. The value can be **cardinal** or **ordinal**. | @@ -617,8 +676,9 @@ Creates a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat(); + ```js + // Use the system locale to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat(); ``` @@ -632,14 +692,15 @@ Creates a **RelativeTimeFormat** object. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ---------------------------------------- | ---- | ---------------------------- | -| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| -| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions9) | No | Options for creating a **RelativeTimeFormat** object. | +| Name | Type | Mandatory | Description | +| -------------------- | ---------------------------------------- | ---- | ---------------------------- | +| locale | string \| Array<string> | Yes | A string containing locale information, including the language, optional script, and region.| +| options9+ | [RelativeTimeFormatInputOptions](#relativetimeformatinputoptions8) | No | Options for creating a **RelativeTimeFormat** object. | **Example** - ``` - var relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. Set localeMatcher to lookup, numeric to always, and style to long. + let relativeTimeFormat = new Intl.RelativeTimeFormat("zh-CN", {"localeMatcher": "lookup", "numeric": "always", "style": "long"}); ``` @@ -658,16 +719,18 @@ Formats the value and unit based on the specified locale and formatting options. | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------ | ---------- | | string | Relative time after formatting.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); - relativetimefmt.format(3, "quarter") + ```js + // Use locale zh-CN to create a RelativeTimeFormat object. + let relativetimefmt = new Intl.RelativeTimeFormat("zh-CN"); + // Obtain the localized representation (in unit of quarter) of number 3 in locale zh-CN. + let formatResult = relativetimefmt.format(3, "quarter"); // formatResult = "3 quarters later" ``` @@ -675,7 +738,7 @@ Formats the value and unit based on the specified locale and formatting options. formatToParts(value: number, unit: string): Array<object> -Returns an array of RelativeTimeFormat objects in parts for locale-aware formatting. +Obtains an array of RelativeTimeFormat objects in parts for locale-aware formatting. **System capability**: SystemCapability.Global.I18n @@ -686,16 +749,17 @@ Returns an array of RelativeTimeFormat objects in parts for locale-aware formatt | value | number | Yes | Value to format. | | unit | string | Yes | Unit to format. The value can be any of the following: **year**, **quarter**, **month**, **week**, **day**, **hour**, **minute**, **second**.| -**Return Value** +**Return value** | Type | Description | | ------------------- | --------------------------- | | Array<object> | An array of **RelativeTimeFormat** objects in parts.| **Example** - ``` - var relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); - var parts = relativetimefmt.format(10, "seconds"); + ```js + // Use locale en to create a RelativeTimeFormat object. Set numeric to auto. + let relativetimefmt = new Intl.RelativeTimeFormat("en", {"numeric": "auto"}); + let parts = relativetimefmt.formatToParts(10, "seconds"); // parts = [ {type: "literal", value: "in"}, {type: "integer", value: 10, unit: "second"}, {type: "literal", value: "seconds"} ] ``` @@ -707,39 +771,42 @@ Obtains the formatting options for **RelativeTimeFormat** objects. **System capability**: SystemCapability.Global.I18n -**Return Value** +**Return value** | Type | Description | | ---------------------------------------- | --------------------------------- | | [RelativeTimeFormatResolvedOptions](#relativetimeformatresolvedoptions8) | Formatting options for **RelativeTimeFormat** objects.| **Example** - ``` - var relativetimefmt= new Intl.RelativeTimeFormat("en-GB"); - relativetimefmt.resolvedOptions(); + ```js + // Use locale en-GB to create a RelativeTimeFormat object. + let relativetimefmt= new Intl.RelativeTimeFormat("en-GB", { style: "short" }); + // Obtain the options of the RelativeTimeFormat object. + let options = relativetimefmt.resolvedOptions(); + let style = options.style; // style = "short" ``` -## RelativeTimeFormatInputOptions9+ +## RelativeTimeFormatInputOptions8+ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | ------------- | ------ | ---- | ---- | ---------------------------------------- | | localeMatcher | string | Yes | Yes | Locale matching algorithm. The value can be **lookup** or **best fit**.| | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | | style | string | Yes | Yes | Length of an internationalized message. The value can be **long**, **short**, or **narrow**.| -## RelativeTimeFormatResolvedOptions8+ +## RelativeTimeFormatResolvedOptions8+ Represents the properties of a **RelativeTimeFormat** object. **System capability**: SystemCapability.Global.I18n -| Name | Type | Readable | Writable | Description | +| Name | Type | Readable | Writable | Description | | --------------- | ------ | ---- | ---- | ---------------------------------------- | | locale | string | Yes | Yes | A string containing locale information, including the language, optional script, and region. | | numeric | string | Yes | Yes | Format of the output message. The value can be **always** or **auto**. | diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md index dd4ac0b22afb7e0101579db5b6d639504f58197d..e69775942629948eab964f4f91795ddfe7dfeda7 100644 --- a/en/application-dev/reference/apis/js-apis-keycode.md +++ b/en/application-dev/reference/apis/js-apis-keycode.md @@ -1,349 +1,350 @@ -# Keycode +# @ohos.multimodalInput.keyCode (Key Code) -The Keycode module provides keycodes for a key device. +The **keyCode** module provides keycodes for a key device. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import ```js -import {KeyCode} from '@ohos.multimodalInput.keyCode' +import {KeyCode} from '@ohos.multimodalInput.keyCode'; ``` ## KeyCode **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| KEYCODE_FN | number | Yes| No| Function (Fn) key| -| KEYCODE_UNKNOWN | number | Yes| No| Unknown key| -| KEYCODE_HOME | number | Yes| No| Home key | -| KEYCODE_BACK | number | Yes| No| Back key| -| KEYCODE_MEDIA_PLAY_PAUSE | number | Yes| No| Play/Pause key| -| KEYCODE_MEDIA_STOP | number | Yes| No| Stop key| -| KEYCODE_MEDIA_NEXT | number | Yes| No| Next key| -| KEYCODE_MEDIA_PREVIOUS | number | Yes| No| Previous key| -| KEYCODE_MEDIA_REWIND | number | Yes| No| Rewind key| -| KEYCODE_MEDIA_FAST_FORWARD | number | Yes| No| Fast Forward key| -| KEYCODE_VOLUME_UP | number | Yes| No| Volume Up key| -| KEYCODE_VOLUME_DOWN | number | Yes| No| Volume Down key| -| KEYCODE_POWER | number | Yes| No| Power key| -| KEYCODE_CAMERA | number | Yes| No| Camera key| -| KEYCODE_VOLUME_MUTE | number | Yes| No| Speaker Mute key| -| KEYCODE_MUTE | number | Yes| No| Mute key| -| KEYCODE_BRIGHTNESS_UP | number | Yes| No| Brightness Up key| -| KEYCODE_BRIGHTNESS_DOWN | number | Yes| No| Brightness Down key| -| KEYCODE_0 | number | Yes| No| Key 0| -| KEYCODE_1 | number | Yes| No| Key 1| -| KEYCODE_2 | number | Yes| No| Key 2| -| KEYCODE_3 | number | Yes| No| Key 3| -| KEYCODE_4 | number | Yes| No| Key 4| -| KEYCODE_5 | number | Yes| No| Key 5| -| KEYCODE_6 | number | Yes| No| Key 6| -| KEYCODE_7 | number | Yes| No| Key 7| -| KEYCODE_8 | number | Yes| No| Key 8| -| KEYCODE_9 | number | Yes| No| Key 9| -| KEYCODE_STAR | number | Yes| No| Key *| -| KEYCODE_POUND | number | Yes| No| Key #| -| KEYCODE_DPAD_UP | number | Yes| No| Up key on D-pad| -| KEYCODE_DPAD_DOWN | number | Yes| No| Down key on D-pad| -| KEYCODE_DPAD_LEFT | number | Yes| No| Left key on D-pad| -| KEYCODE_DPAD_RIGHT | number | Yes| No| Right key on D-pad| -| KEYCODE_DPAD_CENTER | number | Yes| No| Center key on D-pad| -| KEYCODE_A | number | Yes| No| Key A| -| KEYCODE_B | number | Yes| No| Key B| -| KEYCODE_C | number | Yes| No| Key C| -| KEYCODE_D | number | Yes| No| Key D| -| KEYCODE_E | number | Yes| No| Key E| -| KEYCODE_F | number | Yes| No| Key F| -| KEYCODE_G | number | Yes| No| Key G| -| KEYCODE_H | number | Yes| No| Key H| -| KEYCODE_I | number | Yes| No| Key I| -| KEYCODE_J | number | Yes| No| Key J| -| KEYCODE_K | number | Yes| No| Key K| -| KEYCODE_L | number | Yes| No| Key L| -| KEYCODE_M | number | Yes| No| Key M| -| KEYCODE_N | number | Yes| No| Key N| -| KEYCODE_O | number | Yes| No| Key O| -| KEYCODE_P | number | Yes| No| Key P| -| KEYCODE_Q | number | Yes| No| Key Q| -| KEYCODE_R | number | Yes| No| Key R| -| KEYCODE_S | number | Yes| No| Key S| -| KEYCODE_T | number | Yes| No| Key T| -| KEYCODE_U | number | Yes| No| Key U| -| KEYCODE_V | number | Yes| No| Key V| -| KEYCODE_W | number | Yes| No| Key W| -| KEYCODE_X | number | Yes| No| Key X| -| KEYCODE_Y | number | Yes| No| Key Y| -| KEYCODE_Z | number | Yes| No| Key Z| -| KEYCODE_COMMA | number | Yes| No| Key ,| -| KEYCODE_PERIOD | number | Yes| No| Key .| -| KEYCODE_ALT_LEFT | number | Yes| No| Alt+Left key| -| KEYCODE_ALT_RIGHT | number | Yes| No| Alt+Right key| -| KEYCODE_SHIFT_LEFT | number | Yes| No| Shift+Left key| -| KEYCODE_SHIFT_RIGHT | number | Yes| No| Shift+Right key| -| KEYCODE_TAB | number | Yes| No| Tab key| -| KEYCODE_SPACE | number | Yes| No| Space key| -| KEYCODE_SYM | number | Yes| No| Symbol key| -| KEYCODE_EXPLORER | number | Yes| No| Explorer key, which is used to start the explorer application| -| KEYCODE_ENVELOPE | number | Yes| No| Email key, which is used to start the email application| -| KEYCODE_ENTER | number | Yes| No| Enter key| -| KEYCODE_DEL | number | Yes| No| Delete key| -| KEYCODE_GRAVE | number | Yes| No| Key `| -| KEYCODE_MINUS | number | Yes| No| Key -| -| KEYCODE_EQUALS | number | Yes| No| Key =| -| KEYCODE_LEFT_BRACKET | number | Yes| No| Key [| -| KEYCODE_RIGHT_BRACKET | number | Yes| No| Key ]| -| KEYCODE_BACKSLASH | number | Yes| No| Key \\| -| KEYCODE_SEMICOLON | number | Yes| No| Key ;| -| KEYCODE_APOSTROPHE | number | Yes| No| Key ' | -| KEYCODE_SLASH | number | Yes| No| Key /| -| KEYCODE_AT | number | Yes| No| Key @| -| KEYCODE_PLUS | number | Yes| No| Key +| -| KEYCODE_MENU | number | Yes| No| Menu key| -| KEYCODE_PAGE_UP | number | Yes| No| Page Up key| -| KEYCODE_PAGE_DOWN | number | Yes| No| Page Down key| -| KEYCODE_ESCAPE | number | Yes| No| ESC key| -| KEYCODE_FORWARD_DEL | number | Yes| No| Delete key| -| KEYCODE_CTRL_LEFT | number | Yes| No| Control+Left | -| KEYCODE_CTRL_RIGHT | number | Yes| No| Control+Right | -| KEYCODE_CAPS_LOCK | number | Yes| No| Caps Lock key| -| KEYCODE_SCROLL_LOCK | number | Yes| No| Scroll Lock key| -| KEYCODE_META_LEFT | number | Yes| No| Left Meta key| -| KEYCODE_META_RIGHT | number | Yes| No| Right Meta key| -| KEYCODE_FUNCTION | number | Yes| No| Function key| -| KEYCODE_SYSRQ | number | Yes| No| System Request/Print Screen key| -| KEYCODE_BREAK | number | Yes| No| Break/Pause key| -| KEYCODE_MOVE_HOME | number | Yes| No| Move to Home key| -| KEYCODE_MOVE_END | number | Yes| No| Move to End key| -| KEYCODE_INSERT | number | Yes| No| Insert key| -| KEYCODE_FORWARD | number | Yes| No| Delete key | -| KEYCODE_MEDIA_PLAY | number | Yes| No| Play key| -| KEYCODE_MEDIA_PAUSE | number | Yes| No| Pause key| -| KEYCODE_MEDIA_CLOSE | number | Yes| No| Close key| -| KEYCODE_MEDIA_EJECT | number | Yes| No| Eject key| -| KEYCODE_MEDIA_RECORD | number | Yes| No| Record key| -| KEYCODE_F1 | number | Yes| No| F1 key| -| KEYCODE_F2 | number | Yes| No| F2 key| -| KEYCODE_F3 | number | Yes| No| F3 key| -| KEYCODE_F4 | number | Yes| No| F4 key| -| KEYCODE_F5 | number | Yes| No| F5 key| -| KEYCODE_F6 | number | Yes| No| F6 key| -| KEYCODE_F7 | number | Yes| No| F7 key| -| KEYCODE_F8 | number | Yes| No| F8 key| -| KEYCODE_F9 | number | Yes| No| F9 key| -| KEYCODE_F10 | number | Yes| No| F10 key| -| KEYCODE_F11 | number | Yes| No| F11 key| -| KEYCODE_F12 | number | Yes| No| F12 key| -| KEYCODE_NUM_LOCK | number | Yes| No| Number Lock key| -| KEYCODE_NUMPAD_0 | number | Yes| No| Key 0 on numeric keypad| -| KEYCODE_NUMPAD_1 | number | Yes| No| Key 1 on numeric keypad| -| KEYCODE_NUMPAD_2 | number | Yes| No| Key 2 on numeric keypad| -| KEYCODE_NUMPAD_3 | number | Yes| No| Key 3 on numeric keypad| -| KEYCODE_NUMPAD_4 | number | Yes| No| Key 4 on numeric keypad| -| KEYCODE_NUMPAD_5 | number | Yes| No| Key 5 on numeric keypad| -| KEYCODE_NUMPAD_6 | number | Yes| No| Key 6 on numeric keypad| -| KEYCODE_NUMPAD_7 | number | Yes| No| Key 7 on numeric keypad| -| KEYCODE_NUMPAD_8 | number | Yes| No| Key 8 on numeric keypad| -| KEYCODE_NUMPAD_9 | number | Yes| No| Key 9 on numeric keypad| -| KEYCODE_NUMPAD_DIVIDE | number | Yes| No| Key / on numeric keypad| -| KEYCODE_NUMPAD_MULTIPLY | number | Yes| No| Key * on numeric keypad| -| KEYCODE_NUMPAD_SUBTRACT | number | Yes| No| Key - on numeric keypad| -| KEYCODE_NUMPAD_ADD | number | Yes| No| Key + on numeric keypad| -| KEYCODE_NUMPAD_DOT | number | Yes| No| Key . on numeric keypad| -| KEYCODE_NUMPAD_COMMA | number | Yes| No| Key , on numeric keypad| -| KEYCODE_NUMPAD_ENTER | number | Yes| No| Enter key on numeric keypad| -| KEYCODE_NUMPAD_EQUALS | number | Yes| No| Key = on numeric keypad| -| KEYCODE_NUMPAD_LEFT_PAREN | number | Yes| No| Key ( on numeric keypad| -| KEYCODE_NUMPAD_RIGHT_PAREN | number | Yes| No| Key ) on numeric keypad| -| KEYCODE_VIRTUAL_MULTITASK | number | Yes| No| Multi-task key| -| KEYCODE_SLEEP | number | Yes| No| Sleep key| -| KEYCODE_ZENKAKU_HANKAKU | number | Yes| No| Zenkaku/Hankaku key| -| KEYCODE_102ND | number | Yes| No| 102nd key| -| KEYCODE_RO | number | Yes| No| Ro key| -| KEYCODE_KATAKANA | number | Yes| No| Katakana key| -| KEYCODE_HIRAGANA | number | Yes| No| Hiragana key| -| KEYCODE_HENKAN | number | Yes| No| Henkan key| -| KEYCODE_KATAKANA_HIRAGANA | number | Yes| No| Katakana/Hiragana key| -| KEYCODE_MUHENKAN | number | Yes| No| Muhenkan key| -| KEYCODE_LINEFEED | number | Yes| No| Linefeed key| -| KEYCODE_MACRO | number | Yes| No| Macro key| -| KEYCODE_NUMPAD_PLUSMINUS | number | Yes| No| Plus/Minus key on the numeric keypad| -| KEYCODE_SCALE | number | Yes| No| Scale key| -| KEYCODE_HANGUEL | number | Yes| No| Hanguel key| -| KEYCODE_HANJA | number | Yes| No| Hanja key| -| KEYCODE_YEN | number | Yes| No| Yen key| -| KEYCODE_STOP | number | Yes| No| Stop key| -| KEYCODE_AGAIN | number | Yes| No| Again key| -| KEYCODE_PROPS | number | Yes| No| Props key| -| KEYCODE_UNDO | number | Yes| No| Undo key| -| KEYCODE_COPY | number | Yes| No| Copy key| -| KEYCODE_OPEN | number | Yes| No| Open key| -| KEYCODE_PASTE | number | Yes| No| Paste key| -| KEYCODE_FIND | number | Yes| No| Find key| -| KEYCODE_CUT | number | Yes| No| Cut key| -| KEYCODE_HELP | number | Yes| No| Help key| -| KEYCODE_CALC | number | Yes| No| Calc key, which is used to start the calculator application| -| KEYCODE_FILE | number | Yes| No| File key| -| KEYCODE_BOOKMARKS | number | Yes| No| Bookmarks key| -| KEYCODE_NEXT | number | Yes| No| Next key| -| KEYCODE_PLAYPAUSE | number | Yes| No| Play/Pause key| -| KEYCODE_PREVIOUS | number | Yes| No| Previous key| -| KEYCODE_STOPCD | number | Yes| No| Stop CD key| -| KEYCODE_CONFIG | number | Yes| No| Config key| -| KEYCODE_REFRESH | number | Yes| No| Refresh key| -| KEYCODE_EXIT | number | Yes| No| Exit key| -| KEYCODE_EDIT | number | Yes| No| Edit key| -| KEYCODE_SCROLLUP | number | Yes| No| Scroll Up key| -| KEYCODE_SCROLLDOWN | number | Yes| No| Scroll Down key| -| KEYCODE_NEW | number | Yes| No| New key| -| KEYCODE_REDO | number | Yes| No| Redo key| -| KEYCODE_CLOSE | number | Yes| No| Close key| -| KEYCODE_PLAY | number | Yes| No| Play key| -| KEYCODE_BASSBOOST | number | Yes| No| Bass Boost key| -| KEYCODE_PRINT | number | Yes| No| Print key| -| KEYCODE_CHAT | number | Yes| No| Chat key| -| KEYCODE_FINANCE | number | Yes| No| Finance key| -| KEYCODE_CANCEL | number | Yes| No| Cancel key| -| KEYCODE_KBDILLUM_TOGGLE | number | Yes| No| Keyboard Illumination Toggle key| -| KEYCODE_KBDILLUM_DOWN | number | Yes| No| Keyboard Illumination Up key| -| KEYCODE_KBDILLUM_UP | number | Yes| No| Keyboard Illumination Down key| -| KEYCODE_SEND | number | Yes| No| Send key| -| KEYCODE_REPLY | number | Yes| No| Reply key| -| KEYCODE_FORWARDMAIL | number | Yes| No| Forward Mail key| -| KEYCODE_SAVE | number | Yes| No| Save key| -| KEYCODE_DOCUMENTS | number | Yes| No| Documents key| -| KEYCODE_VIDEO_NEXT | number | Yes| No| Next Video key| -| KEYCODE_VIDEO_PREV | number | Yes| No| Previous Video key| -| KEYCODE_BRIGHTNESS_CYCLE | number | Yes| No| Brightness Cycle key| -| KEYCODE_BRIGHTNESS_ZERO | number | Yes| No| Brightness Zero key| -| KEYCODE_DISPLAY_OFF | number | Yes| No| Display Off Key| -| KEYCODE_BTN_MISC | number | Yes| No| Misc Button key| -| KEYCODE_GOTO | number | Yes| No| Goto key| -| KEYCODE_INFO | number | Yes| No| Info key| -| KEYCODE_PROGRAM | number | Yes| No| Program key| -| KEYCODE_PVR | number | Yes| No| PVR key| -| KEYCODE_SUBTITLE | number | Yes| No| Subtitle key| -| KEYCODE_FULL_SCREEN | number | Yes| No| Full Screen key| -| KEYCODE_KEYBOARD | number | Yes| No| Keyboard| -| KEYCODE_ASPECT_RATIO | number | Yes| No| Aspect Ratio key| -| KEYCODE_PC | number | Yes| No| Port Control key| -| KEYCODE_TV | number | Yes| No| TV key| -| KEYCODE_TV2 | number | Yes| No| TV key 2| -| KEYCODE_VCR | number | Yes| No| VCR key| -| KEYCODE_VCR2 | number | Yes| No| VCR key 2| -| KEYCODE_SAT | number | Yes| No| SAT key| -| KEYCODE_CD | number | Yes| No| CD key| -| KEYCODE_TAPE | number | Yes| No| Tape key| -| KEYCODE_TUNER | number | Yes| No| Tuner key| -| KEYCODE_PLAYER | number | Yes| No| Player key| -| KEYCODE_DVD | number | Yes| No| DVD key| -| KEYCODE_AUDIO | number | Yes| No| Audio key| -| KEYCODE_VIDEO | number | Yes| No| Video key| -| KEYCODE_MEMO | number | Yes| No| Memo key| -| KEYCODE_CALENDAR | number | Yes| No| Calendar key| -| KEYCODE_RED | number | Yes| No| Red indicator| -| KEYCODE_GREEN | number | Yes| No| Green indicator| -| KEYCODE_YELLOW | number | Yes| No| Yellow indicator| -| KEYCODE_BLUE | number | Yes| No| Blue indicator| -| KEYCODE_CHANNELUP | number | Yes| No| Channel Up key| -| KEYCODE_CHANNELDOWN | number | Yes| No| Channel Down key| -| KEYCODE_LAST | number | Yes| No| Last key| -| KEYCODE_RESTART | number | Yes| No| Restart key| -| KEYCODE_SLOW | number | Yes| No| Slow key| -| KEYCODE_SHUFFLE | number | Yes| No| Shuffle key| -| KEYCODE_VIDEOPHONE | number | Yes| No| Videophone key| -| KEYCODE_GAMES | number | Yes| No| Games key| -| KEYCODE_ZOOMIN | number | Yes| No| Zoom-in key| -| KEYCODE_ZOOMOUT | number | Yes| No| Zoom-out key| -| KEYCODE_ZOOMRESET | number | Yes| No| Zoom Reset key| -| KEYCODE_WORDPROCESSOR | number | Yes| No| Word Processor key| -| KEYCODE_EDITOR | number | Yes| No| Editor key| -| KEYCODE_SPREADSHEET | number | Yes| No| Spreadsheet key| -| KEYCODE_GRAPHICSEDITOR | number | Yes| No| Graphics Editor key| -| KEYCODE_PRESENTATION | number | Yes| No| Presentation key| -| KEYCODE_DATABASE | number | Yes| No| Database key| -| KEYCODE_NEWS | number | Yes| No| News key| -| KEYCODE_VOICEMAIL | number | Yes| No| Voicemail key| -| KEYCODE_ADDRESSBOOK | number | Yes| No| Addressbook key| -| KEYCODE_MESSENGER | number | Yes| No| Messenger key| -| KEYCODE_BRIGHTNESS_TOGGLE | number | Yes| No| Brightness Toggle key| -| KEYCODE_SPELLCHECK | number | Yes| No| Spell Check key| -| KEYCODE_COFFEE | number | Yes| No| Coffee key, which is used to launch screen lock or screen saver| -| KEYCODE_MEDIA_REPEAT | number | Yes| No| Media Repeat key| -| KEYCODE_IMAGES | number | Yes| No| Images key| -| KEYCODE_BUTTONCONFIG | number | Yes| No| Button Configuration key| -| KEYCODE_TASKMANAGER | number | Yes| No| Task Manager key| -| KEYCODE_JOURNAL | number | Yes| No| Log key| -| KEYCODE_CONTROLPANEL | number | Yes| No| Control Panel key| -| KEYCODE_APPSELECT | number | Yes| No| App Select key| -| KEYCODE_SCREENSAVER | number | Yes| No| Screen Saver key| -| KEYCODE_ASSISTANT | number | Yes| No| Assistant key| -| KEYCODE_KBD_LAYOUT_NEXT | number | Yes| No| Next Keyboard Layout key| -| KEYCODE_BRIGHTNESS_MIN | number | Yes| No| Min Brightness key| -| KEYCODE_BRIGHTNESS_MAX | number | Yes| No| Max Brightness key| -| KEYCODE_KBDINPUTASSIST_PREV | number | Yes| No| Keyboard Input-assisted Previous key| -| KEYCODE_KBDINPUTASSIST_NEXT | number | Yes| No| Keyboard Input-assisted Next key| -| KEYCODE_KBDINPUTASSIST_PREVGROUP | number | Yes| No| Keyboard Input-assisted Previous Group key| -| KEYCODE_KBDINPUTASSIST_NEXTGROUP | number | Yes| No| Keyboard Input-assisted Next Group key| -| KEYCODE_KBDINPUTASSIST_ACCEPT | number | Yes| No| Keyboard Input-assisted Accept key| -| KEYCODE_KBDINPUTASSIST_CANCEL | number | Yes| No| Keyboard Input-assisted Cancel key| -| KEYCODE_FRONT | number | Yes| No| Front key, which is used to launch the windshield defogger| -| KEYCODE_SETUP | number | Yes| No| Setup key| -| KEYCODE_WAKEUP | number | Yes| No| Wakeup key| -| KEYCODE_SENDFILE | number | Yes| No| Send File key| -| KEYCODE_DELETEFILE | number | Yes| No| Delete File key| -| KEYCODE_XFER | number | Yes| No| XFER key, which is used to start file transfer| -| KEYCODE_PROG1 | number | Yes| No| Program key 1| -| KEYCODE_PROG2 | number | Yes| No| Program key 2| -| KEYCODE_MSDOS | number | Yes| No| MS-DOS key| -| KEYCODE_SCREENLOCK | number | Yes| No| Screen Lock key| -| KEYCODE_DIRECTION_ROTATE_DISPLAY | number | Yes| No| Directional Rotation Display key| -| KEYCODE_CYCLEWINDOWS | number | Yes| No| Windows Cycle key| -| KEYCODE_COMPUTER | number | Yes| No| Key | -| KEYCODE_EJECTCLOSECD | number | Yes| No| Eject CD key| -| KEYCODE_ISO | number | Yes| No| ISO key| -| KEYCODE_MOVE | number | Yes| No| Move key| -| KEYCODE_F13 | number | Yes| No| F13 key| -| KEYCODE_F14 | number | Yes| No| F14 key| -| KEYCODE_F15 | number | Yes| No| F15 key| -| KEYCODE_F16 | number | Yes| No| F16 key| -| KEYCODE_F17 | number | Yes| No| F17 key| -| KEYCODE_F18 | number | Yes| No| F18 key| -| KEYCODE_F19 | number | Yes| No| F19 key| -| KEYCODE_F20 | number | Yes| No| F20 key| -| KEYCODE_F21 | number | Yes| No| F21 key| -| KEYCODE_F22 | number | Yes| No| F22 key| -| KEYCODE_F23 | number | Yes| No| F23 key| -| KEYCODE_F24 | number | Yes| No| F24 key| -| KEYCODE_PROG3 | number | Yes| No| Program key 3| -| KEYCODE_PROG4 | number | Yes| No| Program key 4| -| KEYCODE_DASHBOARD | number | Yes| No| Dashboard| -| KEYCODE_SUSPEND | number | Yes| No| Suspend key| -| KEYCODE_HP | number | Yes| No| HP key| -| KEYCODE_SOUND | number | Yes| No| Sound key| -| KEYCODE_QUESTION | number | Yes| No| Question key| -| KEYCODE_CONNECT | number | Yes| No| Connect key| -| KEYCODE_SPORT | number | Yes| No| Sport key| -| KEYCODE_SHOP | number | Yes| No| Shop key| -| KEYCODE_ALTERASE | number | Yes| No| Alternate key| -| KEYCODE_SWITCHVIDEOMODE | number | Yes| No| Switch Video Mode key (monitor, LCD, and TV, etc.)| -| KEYCODE_BATTERY | number | Yes| No| Battery key| -| KEYCODE_BLUETOOTH | number | Yes| No| Bluetooth key| -| KEYCODE_WLAN | number | Yes| No| WLAN key| -| KEYCODE_UWB | number | Yes| No| Ultra-wideband key| -| KEYCODE_WWAN_WIMAX | number | Yes| No| WWAN WiMAX key| -| KEYCODE_RFKILL | number | Yes| No| RF Kill key| -| KEYCODE_CHANNEL | number | Yes| No| Channel key| -| KEYCODE_BTN_0 | number | Yes| No| Key 0| -| KEYCODE_BTN_1 | number | Yes| No| Button 1| -| KEYCODE_BTN_2 | number | Yes| No| Button 2| -| KEYCODE_BTN_3 | number | Yes| No| Button 3| -| KEYCODE_BTN_4 | number | Yes| No| Button 4| -| KEYCODE_BTN_5 | number | Yes| No| Button 5| -| KEYCODE_BTN_6 | number | Yes| No| Button 6| -| KEYCODE_BTN_7 | number | Yes| No| Button 7| -| KEYCODE_BTN_8 | number | Yes| No| Button 8| -| KEYCODE_BTN_9 | number | Yes| No| Button 9| +| Name | Value | Description | +| -------------------------------- | ------ | --------------------------- | +| KEYCODE_FN | 0 | Function (Fn) key | +| KEYCODE_UNKNOWN | -1 | Unknown key | +| KEYCODE_HOME | 1 | Function (Home) key | +| KEYCODE_BACK | 2 | Back key | +| KEYCODE_MEDIA_PLAY_PAUSE | 10 | Play/Pause key | +| KEYCODE_MEDIA_STOP | 11 | Stop key | +| KEYCODE_MEDIA_NEXT | 12 | Next key | +| KEYCODE_MEDIA_PREVIOUS | 13 | Previous key | +| KEYCODE_MEDIA_REWIND | 14 | Rewind key | +| KEYCODE_MEDIA_FAST_FORWARD | 15 | Fast Forward key | +| KEYCODE_VOLUME_UP | 16 | Volume Up key | +| KEYCODE_VOLUME_DOWN | 17 | Volume Down key | +| KEYCODE_POWER | 18 | Power key | +| KEYCODE_CAMERA | 19 | Camera key | +| KEYCODE_VOLUME_MUTE | 22 | Speaker Mute key | +| KEYCODE_MUTE | 23 | Mute key | +| KEYCODE_BRIGHTNESS_UP | 40 | Brightness Up key | +| KEYCODE_BRIGHTNESS_DOWN | 41 | Brightness Down key | +| KEYCODE_0 | 2000 | Key 0 | +| KEYCODE_1 | 2001 | Key 1 | +| KEYCODE_2 | 2002 | Key 2 | +| KEYCODE_3 | 2003 | Key 3 | +| KEYCODE_4 | 2004 | Key 4 | +| KEYCODE_5 | 2005 | Key 5 | +| KEYCODE_6 | 2006 | Key 6 | +| KEYCODE_7 | 2007 | Key 7 | +| KEYCODE_8 | 2008 | Key 8 | +| KEYCODE_9 | 2009 | Key 9 | +| KEYCODE_STAR | 2010 | Key * | +| KEYCODE_POUND | 2011 | Key # | +| KEYCODE_DPAD_UP | 2012 | Up key on D-pad | +| KEYCODE_DPAD_DOWN | 2013 | Down key on D-pad | +| KEYCODE_DPAD_LEFT | 2014 | Left key on D-pad | +| KEYCODE_DPAD_RIGHT | 2015 | Right key on D-pad | +| KEYCODE_DPAD_CENTER | 2016 | Center key on D-pad | +| KEYCODE_A | 2017 | Key A | +| KEYCODE_B | 2018 | Key B | +| KEYCODE_C | 2019 | Key C | +| KEYCODE_D | 2020 | Key D | +| KEYCODE_E | 2021 | Key E | +| KEYCODE_F | 2022 | Key F | +| KEYCODE_G | 2023 | Key G | +| KEYCODE_H | 2024 | Key H | +| KEYCODE_I | 2025 | Key I | +| KEYCODE_J | 2026 | Key J | +| KEYCODE_K | 2027 | Key K | +| KEYCODE_L | 2028 | Key L | +| KEYCODE_M | 2029 | Key M | +| KEYCODE_N | 2030 | Key N | +| KEYCODE_O | 2031 | Key O | +| KEYCODE_P | 2032 | Key P | +| KEYCODE_Q | 2033 | Key Q | +| KEYCODE_R | 2034 | Key R | +| KEYCODE_S | 2035 | Key S | +| KEYCODE_T | 2036 | Key T | +| KEYCODE_U | 2037 | Key U | +| KEYCODE_V | 2038 | Key V | +| KEYCODE_W | 2039 | Key W | +| KEYCODE_X | 2040 | Key X | +| KEYCODE_Y | 2041 | Key Y | +| KEYCODE_Z | 2042 | Key Z | +| KEYCODE_COMMA | 2043 | Key , | +| KEYCODE_PERIOD | 2044 | Key . | +| KEYCODE_ALT_LEFT | 2045 | Left Alt key | +| KEYCODE_ALT_RIGHT | 2046 | Right Alt key | +| KEYCODE_SHIFT_LEFT | 2047 | Left Shift key | +| KEYCODE_SHIFT_RIGHT | 2048 | Right Shift key | +| KEYCODE_TAB | 2049 | Tab key | +| KEYCODE_SPACE | 2050 | Space key | +| KEYCODE_SYM | 2051 | Symbol key | +| KEYCODE_EXPLORER | 2052 | Explorer key, which is used to start the explorer application | +| KEYCODE_ENVELOPE | 2053 | Email key, which is used to start the email application | +| KEYCODE_ENTER | 2054 | Enter key | +| KEYCODE_DEL | 2055 | Delete key | +| KEYCODE_GRAVE | 2056 | Key ` | +| KEYCODE_MINUS | 2057 | Key - | +| KEYCODE_EQUALS | 2058 | Key = | +| KEYCODE_LEFT_BRACKET | 2059 | Key [ | +| KEYCODE_RIGHT_BRACKET | 2060 | Key ] | +| KEYCODE_BACKSLASH | 2061 | Key \\ | +| KEYCODE_SEMICOLON | 2062 | Key ; | +| KEYCODE_APOSTROPHE | 2063 | Key ' | +| KEYCODE_SLASH | 2064 | Key / | +| KEYCODE_AT | 2065 | Key @ | +| KEYCODE_PLUS | 2066 | Key + | +| KEYCODE_MENU | 2067 | Menu key | +| KEYCODE_PAGE_UP | 2068 | Page Up key | +| KEYCODE_PAGE_DOWN | 2069 | Page Down key | +| KEYCODE_ESCAPE | 2070 | ESC key | +| KEYCODE_FORWARD_DEL | 2071 | Delete key | +| KEYCODE_CTRL_LEFT | 2072 | Left Ctrl key | +| KEYCODE_CTRL_RIGHT | 2073 | Right Ctrl key | +| KEYCODE_CAPS_LOCK | 2074 | Caps Lock key | +| KEYCODE_SCROLL_LOCK | 2075 | Scroll Lock key | +| KEYCODE_META_LEFT | 2076 | Left Meta key | +| KEYCODE_META_RIGHT | 2077 | Right Meta key | +| KEYCODE_FUNCTION | 2078 | Function key | +| KEYCODE_SYSRQ | 2079 | System Request/Print Screen key | +| KEYCODE_BREAK | 2080 | Break/Pause key | +| KEYCODE_MOVE_HOME | 2081 | Move to Home key | +| KEYCODE_MOVE_END | 2082 | Move to End key | +| KEYCODE_INSERT | 2083 | Insert key | +| KEYCODE_FORWARD | 2084 | Forward key | +| KEYCODE_MEDIA_PLAY | 2085 | Play key | +| KEYCODE_MEDIA_PAUSE | 2086 | Pause key | +| KEYCODE_MEDIA_CLOSE | 2087 | Close key | +| KEYCODE_MEDIA_EJECT | 2088 | Eject key | +| KEYCODE_MEDIA_RECORD | 2089 | Record key | +| KEYCODE_F1 | 2090 | F1 key | +| KEYCODE_F2 | 2091 | F2 key | +| KEYCODE_F3 | 2092 | F3 key | +| KEYCODE_F4 | 2093 | F4 key | +| KEYCODE_F5 | 2094 | F5 key | +| KEYCODE_F6 | 2095 | F6 key | +| KEYCODE_F7 | 2096 | F7 key | +| KEYCODE_F8 | 2097 | F8 key | +| KEYCODE_F9 | 2098 | F9 key | +| KEYCODE_F10 | 2099 | F10 key | +| KEYCODE_F11 | 2100 | F11 key | +| KEYCODE_F12 | 2101 | F12 key | +| KEYCODE_NUM_LOCK | 2102 | Number Lock key | +| KEYCODE_NUMPAD_0 | 2103 | Key 0 on numeric keypad | +| KEYCODE_NUMPAD_1 | 2104 | Key 1 on numeric keypad | +| KEYCODE_NUMPAD_2 | 2105 | Key 2 on numeric keypad | +| KEYCODE_NUMPAD_3 | 2106 | Key 3 on numeric keypad | +| KEYCODE_NUMPAD_4 | 2107 | Key 4 on numeric keypad | +| KEYCODE_NUMPAD_5 | 2108 | Key 5 on numeric keypad | +| KEYCODE_NUMPAD_6 | 2109 | Key 6 on numeric keypad | +| KEYCODE_NUMPAD_7 | 2110 | Key 7 on numeric keypad | +| KEYCODE_NUMPAD_8 | 2111 | Key 8 on numeric keypad | +| KEYCODE_NUMPAD_9 | 2112 | Key 9 on numeric keypad | +| KEYCODE_NUMPAD_DIVIDE | 2113 | Key / on numeric keypad | +| KEYCODE_NUMPAD_MULTIPLY | 2114 | Key * on numeric keypad | +| KEYCODE_NUMPAD_SUBTRACT | 2115 | Key - on numeric keypad | +| KEYCODE_NUMPAD_ADD | 2116 | Key + on numeric keypad | +| KEYCODE_NUMPAD_DOT | 2117 | Key . on numeric keypad | +| KEYCODE_NUMPAD_COMMA | 2118 | Key , on numeric keypad | +| KEYCODE_NUMPAD_ENTER | 2119 | Enter key on numeric keypad | +| KEYCODE_NUMPAD_EQUALS | 2120 | Key = on numeric keypad | +| KEYCODE_NUMPAD_LEFT_PAREN | 2121 | Key ( on numeric keypad | +| KEYCODE_NUMPAD_RIGHT_PAREN | 2122 | Key ) on numeric keypad | +| KEYCODE_VIRTUAL_MULTITASK | 2210 | Multi-task key | +| KEYCODE_SLEEP | 2600 | Sleep key | +| KEYCODE_ZENKAKU_HANKAKU | 2601 | Zenkaku/Hankaku key | +| KEYCODE_102ND | 2602 | 102nd key | +| KEYCODE_RO | 2603 | Ro key | +| KEYCODE_KATAKANA | 2604 | Katakana key | +| KEYCODE_HIRAGANA | 2605 | Hiragana key | +| KEYCODE_HENKAN | 2606 | Henkan key | +| KEYCODE_KATAKANA_HIRAGANA | 2607 | Katakana/Hiragana key | +| KEYCODE_MUHENKAN | 2608 | Muhenkan key | +| KEYCODE_LINEFEED | 2609 | Linefeed key | +| KEYCODE_MACRO | 2610 | Macro key | +| KEYCODE_NUMPAD_PLUSMINUS | 2611 | Plus/Minus key on the numeric keypad | +| KEYCODE_SCALE | 2612 | Scale key | +| KEYCODE_HANGUEL | 2613 | Hanguel key | +| KEYCODE_HANJA | 2614 | Hanja key | +| KEYCODE_YEN | 2615 | Yen key | +| KEYCODE_STOP | 2616 | Stop key | +| KEYCODE_AGAIN | 2617 | Again key | +| KEYCODE_PROPS | 2618 | Props key | +| KEYCODE_UNDO | 2619 | Undo key | +| KEYCODE_COPY | 2620 | Copy key | +| KEYCODE_OPEN | 2621 | Open key | +| KEYCODE_PASTE | 2622 | Paste key | +| KEYCODE_FIND | 2623 | Find key | +| KEYCODE_CUT | 2624 | Cut key | +| KEYCODE_HELP | 2625 | Help key | +| KEYCODE_CALC | 2626 | Calc key, which is used to start the calculator application | +| KEYCODE_FILE | 2627 | File key | +| KEYCODE_BOOKMARKS | 2628 | Bookmarks key | +| KEYCODE_NEXT | 2629 | Next key | +| KEYCODE_PLAYPAUSE | 2630 | Play/Pause key | +| KEYCODE_PREVIOUS | 2631 | Previous key | +| KEYCODE_STOPCD | 2632 | Stop CD key | +| KEYCODE_CONFIG | 2634 | Config key | +| KEYCODE_REFRESH | 2635 | Refresh key | +| KEYCODE_EXIT | 2636 | Exit key | +| KEYCODE_EDIT | 2637 | Edit key | +| KEYCODE_SCROLLUP | 2638 | Scroll Up key | +| KEYCODE_SCROLLDOWN | 2639 | Scroll Down key | +| KEYCODE_NEW | 2640 | New key | +| KEYCODE_REDO | 2641 | Redo key | +| KEYCODE_CLOSE | 2642 | Close key | +| KEYCODE_PLAY | 2643 | Play key | +| KEYCODE_BASSBOOST | 2644 | Bass Boost key | +| KEYCODE_PRINT | 2645 | Print key | +| KEYCODE_CHAT | 2646 | Chat key | +| KEYCODE_FINANCE | 2647 | Finance key | +| KEYCODE_CANCEL | 2648 | Cancel key | +| KEYCODE_KBDILLUM_TOGGLE | 2649 | Keyboard Illumination Toggle key | +| KEYCODE_KBDILLUM_DOWN | 2650 | Keyboard Illumination Up key | +| KEYCODE_KBDILLUM_UP | 2651 | Keyboard Illumination Down key | +| KEYCODE_SEND | 2652 | Send key | +| KEYCODE_REPLY | 2653 | Reply key | +| KEYCODE_FORWARDMAIL | 2654 | Forward Mail key | +| KEYCODE_SAVE | 2655 | Save key | +| KEYCODE_DOCUMENTS | 2656 | Documents key | +| KEYCODE_VIDEO_NEXT | 2657 | Next Video key | +| KEYCODE_VIDEO_PREV | 2658 | Previous Video key | +| KEYCODE_BRIGHTNESS_CYCLE | 2659 | Brightness Cycle key | +| KEYCODE_BRIGHTNESS_ZERO | 2660 | Brightness Zero key | +| KEYCODE_DISPLAY_OFF | 2661 | Display Off Key | +| KEYCODE_BTN_MISC | 2662 | Misc Button key | +| KEYCODE_GOTO | 2663 | Goto key | +| KEYCODE_INFO | 2664 | Info key | +| KEYCODE_PROGRAM | 2665 | Program key | +| KEYCODE_PVR | 2666 | PVR key | +| KEYCODE_SUBTITLE | 2667 | Subtitle key | +| KEYCODE_FULL_SCREEN | 2668 | Full Screen key | +| KEYCODE_KEYBOARD | 2669 | Keyboard | +| KEYCODE_ASPECT_RATIO | 2670 | Aspect Ratio key | +| KEYCODE_PC | 2671 | Port Control key | +| KEYCODE_TV | 2672 | TV key | +| KEYCODE_TV2 | 2673 | TV key 2 | +| KEYCODE_VCR | 2674 | VCR key | +| KEYCODE_VCR2 | 2675 | VCR key 2 | +| KEYCODE_SAT | 2676 | SAT key | +| KEYCODE_CD | 2677 | CD key | +| KEYCODE_TAPE | 2678 | Tape key | +| KEYCODE_TUNER | 2679 | Tuner key | +| KEYCODE_PLAYER | 2680 | Player key | +| KEYCODE_DVD | 2681 | DVD key | +| KEYCODE_AUDIO | 2682 | Audio key | +| KEYCODE_VIDEO | 2683 | Video key | +| KEYCODE_MEMO | 2684 | Memo key | +| KEYCODE_CALENDAR | 2685 | Calendar key | +| KEYCODE_RED | 2686 | Red indicator | +| KEYCODE_GREEN | 2687 | Green indicator | +| KEYCODE_YELLOW | 2688 | Yellow indicator | +| KEYCODE_BLUE | 2689 | Blue indicator | +| KEYCODE_CHANNELUP | 2690 | Channel Up key | +| KEYCODE_CHANNELDOWN | 2691 | Channel Down key | +| KEYCODE_LAST | 2692 | Last key | +| KEYCODE_RESTART | 2693 | Restart key | +| KEYCODE_SLOW | 2694 | Slow key | +| KEYCODE_SHUFFLE | 2695 | Shuffle key | +| KEYCODE_VIDEOPHONE | 2696 | Videophone key | +| KEYCODE_GAMES | 2697 | Games key | +| KEYCODE_ZOOMIN | 2698 | Zoom-in key | +| KEYCODE_ZOOMOUT | 2699 | Zoom-out key | +| KEYCODE_ZOOMRESET | 2700 | Zoom Reset key | +| KEYCODE_WORDPROCESSOR | 2701 | Word Processor key | +| KEYCODE_EDITOR | 2702 | Editor key | +| KEYCODE_SPREADSHEET | 2703 | Spreadsheet key | +| KEYCODE_GRAPHICSEDITOR | 2704 | Graphics Editor key | +| KEYCODE_PRESENTATION | 2705 | Presentation key | +| KEYCODE_DATABASE | 2706 | Database key | +| KEYCODE_NEWS | 2707 | News key | +| KEYCODE_VOICEMAIL | 2708 | Voicemail key | +| KEYCODE_ADDRESSBOOK | 2709 | Addressbook key | +| KEYCODE_MESSENGER | 2710 | Messenger key | +| KEYCODE_BRIGHTNESS_TOGGLE | 2711 | Brightness Toggle key | +| KEYCODE_SPELLCHECK | 2712 | Spell Check key | +| KEYCODE_COFFEE | 2713 | Coffee key, which is used to launch screen lock or screen saver | +| KEYCODE_MEDIA_REPEAT | 2714 | Media Repeat key | +| KEYCODE_IMAGES | 2715 | Images key | +| KEYCODE_BUTTONCONFIG | 2716 | Button Configuration key | +| KEYCODE_TASKMANAGER | 2717 | Task Manager key | +| KEYCODE_JOURNAL | 2718 | Log key | +| KEYCODE_CONTROLPANEL | 2719 | Control Panel key | +| KEYCODE_APPSELECT | 2720 | App Select key | +| KEYCODE_SCREENSAVER | 2721 | Screen Saver key | +| KEYCODE_ASSISTANT | 2722 | Assistant key | +| KEYCODE_KBD_LAYOUT_NEXT | 2723 | Next Keyboard Layout key | +| KEYCODE_BRIGHTNESS_MIN | 2724 | Min Brightness key | +| KEYCODE_BRIGHTNESS_MAX | 2725 | Max Brightness key | +| KEYCODE_KBDINPUTASSIST_PREV | 2726 | Keyboard Input-assisted Previous key | +| KEYCODE_KBDINPUTASSIST_NEXT | 2727 | Keyboard Input-assisted Next key | +| KEYCODE_KBDINPUTASSIST_PREVGROUP | 2728 | Keyboard Input-assisted Previous Group key | +| KEYCODE_KBDINPUTASSIST_NEXTGROUP | 2729 | Keyboard Input-assisted Next Group key | +| KEYCODE_KBDINPUTASSIST_ACCEPT | 2730 | Keyboard Input-assisted Accept key | +| KEYCODE_KBDINPUTASSIST_CANCEL | 2731 | Keyboard Input-assisted Cancel key | +| KEYCODE_FRONT | 2800 | Front key, which is used to launch the windshield defogger | +| KEYCODE_SETUP | 2801 | Setup key | +| KEYCODE_WAKEUP | 2802 | Wakeup key | +| KEYCODE_SENDFILE | 2803 | Send File key | +| KEYCODE_DELETEFILE | 2804 | Delete File key | +| KEYCODE_XFER | 2805 | XFER key, which is used to start file transfer | +| KEYCODE_PROG1 | 2806 | Program key 1 | +| KEYCODE_PROG2 | 2807 | Program key 2 | +| KEYCODE_MSDOS | 2808 | MS-DOS key | +| KEYCODE_SCREENLOCK | 2809 | Screen Lock key | +| KEYCODE_DIRECTION_ROTATE_DISPLAY | 2810 | Directional Rotation Display key | +| KEYCODE_CYCLEWINDOWS | 2811 | Windows Cycle key | +| KEYCODE_COMPUTER | 2812 | Keys | +| KEYCODE_EJECTCLOSECD | 2813 | Eject CD key | +| KEYCODE_ISO | 2814 | ISO key | +| KEYCODE_MOVE | 2815 | Move key | +| KEYCODE_F13 | 2816 | F13 key | +| KEYCODE_F14 | 2817 | F14 key | +| KEYCODE_F15 | 2818 | F15 key | +| KEYCODE_F16 | 2819 | F16 key | +| KEYCODE_F17 | 2820 | F17 key | +| KEYCODE_F18 | 2821 | F18 key | +| KEYCODE_F19 | 2822 | F19 key | +| KEYCODE_F20 | 2823 | F20 key | +| KEYCODE_F21 | 2824 | F21 key | +| KEYCODE_F22 | 2825 | F22 key | +| KEYCODE_F23 | 2826 | F23 key | +| KEYCODE_F24 | 2827 | F24 key | +| KEYCODE_PROG3 | 2828 | Program key 3 | +| KEYCODE_PROG4 | 2829 | Program key 4 | +| KEYCODE_DASHBOARD | 2830 | Dashboard | +| KEYCODE_SUSPEND | 2831 | Suspend key | +| KEYCODE_HP | 2832 | HP key | +| KEYCODE_SOUND | 2833 | Sound key | +| KEYCODE_QUESTION | 2834 | Question key | +| KEYCODE_CONNECT | 2836 | Connect key | +| KEYCODE_SPORT | 2837 | Sport key | +| KEYCODE_SHOP | 2838 | Shop key | +| KEYCODE_ALTERASE | 2839 | Alternate key | +| KEYCODE_SWITCHVIDEOMODE | 2841 | Switch Video Mode key (monitor, LCD, and TV, etc.)| +| KEYCODE_BATTERY | 2842 | Battery key | +| KEYCODE_BLUETOOTH | 2843 | Bluetooth key | +| KEYCODE_WLAN | 2844 | WLAN key | +| KEYCODE_UWB | 2845 | Ultra-wideband key | +| KEYCODE_WWAN_WIMAX | 2846 | WWAN WiMAX key | +| KEYCODE_RFKILL | 2847 | RF Kill key | +| KEYCODE_CHANNEL | 3001 | Channel key | +| KEYCODE_BTN_0 | 3100 | Button 0 | +| KEYCODE_BTN_1 | 3101 | Button 1 | +| KEYCODE_BTN_2 | 3102 | Button 2 | +| KEYCODE_BTN_3 | 3103 | Button 3 | +| KEYCODE_BTN_4 | 3104 | Button 4 | +| KEYCODE_BTN_5 | 3105 | Button 5 | +| KEYCODE_BTN_6 | 3106 | Button 6 | +| KEYCODE_BTN_7 | 3107 | Button 7 | +| KEYCODE_BTN_8 | 3108 | Button 8 | +| KEYCODE_BTN_9 | 3109 | Button 9 | diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md index ded0aab53e599fd8aebad2de8963fc503e83d8fb..32c18a558572b8f971b8faf6277c3300e86f9649 100644 --- a/en/application-dev/reference/apis/js-apis-keyevent.md +++ b/en/application-dev/reference/apis/js-apis-keyevent.md @@ -1,6 +1,6 @@ -# Key Event +# @ohos.multimodalInput.keyEvent (Key Event) -The Key Event module provides key events reported by an input device. +The **keyEvent** module provides key events reported by an input device. > **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. @@ -8,44 +8,44 @@ The Key Event module provides key events reported by an input device. ## Modules to Import ```js -import {Action,Key,KeyEvent} from '@ohos.multimodalInput.keyEvent'; +import {Action, Key, KeyEvent} from '@ohos.multimodalInput.keyEvent'; ``` ## Action **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| CANCEL | number | Yes| No| Cancellation of a key action.| -| DOWN | number | Yes| No| Pressing of a key.| -| UP | number | Yes| No| Release of a key.| +| Name | Value | Description | +| ------ | ------- | -------- | +| CANCEL | 0 | Cancellation of a key action.| +| DOWN | 1 | Pressing of a key.| +| UP | 2 | Release of a key.| ## Key **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| code | KeyCode | Yes| No| Keycode.| -| pressedTime | number | Yes| No| Time when the key is pressed.| -| deviceId | number | Yes| No| Device to which the key belongs.| +| Name | Type| Readable| Writable| Description | +| ----------- | -------- | ---- | ---- | -------------- | +| code | KeyCode | Yes | No | Keycode. | +| pressedTime | number | Yes | No | Time when the key is pressed.| +| deviceId | number | Yes | No | ID of the device to which the key belongs. | ## KeyEvent **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| action | Action | Yes| No| Key action.| -| key | Key | Yes| No| Key that has changed.| -| unicodeChar | number | Yes| No| Unicode character corresponding to the key.| -| keys | Key[] | Yes| No| List of pressed keys.| -| ctrlKey | boolean | Yes| No| Whether ctrlKey is being pressed.| -| altKey | boolean | Yes| No| Whether altKey is being pressed.| -| shiftKey | boolean | Yes| No| Whether shiftKey is being pressed.| -| logoKey | boolean | Yes| No| Whether logoKey is being pressed.| -| fnKey | boolean | Yes| No| Whether fnKey is being pressed.| -| capsLock | boolean | Yes| No| Whether capsLock is active.| -| numLock | boolean | Yes| No| Whether numLock is active.| -| scrollLock | boolean | Yes| No| Whether scrollLock is active.| +| Name | Type| Readable| Writable| Description | +| ----------- | -------- | ---- | ---- | ------------------------------ | +| action | Action | Yes | No | Key action. | +| key | Key | Yes | No | Key for which the event is reported. | +| unicodeChar | number | Yes | No | Unicode character corresponding to the key. | +| keys | Key[] | Yes | No | List of pressed keys. | +| ctrlKey | boolean | Yes | No | Whether ctrlKey is being pressed. | +| altKey | boolean | Yes | No | Whether altKey is being pressed. | +| shiftKey | boolean | Yes | No | Whether shiftKey is being pressed. | +| logoKey | boolean | Yes | No | Whether logoKey is being pressed. | +| fnKey | boolean | Yes | No | Whether fnKey is being pressed. | +| capsLock | boolean | Yes | No | Whether capsLock is active. | +| numLock | boolean | Yes | No | Whether numLock is active. | +| scrollLock | boolean | Yes | No | Whether scrollLock is active.| diff --git a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md index f149c30d7a93f9adaaa68c03edea7426a8882531..505c29ae0ef6cc18404767eaa4a4b4ac88296651 100644 --- a/en/application-dev/reference/apis/js-apis-launcherBundleManager.md +++ b/en/application-dev/reference/apis/js-apis-launcherBundleManager.md @@ -1,6 +1,6 @@ -# Bundle.launcherBundleManager +# @ohos.bundle.launcherBundleManager -The **Bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the launcher ability information and shortcut information. +The **bundle.launcherBundleManager** module providers APIs for the **Home Screen** application to obtain the launcher ability information and shortcut information. > **NOTE** > @@ -27,7 +27,7 @@ Obtains the launcher ability information based on the given bundle name and user **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| | userId | number | Yes | User ID.| @@ -78,7 +78,7 @@ Obtains the launcher ability information based on the given bundle name and user **Parameters** -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| | userId | number | Yes | User ID.| @@ -128,7 +128,7 @@ Obtains the launcher ability information of all applications based on the given **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | | userId | number | Yes | User ID.| @@ -176,7 +176,7 @@ Obtains the launcher ability information of all applications based on the given **Parameters** -| Name| Type | Mandatory| Description | +| Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------- | | userId | number | Yes | User ID.| @@ -222,7 +222,7 @@ Obtains the shortcut information of the current user based on the given bundle n **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| @@ -269,13 +269,13 @@ Obtains the shortcut information of the current user based on the given bundle n **System capability**: SystemCapability.BundleManager.BundleFramework.Launcher -| Name | Type | Mandatory| Description | +| Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------- | | bundleName | string | Yes | Bundle name of the application.| **Return value** -| Template | Description | +| Type | Description | | ---------------------- | ----------------------------------------------- | | Promise\> | Promise used to return the **ShortcutInfo** object obtained.| diff --git a/en/application-dev/reference/apis/js-apis-lightweightmap.md b/en/application-dev/reference/apis/js-apis-lightweightmap.md index f2ab94b72b0538f83cd21642081172cfb19b3cb1..89893c1c97d183c69765535141b2012fae9e080a 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightmap.md +++ b/en/application-dev/reference/apis/js-apis-lightweightmap.md @@ -1,12 +1,13 @@ -# Nonlinear Container LightWeightMap +# @ohos.util.LightWeightMap (Nonlinear Container LightWeightMap) > **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. **LightWeightMap** stores key-value (KV) pairs. Each key must be unique and have only one value. -**LightWeightMap** is based on generics and uses a lightweight structure. Keys in the map are searched using hash values, which are stored in an array. +**LightWeightMap** is based on generics and uses a lightweight structure. Its default initial capacity is 8, and it has the capacity doubled in each expansion. + +The keys in such a set are searched using hash values, which are stored in an array. Compared with **[HashMap](js-apis-hashmap.md)**, which can also store KV pairs, **LightWeightMap** occupies less memory. @@ -44,7 +45,7 @@ A constructor used to create a **LightWeightMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -54,11 +55,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); -try { - let lightWeightMap2 = LightWeightMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -78,7 +74,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -89,11 +85,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const lightWeightMap = new LightWeightMap(); let result = lightWeightMap.isEmpty(); -try { - lightWeightMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -119,7 +110,7 @@ Checks whether this container contains all elements of the specified **LightWeig **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -134,11 +125,6 @@ lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); map.set("sparrow", 356); let result = lightWeightMap.hasAll(map); -try { - lightWeightMap.hasAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -164,7 +150,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -174,15 +160,8 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); -let result = lightWeightMap.hasKey; -lightWeightMap.hasKey("squirrel"); lightWeightMap.set("squirrel", 123); -let result1 = lightWeightMap.hasKey("squirrel"); -try { - lightWeightMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} +let result = lightWeightMap.hasKey("squirrel"); ``` @@ -208,7 +187,7 @@ Checks whether this container contains the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -221,11 +200,6 @@ let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.hasValue(123); lightWeightMap.set("squirrel", 123); let result1 = lightWeightMap.hasValue(123); -try { - lightWeightMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -239,7 +213,7 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -256,11 +230,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); lightWeightMap.increaseCapacityTo(10); -try { - lightWeightMap.increaseCapacityTo.bind({}, 10)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -286,7 +255,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -299,11 +268,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.get("sparrow"); -try { - lightWeightMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -329,7 +293,7 @@ Obtains the index of the first occurrence of an element with the specified key i **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -342,11 +306,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfKey("sparrow"); -try { - lightWeightMap.getIndexOfKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -372,7 +331,7 @@ Obtains the index of the first occurrence of an element with the specified value **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -385,11 +344,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getIndexOfValue(123); -try { - lightWeightMap.getIndexOfValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -415,12 +369,12 @@ Obtains the key of an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getKeyAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -429,16 +383,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getKeyAt(1); -try { - lightWeightMap.getKeyAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.getKeyAt(6)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -458,7 +402,7 @@ Adds all elements in a **LightWeightMap** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -471,12 +415,7 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let map = new LightWeightMap(); -lightWeightMap.setAll(map); -try { - lightWeightMap.setAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} +map.setAll(lightWeightMap); // Add all elements in lightWeightMap to the map. ``` @@ -502,7 +441,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -513,11 +452,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightMap = new LightWeightMap(); let result = lightWeightMap.set("squirrel", 123); -try { - lightWeightMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -543,7 +477,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -556,11 +490,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.remove("sparrow"); -try { - lightWeightMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -586,7 +515,7 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -599,11 +528,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.removeAt(1); -try { - lightWeightMap.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -630,12 +554,12 @@ Sets a value for an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -644,16 +568,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.setValueAt(1, 3546); -try { - lightWeightMap.setValueAt.bind({}, 1, 3546)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.setValueAt(6, 3546); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -679,12 +593,12 @@ Obtains the value of an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -693,16 +607,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); let result = lightWeightMap.getValueAt(1); -try { - lightWeightMap.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightMap.getValueAt(6); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -716,7 +620,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -729,11 +633,6 @@ let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); lightWeightMap.clear(); -try { - lightWeightMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -753,7 +652,7 @@ Obtains an iterator that contains all the keys in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -771,11 +670,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -795,7 +689,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -813,17 +707,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: LightWeightMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -833,7 +722,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -845,7 +734,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -860,13 +749,6 @@ lightWeightMap.set("gull", 357); lightWeightMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - lightWeightMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -886,7 +768,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -905,11 +787,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - lightWeightMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### toString @@ -922,13 +799,13 @@ Concatenates the elements in this container into a string and returns the string **Return value** -| Type| Description| -| -------- | -------- | -| String | String obtained.| + | Type| Description| + | -------- | -------- | + | String | String obtained.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -940,12 +817,7 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let lightWeightMap = new LightWeightMap(); lightWeightMap.set("squirrel", 123); lightWeightMap.set("sparrow", 356); -let iter = lightWeightMap.toString(); -try { - lightWeightMap.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} +let result = lightWeightMap.toString(); ``` ### [Symbol.iterator] @@ -964,7 +836,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -991,9 +863,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - lightWeightMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-lightweightset.md b/en/application-dev/reference/apis/js-apis-lightweightset.md index f5cfbde6cb11daf8884e3c5cf5818fbccc9475a6..25c7950dc4968bc3f9f33ad6b277ecdc68a6ea09 100644 --- a/en/application-dev/reference/apis/js-apis-lightweightset.md +++ b/en/application-dev/reference/apis/js-apis-lightweightset.md @@ -1,7 +1,6 @@ -# Nonlinear Container LightWeightSet +# @ohos.util.LightWeightSet (Nonlinear Container LightWeightSet) > **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. **LightWeightSet** stores a set of values, each of which must be unique. @@ -23,8 +22,6 @@ This topic uses the following to identify the use of generics: import LightWeightSet from '@ohos.util.LightWeightSet'; ``` - - ## LightWeightSet ### Attributes @@ -46,7 +43,7 @@ A constructor used to create a **LightWeightSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -56,11 +53,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightSet = new LightWeightSet(); -try { - let lightWeightSet2 = LightWeightSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -80,7 +72,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -91,11 +83,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const lightWeightSet = new LightWeightSet(); let result = lightWeightSet.isEmpty(); -try { - lightWeightSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### add @@ -120,7 +107,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -131,11 +118,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.add("squirrel"); -try { - lightWeightSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -155,7 +137,7 @@ Adds all elements in a **LightWeightSet** instance to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -170,11 +152,6 @@ lightWeightSet.add("sparrow"); let set = new LightWeightSet(); set.add("gull"); let result = lightWeightSet.addAll(set); -try { - lightWeightSet.addAll.bind({}, set)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -200,7 +177,7 @@ Checks whether this container contains all elements of the specified **LightWeig **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -215,11 +192,6 @@ lightWeightSet.add("sparrow"); let set = new LightWeightSet(); set.add("sparrow"); let result = lightWeightSet.hasAll(set); -try { - lightWeightSet.hasAll.bind({}, set)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -245,7 +217,7 @@ Checks whether this container has the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -258,11 +230,6 @@ let lightWeightSet = new LightWeightSet(); let result = lightWeightSet.has(123); lightWeightSet.add(123); result = lightWeightSet.has(123); -try { - lightWeightSet.has.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -278,7 +245,7 @@ Checks whether this container contains objects of the same type as the specified | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| obj | Object | Yes| Object to be used for comparison.| +| obj | Object | Yes| **LightWeightSet** instance to be used for comparison.| **Return value** @@ -288,7 +255,7 @@ Checks whether this container contains objects of the same type as the specified **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -302,11 +269,6 @@ lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let obj = ["squirrel", "sparrow"]; let result = lightWeightSet.equal(obj); -try { - lightWeightSet.equal.bind({}, obj)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -326,28 +288,18 @@ Increases the capacity of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The increaseCapacityTo method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of minimumCapacity is out of range. | **Example** ```ts let lightWeightSet = new LightWeightSet(); lightWeightSet.increaseCapacityTo(10); -try { - lightWeightSet.increaseCapacityTo.bind({}, 10)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - lightWeightSet.increaseCapacityTo(2); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -373,7 +325,7 @@ Obtains the position index of the element with the specified key in this contain **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -386,11 +338,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getIndexOf("sparrow"); -try { - lightWeightSet.getIndexOf.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -416,7 +363,7 @@ Removes an element of the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -429,11 +376,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.remove("sparrow"); -try { - lightWeightSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -459,7 +401,7 @@ Removes the element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -472,11 +414,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.removeAt(1); -try { - lightWeightSet.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -502,7 +439,7 @@ Obtains the value of the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -515,11 +452,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.getValueAt(1); -try { - lightWeightSet.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -533,7 +465,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -546,11 +478,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); lightWeightSet.clear(); -try { - lightWeightSet.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -568,14 +495,6 @@ Obtains a string that contains all elements in this container. | -------- | -------- | | String | String obtained.| -**Error codes** - -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). - -| ID| Error Message| -| -------- | -------- | -| 10200011 | The toString method cannot be bound. | - **Example** ```ts @@ -583,11 +502,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toString(); -try { - lightWeightSet.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -607,7 +521,7 @@ Obtains an array that contains all objects in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -620,11 +534,6 @@ let lightWeightSet = new LightWeightSet(); lightWeightSet.add("squirrel"); lightWeightSet.add("sparrow"); let result = lightWeightSet.toArray(); -try { - lightWeightSet.toArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -644,7 +553,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -662,17 +571,12 @@ while(index < lightWeightSet.length) { console.log(JSON.stringify(iter.next().value)); index++; } -try { - lightWeightSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: LightWeightSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -682,7 +586,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -694,7 +598,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -709,13 +613,6 @@ lightWeightSet.add("gull"); lightWeightSet.forEach((value, key) => { console.log("value:" + value, key); }); -try { - lightWeightSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -735,7 +632,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -753,11 +650,6 @@ while(index < lightWeightSet.length) { console.log(JSON.stringify(iter.next().value)); index++; } -try { - lightWeightSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -777,7 +669,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -802,9 +694,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - lightWeightSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-linkedlist.md b/en/application-dev/reference/apis/js-apis-linkedlist.md index 81b7ee076547f3ac3acd72fb3267d8e84265e2b3..0e745d749c0967cd515a91356750f7de0703ace7 100644 --- a/en/application-dev/reference/apis/js-apis-linkedlist.md +++ b/en/application-dev/reference/apis/js-apis-linkedlist.md @@ -1,14 +1,13 @@ -# Linear Container LinkedList +# @ohos.util.LinkedList (Linear Container LinkedList) > **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. **LinkedList** is implemented based on the doubly linked list. Each node of the doubly linked list has references pointing to the previous element and the next element. When querying an element, the system traverses the list from the beginning or end. **LinkedList** offers efficient insertion and removal operations but supports low query efficiency. **LinkedList** allows null elements. Unlike **[List](js-apis-list.md)**, which is a singly linked list, **LinkedList** is a doubly linked list that supports insertion and removal at both ends. -**LinkedList** is less efficient in data access than **[ArrayList](js-apis-arraylist.md)**. +**LinkedList** is more efficient in data insertion than **[ArrayList](js-apis-arraylist.md)**, but less efficient in data access. **Recommended use case**: Use **LinkedList** for frequent insertion and removal operations. @@ -21,9 +20,6 @@ This topic uses the following to identify the use of generics: import LinkedList from '@ohos.util.LinkedList'; ``` - - - ## LinkedList ### Attributes @@ -45,7 +41,7 @@ A constructor used to create a **LinkedList** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -56,11 +52,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let linkedList = new LinkedList(); -try { - let linkedList2 = LinkedList(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -86,7 +77,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -103,11 +94,6 @@ let result2 = linkedList.add(b); let c = {name : "Dylon", age : "13"}; let result3 = linkedList.add(c); let result4 = linkedList.add(false); -try { - linkedList.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### addFirst @@ -126,7 +112,7 @@ Adds an element at the top of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -143,11 +129,6 @@ linkedList.addFirst(b); let c = {name : "Dylon", age : "13"}; linkedList.addFirst(c); linkedList.addFirst(false); -try { - linkedList.addFirst.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insert @@ -167,12 +148,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -181,16 +162,6 @@ let linkedList = new LinkedList(); linkedList.insert(0, "A"); linkedList.insert(1, 0); linkedList.insert(2, true); -try { - linkedList.insert.bind({}, 3, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.insert(6, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -215,7 +186,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -228,11 +199,6 @@ let linkedList = new LinkedList(); let result1 = linkedList.has("squirrel"); linkedList.add("squirrel"); let result = linkedList.has("squirrel"); -try { - linkedList.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### get @@ -257,7 +223,7 @@ Obtains an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -275,11 +241,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.get(2); -try { - linkedList.get.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -304,7 +265,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -322,11 +283,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.getLastIndexOf(2); -try { - linkedList.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -351,7 +307,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -369,11 +325,6 @@ linkedList.add(1); linkedList.add(2); linkedList.add(4); let result = linkedList.getIndexOf(2); -try { - linkedList.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -398,12 +349,12 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -415,16 +366,6 @@ linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeByIndex(2); -try { - linkedList.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.removeByIndex(8); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeFirst @@ -443,33 +384,23 @@ Removes the first element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirst method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeFirst(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeFirst(); -try { - linkedList.removeFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeLast @@ -488,33 +419,23 @@ Removes the last element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeLast method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeLast(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(2); linkedList.add(4); let result = linkedList.removeLast(); -try { - linkedList.removeLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -539,7 +460,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -554,11 +475,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.remove(2); -try { - linkedList.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeFirstFound @@ -583,32 +499,22 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeFirstFound method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeFirstFound(4); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.removeFirstFound(4); -try { - linkedList.removeFirstFound.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeLastFound @@ -633,32 +539,22 @@ Removes the last occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeLastFound method cannot be bound. | -| 10200010 | Container is empty. | +| 10200010 | The container is empty. | **Example** ```ts let linkedList = new LinkedList(); -try { - linkedList.removeLastFound(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} linkedList.add(2); linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.removeLastFound(4); -try { - linkedList.removeLastFound.bind({}, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -677,7 +573,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -692,16 +588,11 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.clone(); -try { - linkedList.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, +forEach(callbackFn: (value: T, index?: number, LinkedList?: LinkedList<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -712,7 +603,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -725,7 +616,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -742,13 +633,6 @@ linkedList.add(4); linkedList.forEach((value, index) => { console.log("value:" + value, index); }); -try { - linkedList.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -761,7 +645,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -776,11 +660,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); linkedList.clear(); -try { - linkedList.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### set @@ -806,12 +685,12 @@ Replaces an element at the specified position in this container with a given ele **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -822,16 +701,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.set(2, "b"); -try { - linkedList.set.bind({}, 2, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - linkedList.set(8, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -850,7 +719,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -864,11 +733,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.convertToArray(); -try { - linkedList.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -887,7 +751,7 @@ Obtains the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -902,11 +766,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); let result = linkedList.getFirst(); -try { - linkedList.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -925,7 +784,7 @@ Obtains the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -940,11 +799,6 @@ linkedList.add(4); linkedList.add(5); linkedList.add(4); linkedList.getLast(); -try { - linkedList.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -963,7 +817,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -990,9 +844,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - linkedList[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-list.md b/en/application-dev/reference/apis/js-apis-list.md index 181febf4ebe037fe37ec061efe832bd4f9a387cd..bd1272f3a7a48a47f30ba689ff9df972932727d6 100644 --- a/en/application-dev/reference/apis/js-apis-list.md +++ b/en/application-dev/reference/apis/js-apis-list.md @@ -1,7 +1,6 @@ -# Linear Container List +# @ohos.util.List (Linear Container List) > **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. **List** is implemented based on the singly linked list. Each node has a reference pointing to the next element. When querying an element, the system traverses the list from the beginning. **List** offers efficient insertion and removal operations but supports low query efficiency. **List** allows null elements. @@ -16,7 +15,7 @@ This topic uses the following to identify the use of generics: ## Modules to Import ```ts -import List from '@ohos.util.List'; +import List from '@ohos.util.List'; ``` @@ -26,7 +25,7 @@ import List from '@ohos.util.List'; **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description| +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | length | number | Yes| No| Number of elements in a list (called container later).| @@ -41,7 +40,7 @@ A constructor used to create a **List** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -51,11 +50,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let list = new List(); -try { - let list2 = List(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -81,7 +75,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -98,11 +92,6 @@ let result3 = list.add(b); let c = {name : "Dylon", age : "13"}; let result4 = list.add(c); let result5 = list.add(false); -try { - list.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### insert @@ -122,12 +111,12 @@ Inserts an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The insert method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -136,16 +125,6 @@ let list = new List(); list.insert("A", 0); list.insert(0, 1); list.insert(true, 2); -try { - list.insert.bind({}, "b", 3)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.insert("b", 6); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### has @@ -170,7 +149,7 @@ Checks whether this container has the specified element. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -183,11 +162,6 @@ let list = new List(); let result = list.has("squirrel"); list.add("squirrel"); let result1 = list.has("squirrel"); -try { - list.has.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### get @@ -212,7 +186,7 @@ Obtains the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -230,11 +204,6 @@ list.add(1); list.add(2); list.add(4); let result = list.get(2); -try { - list.get.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLastIndexOf @@ -259,7 +228,7 @@ Obtains the index of the last occurrence of the specified element in this contai **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -277,11 +246,6 @@ list.add(1); list.add(2); list.add(4); let result = list.getLastIndexOf(2); -try { - list.getLastIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getIndexOf @@ -306,7 +270,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -325,11 +289,6 @@ list.add(2); list.add(4); list.getIndexOf(2); let result = list.getIndexOf(2); -try { - list.getIndexOf.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### equal @@ -354,7 +313,7 @@ Compares whether a specified object is equal to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -375,11 +334,6 @@ obj1.add(5); list.equal(obj1); let obj2 = {name : "Dylon", age : "13"}; let result = list.equal(obj2); -try { - list.equal.bind({}, obj2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### removeByIndex @@ -404,12 +358,12 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeByIndex method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -421,16 +375,6 @@ list.add(5); list.add(2); list.add(4); let result = list.removeByIndex(2); -try { - list.removeByIndex.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.removeByIndex(8); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### remove @@ -455,7 +399,7 @@ Removes the first occurrence of the specified element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -470,16 +414,11 @@ list.add(4); list.add(5); list.add(4); let result = list.remove(2); -try { - list.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, list?: List<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, list?: List<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -490,7 +429,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for the replacement.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -503,7 +442,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -523,18 +462,11 @@ list.replaceAllElements((value: number, index: number) => { list.replaceAllElements((value: number, index: number) => { return value = value - 2; }); -try { - list.replaceAllElements.bind({}, (value: number, index: number) => { - return value = 2 * value; - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, List?: List<T>) => void, +forEach(callbackFn: (value: T, index?: number, List?: List<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -545,7 +477,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Value Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked for the replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -558,7 +490,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -575,14 +507,6 @@ list.add(4); list.forEach((value, index) => { console.log("value: " + value, index); }); -try { - list.forEach.bind({}, (value, index) => { - console.log("value: " + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} - ``` ### sort @@ -608,7 +532,7 @@ comparator **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -622,13 +546,8 @@ list.add(2); list.add(4); list.add(5); list.add(4); -list.sort((a: number, b: number) => a - b); -list.sort((a: number, b: number) => b - a); -try { - list.sort.bind({}, (a: number, b: number) => b - a)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} +list.sort((a: number, b: number) => a - b); // The elements are sorted in ascending order. +list.sort((a: number, b: number) => b - a); // The elements are sorted in descending order. ``` ### getSubList @@ -654,12 +573,12 @@ Obtains elements within a range in this container, including the element at the **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getSubList method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of fromIndex or toIndex is out of range. | **Example** @@ -672,16 +591,6 @@ list.add(4); let result = list.getSubList(2, 4); let result1 = list.getSubList(4, 3); let result2 = list.getSubList(2, 6); -try { - list.getSubList.bind({}, 2, 4)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.getSubList(2, 10); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clear @@ -694,7 +603,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -709,11 +618,6 @@ list.add(4); list.add(5); list.add(4); list.clear(); -try { - list.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### set @@ -739,12 +643,12 @@ Replaces an element at the specified position in this container with a given ele **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The set method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -755,16 +659,6 @@ list.add(4); list.add(5); list.add(4); list.set(2, "b"); -try { - list.set.bind({}, 3, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - list.set(8, "b"); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### convertToArray @@ -783,7 +677,7 @@ Converts this container into an array. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -798,11 +692,6 @@ list.add(4); list.add(5); list.add(4); let result = list.convertToArray(); -try { - list.convertToArray.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -821,7 +710,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -836,11 +725,6 @@ list.add(4); list.add(5); list.add(4); let result = list.isEmpty(); -try { - list.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -859,7 +743,7 @@ Obtains the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -874,11 +758,6 @@ list.add(4); list.add(5); list.add(4); let result = list.getFirst(); -try { - list.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getLast @@ -897,7 +776,7 @@ Obtains the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -912,11 +791,6 @@ list.add(4); list.add(5); list.add(4); let result = list.getLast(); -try { - list.getLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -935,7 +809,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -962,9 +836,4 @@ while(temp != undefined) { console.log("value: " + temp); temp = iter.next().value; } -try { - list[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-logs.md b/en/application-dev/reference/apis/js-apis-logs.md index e2d0aff5a5eec1f468b0511a08f1f593a9af3548..48cc7954e1b4315f0e12d9571395decf9592b90d 100644 --- a/en/application-dev/reference/apis/js-apis-logs.md +++ b/en/application-dev/reference/apis/js-apis-logs.md @@ -1,6 +1,6 @@ -# Log +# console (Log) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE**
> The APIs of this module are no longer maintained since API version 7. You are advised to use ['@ohos.hilog](js-apis-hilog.md)' instead. ## console.debug diff --git a/en/application-dev/reference/apis/js-apis-matrix4.md b/en/application-dev/reference/apis/js-apis-matrix4.md new file mode 100644 index 0000000000000000000000000000000000000000..f5b9b27f55ed9d363939bef6f55582423afe4a28 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-matrix4.md @@ -0,0 +1,474 @@ +# @ohos.matrix4 + +The **matrix4** module provides APIs for matrix transformation. You can use these APIs to translate, rotate, and scale images. + +> **NOTE** +> +> 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 +import matrix4 from '@ohos.matrix4' +``` + + +## matrix4.init + +init(array: Array<number>): Matrix4Transit + + +Matrix constructor, which is used to create a 4x4 matrix by using the input parameter. Column-major order is used. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ------------------------------------------------------------ | +| array | Array<number> | Yes | A number array whose length is 16 (4 x 4). For details, see **array** parameters.
Default value:
[1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1] | + +**Return value** + +| Type | Description | +| -------------- | ---------------------------- | +| Matrix4Transit | 4x4 matrix object created based on the input parameter.| + +**array** parameters + +| Name | Type | Mandatory | Description | +| ---- | ------ | ---- | -------------------- | +| m00 | number | Yes | Scaling value of the x-axis. The default value is **1** for the identity matrix. | +| m01 | number | Yes | The second value, which is affected by the rotation of the x, y, and z axes. | +| m02 | number | Yes | The third value, which is affected by the rotation of the x, y, and z axes. | +| m03 | number | Yes | The fourth value, which is meaningless. | +| m10 | number | Yes | The fifth value, which is affected by the rotation of the x, y, and z axes. | +| m11 | number | Yes | Scaling value of the y-axis. The default value is **1** for the identity matrix. | +| m12 | number | Yes | The seventh value, which is affected by the rotation of the x, y, and z axes. | +| m13 | number | Yes | The eighth value, which is meaningless. | +| m20 | number | Yes | The ninth value, which is affected by the rotation of the x, y, and z axes. | +| m21 | number | Yes | The tenth value, which is affected by the rotation of the x, y, and z axes. | +| m22 | number | Yes | Scaling value of the z-axis. The default value is **1** for the identity matrix. | +| m23 | number | Yes | Meaningless value. | +| m30 | number | Yes | Translation value of the x-axis, in px. The default value is **0** for the identity matrix.| +| m31 | number | Yes | Translation value of the y-axis, in px. The default value is **0** for the identity matrix.| +| m32 | number | Yes | Translation value of the z-axis, in px. The default value is **0** for the identity matrix.| +| m33 | number | Yes | Valid in homogeneous coordinates, presenting the perspective projection effect. | + +**Example** + +```ts +import matrix4 from '@ohos.matrix4' +// Create a 4 x 4 matrix. +let matrix = matrix4.init([1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0]) +@Entry +@Component +struct Tests { + build() { + Column() { + Image($r("app.media.zh")) + .width("40%") + .height(100) + .transform(matrix) + } + } +} +``` + + +## matrix4.identity + +identity(): Matrix4Transit + + +Constructs an identity matrix. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| -------------- | -------------- | +| Matrix4Transit | Identity matrix object.| + +**Example** + +```ts +// The effect of matrix 1 is the same as that of matrix 2. +import matrix4 from '@ohos.matrix4' +let matrix1 = matrix4.init([1.0, 0.0, 0.0, 0.0, + 0.0, 1.0, 0.0, 0.0, + 0.0, 0.0, 1.0, 0.0, + 0.0, 0.0, 0.0, 1.0]) +let matrix2 = matrix4.identity() +@Entry +@Component +struct Tests { + build() { + Column() { + Image($r("app.media.zh")) + .width("40%") + .height(100) + .transform(matrix1) + Image($r("app.media.zh")) + .width("40%") + .height(100) + .margin({ top: 150 }) + .transform(matrix2) + } + } +} +``` + + +## matrix4.copy + +copy(): Matrix4Transit + + +Copies this matrix object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Matrix4Transit | Copy object of the current matrix.| + +**Example** + +```ts +// xxx.ets +import matrix4 from '@ohos.matrix4' + +@Entry +@Component +struct Test { + private matrix1 = matrix4.identity().translate({ x: 100 }) + private matrix2 = this.matrix1.copy().scale({ x: 2 }) + + build() { + Column() { + Image($r("app.media.bg1")) + .width("40%") + .height(100) + .transform(this.matrix1) + Image($r("app.media.bg2")) + .width("40%") + .height(100) + .margin({ top: 50 }) + .transform(this.matrix2) + } + } +} +``` + +![en-us_image_0000001219744181](figures/en-us_image_0000001219744181.png) + + +## Matrix4 + + +### combine + +combine(matrix: Matrix4): Matrix4Transit + + +Combines the effects of two matrices to generate a new matrix object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------ | +| matrix | Matrix4 | Yes | Matrix object to be combined.| + +**Return value** + +| Type | Description | +| -------------- | ------------------ | +| Matrix4Transit | Object after matrix combination.| + +**Example** + +```ts +// xxx.ets +import matrix4 from '@ohos.matrix4' + +@Entry +@Component +struct Test { + private matrix1 = matrix4.identity().translate({ x: 200 }).copy() + private matrix2 = matrix4.identity().scale({ x: 2 }).copy() + + build() { + Column() { + // Before matrix transformation + Image($r("app.media.icon")) + .width("40%") + .height(100) + .margin({ top: 50 }) + // Translate the x-axis by 200px, and then scale it twice to obtain the resultant matrix. + Image($r("app.media.icon")) + .transform(this.matrix1.combine(this.matrix2)) + .width("40%") + .height(100) + .margin({ top: 50 }) + } + } +} +``` + +![en-us_image_0000001118642902](figures/en-us_image_0000001118642902.png) + + +### invert + +invert(): Matrix4Transit + +Inverts this matrix object. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Return value** + +| Type | Description | +| -------------- | ---------------------- | +| Matrix4Transit | Inverse matrix object of the current matrix.| + +**Example** + +```ts +import matrix4 from '@ohos.matrix4' +// The effect of matrix 1 (width scaled up by 2x) is opposite to that of matrix 2 (width scaled down by 2x). +let matrix1 = matrix4.identity().scale({ x: 2 }) +let matrix2 = matrix1.invert() + +@Entry +@Component +struct Tests { + build() { + Column() { + Image($r("app.media.zh")) + .width(200) + .height(100) + .transform(matrix1) + .margin({ top: 100 }) + Image($r("app.media.zh")) + .width(200) + .height(100) + .margin({ top: 150 }) + .transform(matrix2) + } + } +} +``` + + +### translate + +translate({x?: number, y?: number, z?: number}): Matrix4Transit + +Translates this matrix object along the x, y, and z axes. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------- | +| x | number | No | Translation distance along the x-axis, in px.
Default value: **0**| +| y | number | No | Translation distance along the y-axis, in px.
Default value: **0**| +| z | number | No | Translation distance along the z-axis, in px.
Default value: **0**| + +**Return value** + +| Type | Description | +| -------------- | ---------------------------- | +| Matrix4Transit | Matrix object after the translation effect is added.| + +**Example** + +```ts +// xxx.ets +import matrix4 from '@ohos.matrix4' + +@Entry +@Component +struct Test { + private matrix1 = matrix4.identity().translate({ x: 100, y: 200, z: 30 }) + + build() { + Column() { + Image($r("app.media.bg1")).transform(this.matrix1) + .width("40%") + .height(100) + } + } +} +``` + +![en-us_image_0000001219662645](figures/en-us_image_0000001219662645.png) + + +### scale + +scale({x?: number, y?: number, z?: number, centerX?: number, centerY?: number}): Matrix4Transit + + +Scales this matrix object along the x, y, and z axes. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------- | +| x | number | No | Scaling multiple along the x-axis.
Default value: **1** | +| y | number | No | Scaling multiple along the y-axis.
Default value: **1** | +| z | number | No | Scaling multiple along the z-axis.
Default value: **1** | +| centerX | number | No | X coordinate of the center point.
Default value: **0**| +| centerY | number | No | Y coordinate of the center point.
Default value: **0**| + +**Return value** + +| Type | Description | +| -------------- | ---------------------------- | +| Matrix4Transit | Matrix object after the scaling effect is added.| + +**Example** + +```ts +// xxx.ets +import matrix4 from '@ohos.matrix4' +@Entry +@Component +struct Test { + private matrix1 = matrix4.identity().scale({ x:2, y:3, z:4, centerX:50, centerY:50 }) + + build() { + Column() { + Image($r("app.media.bg1")).transform(this.matrix1) + .width("40%") + .height(100) + } + } +} +``` + +![en-us_image_0000001219864131](figures/en-us_image_0000001219864131.png) + + +### rotate + +rotate({x?: number, y?: number, z?: number, angle?: number, centerX?: Length, centerY?: Length}): Matrix4Transit + + +Rotates this matrix object along the x, y, and z axes. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | --------------------------------- | +| x | number | No | X coordinate of the rotation axis vector.
Default value: **1** | +| y | number | No | Y coordinate of the rotation axis vector.
Default value: **1** | +| z | number | No | Z coordinate of the rotation axis vector.
Default value: **1** | +| angle | number | No | Rotation angle.
Default value: **0** | +| centerX | number | No | X coordinate of the center point.
Default value: **0**| +| centerY | number | No | Y coordinate of the center point.
Default value: **0**| + +**Return value** + +| Type | Description | +| -------------- | ---------------------------- | +| Matrix4Transit | Matrix object after the rotation effect is added.| + +**Example** + +```ts +// xxx.ets +import matrix4 from '@ohos.matrix4' + +@Entry +@Component +struct Test { + private matrix1 = matrix4.identity().rotate({ x: 1, y: 1, z: 2, angle: 30 }) + + build() { + Column() { + Image($r("app.media.bg1")).transform(this.matrix1) + .width("40%") + .height(100) + }.width("100%").margin({ top: 50 }) + } +} +``` + +![en-us_image_0000001174422898](figures/en-us_image_0000001174422898.png) + + +### transformPoint + +transformPoint(point: Point): Point + + +Applies the current transformation effect to a coordinate point. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----- | ---- | ------------------ | +| point | Point | Yes | Point to be transformed.| + +**Return value** + +| Type | Description | +| ----- | ---------------- | +| Point | Point object after matrix transformation| + +**Example** + +```ts +// xxx.ets +import matrix4 from '@ohos.matrix4' + +@Entry +@Component +struct Test { + private originPoint: [number, number] = [50, 50] + private matrix_1 = matrix4.identity().translate({ x: 150, y: -50 }) + private transformPoint = this.matrix_1.transformPoint(this.originPoint) + private matrix_2 = matrix4.identity().translate({ x: this.transformPoint[0], y: this.transformPoint[1] }) + + build() { + Column() { + Text(`Coordinates before matrix transformation: [${this.originPoint}]`) + .fontSize(16) + Image($r("app.media.image")) + .width('600px') + .height('300px') + .margin({ top: 50 }) + Text(`Coordinates before matrix transformation: [${this.transformPoint}]`) + .fontSize(16) + .margin({ top: 100 }) + Image($r("app.media.image")) + .width('600px') + .height('300px') + .margin({ top: 50 }) + .transform(this.matrix_2) + }.width("100%").padding(50) + } +} +``` + +![en-us_image_0000001219864133](figures/en-us_image_0000001219864133.PNG) diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index 8c4dd734fbdbe5d2a3d2bbd621f04f54ed20d883..6d395fd5f21b8b041f7930ae96002dc430fd650b 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -1,4 +1,4 @@ -# Media +# @ohos.multimedia.media (Media) > **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. @@ -52,7 +52,7 @@ Creates a **VideoPlayer** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.| +| callback | AsyncCallback<[VideoPlayer](#videoplayer8)> | Yes | Callback used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| **Example** @@ -81,7 +81,7 @@ Creates a **VideoPlayer** instance. This API uses a promise to return the result | Type | Description | | ------------------------------------- | ------------------------------------------------------------ | -| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video media.| +| Promise<[VideoPlayer](#videoplayer8)> | Promise used to return the result. If the operation is successful, the **VideoPlayer** instance is returned; otherwise, **null** is returned. The instance can be used to manage and play video.| **Example** @@ -113,7 +113,7 @@ Only one **AudioRecorder** instance can be created per device. | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. The instance can be used to record audio media.| +| [AudioRecorder](#audiorecorder) | Returns the **AudioRecorder** instance if the operation is successful; returns **null** otherwise. The instance can be used to record audio.| **Example** @@ -130,11 +130,21 @@ Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------- | ---- | ------------------------------ | -| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.| +| callback | AsyncCallback<[VideoRecorder](#videorecorder9)> | Yes | Callback used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------ | +| 5400101 | No memory. Return by callback. | **Example** @@ -160,11 +170,21 @@ Only one **AudioRecorder** instance can be created per device. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | ----------------------------------------- | ------------------------------------------------------------ | -| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video media.| +| Promise<[VideoRecorder](#videorecorder9)> | Promise used to return the result. If the operation is successful, the **VideoRecorder** instance is returned; otherwise, **null** is returned. The instance can be used to record video.| + +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------- | +| 5400101 | No memory. Return by promise. | **Example** @@ -277,7 +297,7 @@ For details about the audio playback demo, see [Audio Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------------- | ------------------------------------------------------ | ---- | ---- | ------------------------------------------------------------ | | src | string | Yes | Yes | Audio file URI. The mainstream audio formats (M4A, AAC, MPEG-3, OGG, and WAV) are supported.
**Examples of supported URI schemes**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
**Required permissions**: ohos.permission.READ_MEDIA or ohos.permission.INTERNET| -| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
If the file is an independent music file, use **src=fd://xx**.
| +| fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes | Yes | Description of the audio file. This attribute is required when audio resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Music 1 (address offset: 0, byte length: 100)
Music 2 (address offset: 101; byte length: 50)
Music 3 (address offset: 151, byte length: 150)
1. To play music 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play music 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play music 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent music file, use **src=fd://xx**.
| | loop | boolean | Yes | Yes | Whether to loop audio playback. The value **true** means to loop audio playback, and **false** means the opposite. | | audioInterruptMode9+ | [audio.InterruptMode](js-apis-audio.md#interruptmode9) | Yes | Yes | Audio interruption mode. | | currentTime | number | Yes | No | Current audio playback position, in ms. | @@ -338,7 +358,7 @@ audioPlayer.stop(); reset(): void -Switches the audio resource to be played. +Resets the audio asset to be played. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -496,7 +516,7 @@ for (let i = 0; i < arrayDescription.length; i++) { on(type: 'bufferingUpdate', callback: (infoType: [BufferingInfoType](#bufferinginfotype8), value: number) => void): void -Subscribes to the audio buffering update event. Only network playback supports this subscription. +Subscribes to the audio buffering update event. This API works only under online playback. **System capability**: SystemCapability.Multimedia.Media.AudioPlayer @@ -669,7 +689,7 @@ Describes audio and video file resources. It is used to specify a particular res ## VideoPlayer8+ -Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must call [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. +Provides APIs to manage and play video. Before calling an API of **VideoPlayer**, you must use [createVideoPlayer()](#mediacreatevideoplayer8) to create a [VideoPlayer](#videoplayer8) instance. For details about the video playback demo, see [Video Playback Development](../../media/video-playback.md). @@ -679,7 +699,7 @@ For details about the video playback demo, see [Video Playback Development](../. | Name | Type | Readable| Writable| Description | | ------------------------ | ---------------------------------- | ---- | ---- | ------------------------------------------------------------ | -| url8+ | string | Yes | Yes | Video media URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
| +| url8+ | string | Yes | Yes | Video URL. The mainstream video formats (MPEG-4, MPEG-TS, WebM, and MKV) are supported.
**Example of supported URIs**:
1. FD: fd://xx
![](figures/en-us_image_url.png)
2. HTTP: http://xx
3. HTTPS: https://xx
4. HLS: http://xx or https://xx
| | fdSrc9+ | [AVFileDescriptor](#avfiledescriptor9) | Yes| Yes| Description of a video file. This attribute is required when video resources of an application are continuously stored in a file.
**Example:**
Assume that a music file that stores continuous music resources consists of the following:
Video 1 (address offset: 0, byte length: 100)
Video 2 (address offset: 101; byte length: 50)
Video 3 (address offset: 151, byte length: 150)
1. To play video 1: AVFileDescriptor {fd = resource handle; offset = 0; length = 100; }
2. To play video 2: AVFileDescriptor {fd = resource handle; offset = 101; length = 50; }
3. To play video 3: AVFileDescriptor {fd = resource handle; offset = 151; length = 150; }
To play an independent video file, use **src=fd://xx**.
| | loop8+ | boolean | Yes | Yes | Whether to loop video playback. The value **true** means to loop video playback, and **false** means the opposite. | | videoScaleType9+ | [VideoScaleType](#videoscaletype9) | Yes | Yes | Video scale type. | @@ -702,10 +722,10 @@ Sets **SurfaceId**. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------- | ---- | ------------------------- | -| surfaceId | string | Yes | Surface ID to set. | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| --------- | -------------------- | ---- | ------------------------- | +| surfaceId | string | Yes | Surface ID to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -763,9 +783,9 @@ Prepares for video playback. This API uses an asynchronous callback to return th **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -813,9 +833,9 @@ Starts to play video resources. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -863,9 +883,9 @@ Pauses video playback. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -913,9 +933,9 @@ Stops video playback. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -957,15 +977,15 @@ videoPlayer.stop().then(() => { reset(callback: AsyncCallback\): void -Switches the video resource to be played. This API uses an asynchronous callback to return the result. +Resets the video asset to be played. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -983,7 +1003,7 @@ videoPlayer.reset((err) => { reset(): Promise\ -Switches the video resource to be played. This API uses a promise to return the result. +Resets the video asset to be played. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer @@ -1013,10 +1033,10 @@ Seeks to the specified playback position. The next key frame at the specified po **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1045,7 +1065,7 @@ Seeks to the specified playback position. This API uses an asynchronous callback | -------- | ---------------------- | ---- | ------------------------------------------------------------ | | timeMs | number | Yes | Position to seek to, in ms. The value range is [0, duration].| | mode | [SeekMode](#seekmode8) | Yes | Seek mode. | -| callback | function | Yes | Callback used to return the result. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1080,7 +1100,7 @@ Seeks to the specified playback position. If **mode** is not specified, the next | Type | Description | | -------------- | ------------------------------------------- | -| Promise\ | Promise used to return the playback position, in ms.| +| Promise\| Promise used to return the playback position, in ms.| **Example** @@ -1110,10 +1130,10 @@ Sets the volume. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------------------------------------------ | -| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| vol | number | Yes | Relative volume. The value ranges from 0.00 to 1.00. The value **1** indicates the maximum volume (100%).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1169,9 +1189,9 @@ Releases the video playback resource. This API uses an asynchronous callback to **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ------------------------ | -| callback | function | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1295,10 +1315,10 @@ Sets the video playback speed. This API uses an asynchronous callback to return **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------- | ---- | ---------------------------------------------------------- | -| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| -| callback | function | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------------------------------------------- | +| speed | number | Yes | Video playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -1333,7 +1353,7 @@ Sets the video playback speed. This API uses a promise to return the result. | Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| +| Promise\| Promise used to return playback speed. For details, see [PlaybackSpeed](#playbackspeed8).| **Example** @@ -1348,65 +1368,6 @@ videoPlayer.setSpeed(speed).then(() => { }); ``` -### selectBitrate9+ - -selectBitrate(bitrate:number, callback: AsyncCallback\): void - -Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ---------------------------------------------------------- | -| bitrate | number | Yes | Bit rate to select, which is used in the HLS multi-bit rate scenario. The unit is bit/s. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the set value is returned, the operation is successful; otherwise, the operation fails.| - -**Example** - -```js -let bitrate = 1024000; -videoPlayer.selectBitrate(bitrate, (err, result) => { - if (err == null) { - console.info('selectBitrate success!'); - } else { - console.info('selectBitrate fail!'); - } -}); -``` - -### selectBitrate9+ - -selectBitrate(bitrate:number): Promise\ - -Selects a bit rate from available ones, which can be obtained by calling [availableBitratesCollect](#onavailablebitratescollect9). This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Media.VideoPlayer - -**Parameters** - -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | -------------------------------------------- | -| bitrate | number | Yes | Bit rate, which is used in the HLS multi-bit rate scenario. The unit is bit/s.| - -**Return value** - -| Type | Description | -| ---------------- | --------------------------- | -| Promise\ | Promise used to return the bit rate.| - -**Example** - -```js -let bitrate = 1024000; -videoPlayer.selectBitrate(bitrate).then(() => { - console.info('selectBitrate success'); -}).catch((error) => { - console.info(`video catchCallback, error:${error}`); -}); -``` - ### on('playbackCompleted')8+ on(type: 'playbackCompleted', callback: Callback\): void @@ -1596,7 +1557,7 @@ Enumerates the video scale modes. **System capability**: SystemCapability.Multimedia.Media.VideoPlayer -| Name | Default Value| Description | +| Name | Value| Description | | ---------------------------- | ------ | ---------- | | VIDEO_SCALE_TYPE_FIT | 0 | The video will be stretched to fit the window.| | VIDEO_SCALE_TYPE_FIT_CROP| 1 | The video will be stretched to fit the window, without changing its aspect ratio. The content may be cropped. | @@ -1630,7 +1591,7 @@ audioPlayer.getTrackDescription((error, arrList) => { ## AudioRecorder -Implements audio recording. Before calling an API of **AudioRecorder**, you must call [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. +Implements audio recording. Before calling an API of **AudioRecorder**, you must use [createAudioRecorder()](#mediacreateaudiorecorder) to create an [AudioRecorder](#audiorecorder) instance. For details about the audio recording demo, see [Audio Recording Development](../../media/audio-recorder.md). @@ -1890,13 +1851,13 @@ Enumerates the audio encoding formats. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder -| Name | Default Value| Description | -| ------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet.| -| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| -| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| -| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| -| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| +| Name | Value | Description | +| ------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | Default encoding format.
This API is defined but not implemented yet. | +| AMR_NB | 1 | AMR-NB.
This API is defined but not implemented yet.| +| AMR_WB | 2 | Adaptive Multi Rate-Wide Band Speech Codec (AMR-WB).
This API is defined but not implemented yet.| +| AAC_LC | 3 | Advanced Audio Coding Low Complexity (AAC-LC).| +| HE_AAC | 4 | High-Efficiency Advanced Audio Coding (HE_AAC).
This API is defined but not implemented yet.| ## AudioOutputFormat(deprecated) @@ -1908,13 +1869,13 @@ Enumerates the audio output formats. **System capability**: SystemCapability.Multimedia.Media.AudioRecorder -| Name | Default Value| Description | -| -------- | ------ | ------------------------------------------------------------ | -| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet.| -| MPEG_4 | 2 | MPEG-4. | -| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet.| -| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet.| -| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| +| Name | Value | Description | +| -------- | ---- | ------------------------------------------------------------ | +| DEFAULT | 0 | Default encapsulation format.
This API is defined but not implemented yet. | +| MPEG_4 | 2 | MPEG-4. | +| AMR_NB | 3 | AMR_NB.
This API is defined but not implemented yet. | +| AMR_WB | 4 | AMR_WB.
This API is defined but not implemented yet. | +| AAC_ADTS | 6 | Audio Data Transport Stream (ADTS), which is a transport stream format of AAC-based audio.| ## VideoRecorder9+ @@ -1926,6 +1887,8 @@ For details about the video recording demo, see [Video Recording Development](.. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Type | Readable| Writable| Description | | ------------------ | -------------------------------------- | ---- | ---- | ---------------- | | state9+ | [VideoRecordState](#videorecordstate9) | Yes | No | Video recording state.| @@ -1940,6 +1903,8 @@ Sets video recording parameters. This API uses an asynchronous callback to retur **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | @@ -1947,6 +1912,17 @@ Sets video recording parameters. This API uses an asynchronous callback to retur | config | [VideoRecorderConfig](#videorecorderconfig9) | Yes | Video recording parameters to set. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 201 | Permission denied. Return by callback. | +| 401 | Parameter error. Return by callback. | +| 5400102 | Operation not allowed. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -1992,6 +1968,8 @@ Sets video recording parameters. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name| Type | Mandatory| Description | @@ -2004,6 +1982,17 @@ Sets video recording parameters. This API uses a promise to return the result. | -------------- | ---------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 201 | Permission denied. Return by promise. | +| 401 | Parameter error. Return by promise. | +| 5400102 | Operation not allowed. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2049,12 +2038,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------- | ---- | --------------------------- | | callback | AsyncCallback\ | Yes | Callback used to obtain the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2082,12 +2083,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) is called **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | ---------------- | -------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2111,12 +2124,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2140,12 +2165,24 @@ This API can be called only after [prepare()](#videorecorder_prepare1) and [getI **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2167,12 +2204,24 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2196,12 +2245,24 @@ This API can be called only after [start()](#videorecorder_start1) is called. Yo **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2221,12 +2282,24 @@ Resumes video recording. This API uses an asynchronous callback to return the re **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2248,12 +2321,24 @@ Resumes video recording. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2275,12 +2360,24 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ------------------------------------------ | +| 5400102 | Operation not allowed. Return by callback. | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2304,12 +2401,24 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 5400102 | Operation not allowed. Return by promise. | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2329,12 +2438,22 @@ Releases the video recording resource. This API uses an asynchronous callback to **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | -------------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2356,12 +2475,22 @@ Releases the video recording resource. This API uses a promise to return the res **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2383,12 +2512,23 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2412,12 +2552,23 @@ To start another recording, you must call [prepare()](#videorecorder_prepare1) a **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + **Return value** | Type | Description | | -------------- | ------------------------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | -------------------------------- | +| 5400103 | I/O error. Return by promise. | +| 5400105 | Service died. Return by promise. | + **Example** ```js @@ -2444,6 +2595,15 @@ Subscribes to video recording error events. After an error event is reported, yo | type | string | Yes | Event type, which is **'error'** in this case.
The **'error'** event is triggered when an error occurs during video recording.| | callback | ErrorCallback | Yes | Callback invoked when the event is triggered. | +**Error codes** + +For details about the error codes, see [Media Error Codes](../errorcodes/errorcode-media.md). + +| ID| Error Message | +| -------- | --------------------------------- | +| 5400103 | I/O error. Return by callback. | +| 5400105 | Service died. Return by callback. | + **Example** ```js @@ -2459,6 +2619,8 @@ Enumerates the video recording states. You can obtain the state through the **st **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Type | Description | | -------- | ------ | ---------------------- | | idle | string | The video recorder is idle. | @@ -2474,7 +2636,9 @@ Describes the video recording parameters. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder -| Name | Type | Mandatory| Description | +**System API**: This is a system API. + +| Name | Type | Mandatory| Description | | --------------- | ---------------------------------------------- | ---- | ------------------------------------------------------------ | | audioSourceType | [AudioSourceType](#audiosourcetype9) | Yes | Type of the audio source for video recording. | | videoSourceType | [VideoSourceType](#videosourcetype9) | Yes | Type of the video source for video recording. | @@ -2489,6 +2653,8 @@ Enumerates the audio source types for video recording. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Value | Description | | ------------------------- | ---- | ---------------------- | | AUDIO_SOURCE_TYPE_DEFAULT | 0 | Default audio input source.| @@ -2500,6 +2666,8 @@ Enumerates the video source types for video recording. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder +**System API**: This is a system API. + | Name | Value | Description | | ----------------------------- | ---- | ------------------------------- | | VIDEO_SOURCE_TYPE_SURFACE_YUV | 0 | The input surface carries raw data.| @@ -2511,7 +2679,9 @@ Describes the video recording profile. **System capability**: SystemCapability.Multimedia.Media.VideoRecorder -| Name | Type | Mandatory| Description | +**System API**: This is a system API. + +| Name | Type | Mandatory| Description | | ---------------- | -------------------------------------------- | ---- | ---------------- | | audioBitrate | number | Yes | Audio encoding bit rate.| | audioChannels | number | Yes | Number of audio channels.| @@ -2541,7 +2711,7 @@ Describes the geographical location of the recorded video. **System capability**: SystemCapability.Multimedia.Media.Core -| Name | Type| Mandatory| Description | -| --------- | -------- | ---- | ---------------- | -| latitude | number | Yes | Latitude of the geographical location.| -| longitude | number | Yes | Longitude of the geographical location.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ---------------- | +| latitude | number | Yes | Latitude of the geographical location.| +| longitude | number | Yes | Longitude of the geographical location.| diff --git a/en/application-dev/reference/apis/js-apis-medialibrary.md b/en/application-dev/reference/apis/js-apis-medialibrary.md index d77a386562bb6af94a38edfbd6574647bb93d91d..8298770c17f71299078a9bc1e541abef94cd6d0b 100644 --- a/en/application-dev/reference/apis/js-apis-medialibrary.md +++ b/en/application-dev/reference/apis/js-apis-medialibrary.md @@ -1,7 +1,6 @@ -# MediaLibrary +# @ohos.multimedia.medialibrary (Media Library Management) > **NOTE** -> > The APIs of this module are supported since API version 6. Updates will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -193,7 +192,7 @@ media.getFileAssets(imagesFetchOp).then(function(fetchFileResult) { ### on8+ -on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void +on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void Subscribes to the media library changes. This API uses an asynchronous callback to return the result. @@ -203,7 +202,7 @@ Subscribes to the media library changes. This API uses an asynchronous callback | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| | callback | Callback<void> | Yes | Void callback. | **Example** @@ -215,7 +214,7 @@ media.on('imageChange', () => { ``` ### off8+ -off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void +off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void Unsubscribes from the media library changes. This API uses an asynchronous callback to return the result. @@ -225,7 +224,7 @@ Unsubscribes from the media library changes. This API uses an asynchronous callb | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | ---------------------------------------- | -| type | 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| +| type | 'deviceChange'|
'albumChange'|
'imageChange'|
'audioChange'|
'videoChange'|
'fileChange'|
'remoteFileChange' | Yes | Media type.
'deviceChange': registered device change
'albumChange': album change
'imageChange': image file change
'audioChange': audio file change
'videoChange': video file change
'fileChange': file change
'remoteFileChange': file change on the registered device| | callback | Callback<void> | No | Void callback. | **Example** @@ -885,7 +884,7 @@ Obtains information about online peer devices. This API uses a promise to return | Type | Description | | ------------------- | -------------------- | -| Promise\> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| +| Promise\> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| **Example** @@ -921,7 +920,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal | Type | Description | | ------------------- | -------------------- | -| callback: AsyncCallback\> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| +| callback: AsyncCallback\> | Promise used to return the online peer devices, in an array of **PeerInfo** objects.| **Example** @@ -956,7 +955,7 @@ Obtains information about all peer devices. This API uses a promise to return th | Type | Description | | ------------------- | -------------------- | -| Promise\> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| +| Promise\> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| **Example** @@ -992,7 +991,7 @@ Obtains information about online peer devices. This API uses an asynchronous cal | Type | Description | | ------------------- | -------------------- | -| callback: AsyncCallback\> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| +| callback: AsyncCallback\> | Promise used to return all peer devices, in an array of **PeerInfo** objects.| **Example** @@ -1014,6 +1013,11 @@ async function example() { Provides APIs for encapsulating file asset attributes. +> **NOTE** +> +> 1. The system attempts to parse the file content if the file is an audio or video file. The actual field values will be restored from the passed values during scanning on some devices. +> 2. Some devices may not support the modification of **orientation**. You are advised to use [ModifyImageProperty](js-apis-image.md#modifyimageproperty9) of the **image** module. + ### Attributes **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -1025,7 +1029,7 @@ Provides APIs for encapsulating file asset attributes. | mimeType | string | Yes | No | Extended file attributes. | | mediaType8+ | [MediaType](#mediatype8) | Yes | No | Media type. | | displayName | string | Yes | Yes | Display file name, including the file name extension. | -| title | string | Yes | Yes | Title in the file. | +| title | string | Yes | Yes | Title in the file. By default, it carries the file name without extension. | | relativePath8+ | string | Yes | Yes | Relative public directory of the file. | | parent8+ | number | Yes | No | Parent directory ID. | | size | number | Yes | No | File size, in bytes. | @@ -2486,29 +2490,33 @@ Enumerates media types. Enumerates key file information. +> **NOTE** +> +> The **bucket_id** field may change after file rename or movement. Therefore, you must obtain the field again before using it. + **System capability**: SystemCapability.Multimedia.MediaLibrary.Core | Name | Value | Description | | ------------- | ------------------- | ---------------------------------------------------------- | -| ID | file_id | File ID. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | -| DISPLAY_NAME | display_name | Display file name. | -| PARENT | parent | Parent directory ID. | -| MIME_TYPE | mime_type | Extended file attributes. | -| MEDIA_TYPE | media_type | Media type. | -| SIZE | size | File size, in bytes. | -| DATE_ADDED | date_added | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_MODIFIED | date_modified | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | -| DATE_TAKEN | date_taken | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | -| TITLE | title | Title in the file. | -| ARTIST | artist | Artist of the file. | -| AUDIOALBUM | audio_album | Audio album. | -| DURATION | duration | Duration, in ms. | -| WIDTH | width | Image width, in pixels. | -| HEIGHT | height | Image height, in pixels. | -| ORIENTATION | orientation | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| -| ALBUM_ID | bucket_id | ID of the album to which the file belongs. | -| ALBUM_NAME | bucket_display_name | Name of the album to which the file belongs. | +| ID | "file_id" | File ID. | +| RELATIVE_PATH | "relative_path" | Relative public directory of the file. | +| DISPLAY_NAME | "display_name" | Display file name. | +| PARENT | "parent" | Parent directory ID. | +| MIME_TYPE | "mime_type" | Extended file attributes. | +| MEDIA_TYPE | "media_type" | Media type. | +| SIZE | "size" | File size, in bytes. | +| DATE_ADDED | "date_added" | Date when the file was added. (The value is the number of seconds elapsed since the Epoch time.) | +| DATE_MODIFIED | "date_modified" | Date when the file was modified. (The value is the number of seconds elapsed since the Epoch time.) | +| DATE_TAKEN | "date_taken" | Date when the file (photo) was taken. (The value is the number of seconds elapsed since the Epoch time.) | +| TITLE | "title" | Title in the file. | +| ARTIST | "artist" | Artist of the file. | +| AUDIOALBUM | "audio_album" | Audio album. | +| DURATION | "duration" | Duration, in ms. | +| WIDTH | "width" | Image width, in pixels. | +| HEIGHT | "height" | Image height, in pixels. | +| ORIENTATION | "orientation" | Image display direction (clockwise rotation angle, for example, 0, 90, and 180, in degrees).| +| ALBUM_ID | "bucket_id" | ID of the album to which the file belongs. | +| ALBUM_NAME | "bucket_display_name" | Name of the album to which the file belongs. | ## DirectoryType8+ @@ -2573,8 +2581,6 @@ Describes the image size. Implements the media asset option. -> **NOTE** -> > This API is deprecated since API version 9. **System capability**: SystemCapability.Multimedia.MediaLibrary.Core @@ -2598,5 +2604,5 @@ Describes media selection option. | Name | Type | Readable| Writable| Description | | ----- | ------ | ---- | ---- | -------------------- | -| type | string | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.| +| type | 'image' | 'video' | 'media' | Yes | Yes | Media type, which can be **image**, **media**, or **video**. Currently, only **media** is supported.| | count | number | Yes | Yes | Number of media assets selected. The value starts from 1, which indicates that one media asset can be selected. | diff --git a/en/application-dev/reference/apis/js-apis-mediaquery.md b/en/application-dev/reference/apis/js-apis-mediaquery.md index 4176338c0957632f67df2a74c73cd51a8ab1d48d..f44a0801b9ae1d9d4fec2f4485bf848e8595caa5 100644 --- a/en/application-dev/reference/apis/js-apis-mediaquery.md +++ b/en/application-dev/reference/apis/js-apis-mediaquery.md @@ -1,4 +1,4 @@ -# Media Query +# @ohos.mediaquery The **mediaquery** module provides different styles for different media types. @@ -14,64 +14,64 @@ import mediaquery from '@ohos.mediaquery' ``` -## Required Permissions - -None. - - ## mediaquery.matchMediaSync matchMediaSync(condition: string): MediaQueryListener -Sets the media query criteria and returns the corresponding listening handle. +Sets the media query condition. This API returns the corresponding media query listener. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | --------- | ------ | ---- | ---------------------------------------- | -| condition | string | Yes | Matching condition of a media event. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).| +| condition | string | Yes | Media query condition. For details, see [Syntax of Media Query Conditions](../../ui/ui-ts-layout-mediaquery.md#syntax-of-media-query-conditions).| **Return value** + | Type | Description | | ------------------ | ---------------------- | -| MediaQueryListener | Listening handle to a media event, which is used to register or deregister the listening callback.| +| MediaQueryListener | Media query listener, which is used to register or deregister the listening callback.| **Example** - ```js + +```js let listener = mediaquery.matchMediaSync('(orientation: landscape)'); // Listen for landscape events. - ``` +``` ## MediaQueryListener -Media query handle, including the first query result when the handle is applied for. +Implements the media query listener, including the first query result when the listener is applied for. **System capability**: SystemCapability.ArkUI.ArkUI.Full ### Attributes -| Name | Type | Readable | Writable | Description | -| ------- | ------- | ---- | ---- | ---------- | -| matches | boolean | Yes | No | Whether the match condition is met. | -| media | string | Yes | No | Matching condition of a media event.| +| Name | Type | Readable| Writable| Description | +| ------- | ------- | ---- | ---- | -------------------- | +| matches | boolean | Yes | No | Whether the media query condition is met. | +| media | string | Yes | No | Media query condition.| ### on on(type: 'change', callback: Callback<MediaQueryResult>): void -Registers a callback with the corresponding query condition by using the handle. This callback is triggered when the media attributes change. +Registers the media query listener. The callback is triggered when the media attributes change. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** + | Name | Type | Mandatory | Description | | -------- | -------------------------------- | ---- | ---------------- | -| type | string | Yes | Must enter the string **change**.| +| type | string | Yes | Listener type. The value is fixed at **'change'**.| | callback | Callback<MediaQueryResult> | Yes | Callback registered with media query. | **Example** + For details, see [off Example](#off). @@ -79,17 +79,19 @@ Registers a callback with the corresponding query condition by using the handle. off(type: 'change', callback?: Callback<MediaQueryResult>): void -Deregisters a callback with the corresponding query condition by using the handle, so that no callback is triggered when the media attributes change. +Deregisters the media query listener, so that no callback is triggered when the media attributes change. **System capability**: SystemCapability.ArkUI.ArkUI.Full **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------------------------------- | ---- | ----------------------------- | -| type | boolean | Yes | Must enter the string **change**. | -| callback | Callback<MediaQueryResult> | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.| + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ---------------------------------------------------------- | +| type | string | Yes | Listener type. The value is fixed at **'change'**. | +| callback | Callback<MediaQueryResult> | No | Callback to be deregistered. If the default value is used, all callbacks of the handle are deregistered.| **Example** + ```js import mediaquery from '@ohos.mediaquery' @@ -101,20 +103,23 @@ Deregisters a callback with the corresponding query condition by using the handl // do something here } } - listener.on('change', onPortrait) // Register a callback. - listener.off('change', onPortrait) // Deregister a callback. + listener.on('change', onPortrait) // Register the media query listener. + listener.off('change', onPortrait) // Deregister the media query listener. ``` - ## MediaQueryResult +Provides the media query result. + +**System capability**: SystemCapability.ArkUI.ArkUI.Full + ### Attributes -| Name | Type | Readable | Writable | Description | -| ------- | ------- | ---- | ---- | ---------- | -| matches | boolean | Yes | No | Whether the match condition is met. | -| media | string | Yes | No | Matching condition of a media event.| +| Name | Type | Readable| Writable| Description | +| ------- | ------- | ---- | ---- | -------------------- | +| matches | boolean | Yes | No | Whether the media query condition is met. | +| media | string | Yes | No | Media query condition.| ### Example diff --git a/en/application-dev/reference/apis/js-apis-mouseevent.md b/en/application-dev/reference/apis/js-apis-mouseevent.md index 86cf6b064028b150ad0ff0313580fa6918903682..92935d6f31e788eb0b71ec6529fbc94264e3d8d1 100644 --- a/en/application-dev/reference/apis/js-apis-mouseevent.md +++ b/en/application-dev/reference/apis/js-apis-mouseevent.md @@ -1,6 +1,6 @@ -# Mouse Event +# @ohos.multimodalInput.mouseEvent (Mouse Event) -Represents mouse events reported by an input device. +The **mouseEvent** module provides mouse events reported by an input device. > **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. @@ -8,82 +8,82 @@ Represents mouse events reported by an input device. ## Modules to Import ```js -import {Action,Button,Axis,AxisValue,MouseEvent} from '@ohos.multimodalInput.mouseEvent'; +import { Action, Button, Axis, AxisValue, MouseEvent } from '@ohos.multimodalInput.mouseEvent'; ``` ## Action **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| CANCEL | number | Yes| No| Cancellation of a mouse action.| -| MOVE | number | Yes| No| Moving of the mouse pointer.| -| BUTTON_DOWN | number | Yes| No| Pressing of a mouse button.| -| BUTTON_UP | number | Yes| No| Release of a mouse button.| -| AXIS_BEGIN | number | Yes| No| Beginning of the axis event associated with the mouse.| -| AXIS_UPDATE | number | Yes| No| Updating of the axis event associated with the mouse.| -| AXIS_END | number | Yes| No| Ending of the axis event associated with the mouse.| +| Name | Value| Description | +| ----------- | -------- | -------------------- | +| CANCEL | 0 | Cancellation of a mouse action. | +| MOVE | 1 | Moving of the mouse pointer. | +| BUTTON_DOWN | 2 | Pressing of a mouse button. | +| BUTTON_UP | 3 | Release of a mouse button. | +| AXIS_BEGIN | 4 | Beginning of the axis event associated with the mouse.| +| AXIS_UPDATE | 5 | Updating of the axis event associated with the mouse.| +| AXIS_END | 6 | Ending of the axis event associated with the mouse.| ## Button **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| LEFT | number | Yes| No| Left button on the mouse.| -| MIDDLE | number | Yes| No| Middle button on the mouse.| -| RIGHT | number | Yes| No| Right button on the mouse.| -| SIDE | number | Yes| No| Side button on the mouse.| -| EXTRA | number | Yes| No| Extended button on the mouse.| -| FORWARD | number | Yes| No| Forward button on the mouse.| -| BACK | number | Yes| No| Back button on the mouse.| -| TASK | number | Yes| No| Task button on the mouse.| +| Name | Value | Description | +| ------- | ------| ----- | +| LEFT | 0 | Left button on the mouse. | +| MIDDLE | 1 | Middle button on the mouse. | +| RIGHT | 2 | Right button on the mouse. | +| SIDE | 3 | Side button on the mouse.| +| EXTRA | 4 | Extended button on the mouse.| +| FORWARD | 5 | Forward button on the mouse.| +| BACK | 6 | Back button on the mouse.| +| TASK | 7 | Task button on the mouse.| ## Axis **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| SCROLL_VERTICAL | number | Yes| No| Vertical scroll axis.| -| SCROLL_HORIZONTAL | number | Yes| No| Horizontal scroll axis.| -| PINCH | number | Yes| No| Pinch axis.| +| Name | Value | Description | +| ----------------- | ------- | ----- | +| SCROLL_VERTICAL | 0 | Vertical scroll axis.| +| SCROLL_HORIZONTAL | 1 | Horizontal scroll axis.| +| PINCH | 2 | Pinch axis. | ## AxisValue **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| axis | Axis | Yes| No| Axis type.| -| value | number | Yes| No| Axis value.| +| Name | Type | Readable | Writable | Description | +| ----- | ------ | ---- | ---- | ---- | +| axis | Axis | Yes | No | Axis type. | +| value | number | Yes | No | Axis value. | ## MouseEvent **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| action | Action | Yes| No| Mouse event action.| -| screenX | number | Yes| No| X coordinate of the mouse pointer on the screen.| -| screenY | number | Yes| No| Y coordinate of the mouse pointer on the screen.| -| windowX | number | Yes| No| X coordinate of the mouse pointer in the window.| -| windowY | number | Yes| No| Y coordinate of the mouse pointer in the window.| -| rawDeltaX | number | Yes| No| X axis offset relative to the previous reported mouse pointer position. When the mouse pointer is at the edge of the screen, the value may be less than the difference of the X coordinate reported twice.| -| rawDeltaY | number | Yes| No| Y axis offset relative to the previous reported mouse pointer position.| -| button | Button | Yes| No| Button that is currently pressed or released.| -| pressedButtons | Button[] | Yes| No| Button that is being pressed.| -| axes | AxisValue[] | Yes| No| All axis data contained in the event.| -| pressedKeys | KeyCode[] | Yes| No| List of pressed keys.| -| ctrlKey | boolean | Yes| No| Whether ctrlKey is being pressed.| -| altKey | boolean | Yes| No| Whether altKey is being pressed.| -| shiftKey | boolean | Yes| No| Whether shiftKey is being pressed.| -| logoKey | boolean | Yes| No| Whether logoKey is being pressed.| -| fnKey | boolean | Yes| No| Whether fnKey is being pressed.| -| capsLock | boolean | Yes| No| Whether capsLock is active.| -| numLock | boolean | Yes| No| Whether numLock is active.| -| scrollLock | boolean | Yes| No| Whether scrollLock is active.| +| Name | Type | Readable | Writable | Description | +| -------------- | ----------- | ---- | ---- | ---------------------------------------- | +| action | Action | Yes | No | Mouse event action. | +| screenX | number | Yes | No | Horizontal coordinate of the mouse pointer on the screen. | +| screenY | number | Yes | No | Vertical coordinate of the mouse pointer on the screen. | +| windowX | number | Yes | No | Horizontal coordinate of the mouse pointer in the window. | +| windowY | number | Yes | No | Vertical coordinate of the mouse pointer in the window. | +| rawDeltaX | number | Yes | No | Horizontal coordinate offset relative to the previous reported mouse pointer position.| +| rawDeltaY | number | Yes | No | Vertical coordinate offset relative to the previous reported mouse pointer position. | +| button | Button | Yes | No | Mouse button +| pressedButtons | Button[] | Yes | No | Button being pressed. | +| axes | AxisValue[] | Yes | No | All axis data contained in the event. | +| pressedKeys | KeyCode[] | Yes | No | List of pressed keys. | +| ctrlKey | boolean | Yes | No | Whether ctrlKey is being pressed. | +| altKey | boolean | Yes | No | Whether altKey is being pressed. | +| shiftKey | boolean | Yes | No | Whether shiftKey is being pressed. | +| logoKey | boolean | Yes | No | Whether logoKey is being pressed. | +| fnKey | boolean | Yes | No | Whether fnKey is being pressed. | +| capsLock | boolean | Yes | No | Whether capsLock is active. | +| numLock | boolean | Yes | No | Whether numLock is active. | +| scrollLock | boolean | Yes | No | Whether scrollLock is active. | 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 31414ab325572d7ed25a31b1b3a78a725dce39e6..d5a5f1585a5ae153694833b611861cc49325c4e7 100644 --- a/en/application-dev/reference/apis/js-apis-net-connection.md +++ b/en/application-dev/reference/apis/js-apis-net-connection.md @@ -1,9 +1,8 @@ -# Network Connection Management +# @ohos.net.connection (Network Connection Management) -The network connection management module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. +The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -61,7 +60,7 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` -## connection.getDefaultNetSync +## connection.getDefaultNetSync9+ getDefaultNetSync(): NetHandle; @@ -303,6 +302,55 @@ connection.getDefaultNet().then(function (netHandle) { }) ``` +## connection.isDefaultNetMetered9+ + +isDefaultNetMetered(callback: AsyncCallback\): void + +Checks whether the data traffic usage on the current network is metered. 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 the result. The value **true** indicates the data traffic usage is metered.| + +**Example**: + +```js +connection.isDefaultNetMetered(function (error, has) { + console.log(JSON.stringify(error)) + console.log('has: ' + has) +}) +``` + +## connection.isDefaultNetMetered9+ + +isDefaultNetMetered(): Promise\ + +Checks whether the data traffic usage on the current network is metered. This API uses a promise to return the result. + +**Required permission**: ohos.permission.GET_NETWORK_INFO + +**System capability**: SystemCapability.Communication.NetManager.Core + +**Return value** + +| Type | Description | +| ----------------- | ----------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** indicates the data traffic usage is metered.| + +**Example**: + +```js +connection.isDefaultNetMetered().then(function (has) { + console.log('has: ' + has) +}) +``` + ## connection.reportNetConnected reportNetConnected(netHandle: NetHandle, callback: AsyncCallback<void>): void @@ -332,7 +380,6 @@ connection.getDefaultNet().then(function (netHandle) { }); ``` - ## connection.reportNetConnected reportNetConnected(netHandle: NetHandle): Promise<void> @@ -490,14 +537,13 @@ connection.getAddressesByName(host).then(function (addresses) { }) ``` - ## connection.enableAirplaneMode enableAirplaneMode(callback: AsyncCallback\): void Enables the airplane mode. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -521,7 +567,7 @@ enableAirplaneMode(): Promise\ Enables the airplane mode. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -539,14 +585,13 @@ connection.enableAirplaneMode().then(function (error) { }) ``` - ## connection.disableAirplaneMode disableAirplaneMode(callback: AsyncCallback\): void Disables the airplane mode. This API uses an asynchronous callback to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -570,7 +615,7 @@ disableAirplaneMode(): Promise\ Disables the airplane mode. This API uses a promise to return the result. -This is a system API. +**System API**: This is a system API. **System capability**: SystemCapability.Communication.NetManager.Core @@ -588,7 +633,6 @@ connection.disableAirplaneMode().then(function (error) { }) ``` - ## connection.createNetConnection createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection @@ -825,9 +869,9 @@ Before invoking NetHandle APIs, call **getNetHandle** to obtain a **NetHandle** | Name| Type | Description | | ------ | ------ | ------------------------- | -| netId | number | Network ID. The value must be greater than or equal to 100.| +| netId | number | Network ID. The value **0** indicates no default network. Any other value must be greater than or equal to 100.| -### bindSocket +### bindSocket9+ bindSocket(socketParam: TCPSocket \| UDPSocket, callback: AsyncCallback\): void; @@ -847,33 +891,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses **Example** ```js -connection.getDefaultNet().then(function (netHandle) { +import socket from "@ohos.net.socket"; +connection.getDefaultNet().then((netHandle)=>{ var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); - let socketType = "xxxx"; + let socketType = "TCPSocket"; if (socketType == "TCPSocket") { tcp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { - netHandle.bindSocket(tcp, function (error, data) { - console.log(JSON.stringify(error)) - console.log(JSON.stringify(data)) + if (err) { + console.log('bind fail'); + } + netHandle.bindSocket(tcp, (error, data)=>{ + if (error) { + console.log(JSON.stringify(error)); + } else { + console.log(JSON.stringify(data)); + } + }) }) } else { + let callback = value => { + console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + } udp.on('message', callback); udp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { + if (err) { + console.log('bind fail'); + } 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)) + console.log(JSON.stringify(data)) }); + netHandle.bindSocket(udp,(error, data)=>{ + if (error) { + console.log(JSON.stringify(error)); + } else { + console.log(JSON.stringify(data)); + } + }) }) - } -} + } +}) ``` ### bindSocket @@ -901,31 +962,50 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses **Example** ```js -connection.getDefaultNet().then(function (netHandle) { +import socket from "@ohos.net.socket"; +connection.getDefaultNet().then((netHandle)=>{ var tcp = socket.constructTCPSocketInstance(); var udp = socket.constructUDPSocketInstance(); - let socketType = "xxxx"; - if(socketType == "TCPSocket") { + let socketType = "TCPSocket"; + if (socketType == "TCPSocket") { tcp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { - netHandle.bindSocket(tcp).then(err, data) { - console.log(JSON.stringify(data)) + if (err) { + console.log('bind fail'); + } + netHandle.bindSocket(tcp).then((err, data) => { + if (err) { + console.log(JSON.stringify(err)); + } else { + console.log(JSON.stringify(data)); + } + }) }) } else { + let callback = value => { + console.log(TAG + "on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); + } udp.on('message', callback); udp.bind({ - address: "xxxx", port: xxxx, family: xxxx + address: '192.168.xx.xxx', port: xxxx, family: 1 }, err => { + if (err) { + console.log('bind fail'); + } udp.on('message', (data) => { - console.log(JSON.stringify(data)) - }); - netHandle.bindSocket(tcp).then(err, data) { - console.log(JSON.stringify(data)) - }); + console.log(JSON.stringify(data)); + }) + netHandle.bindSocket(udp).then((err, data) => { + if (err) { + console.log(JSON.stringify(err)); + } else { + console.log(JSON.stringify(data)); + } + }) }) - } -} + } +}) ``` @@ -1059,10 +1139,10 @@ Provides an instance that bears data network capabilities. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ----------------------- | ----------------------------------- | ------------------------------------------------------------ | -| netCapabilities | [NetCapabilities](#netcapabilities) | Network transmission capabilities and bearer types of the data network. | -| bearerPrivateIdentifier | string | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| netCapabilities | [NetCapabilities](#netcapabilities) | Yes | Network transmission capabilities and bearer types of the data network. | +| bearerPrivateIdentifier | string | No | Network identifier. The identifier of a Wi-Fi network is **wifi**, and that of a cellular network is **slot0** (corresponding to SIM card 1).| ## NetCapabilities @@ -1070,12 +1150,12 @@ Defines the network capability set. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| --------------------- | ---------------------------------- | ------------------------ | -| linkUpBandwidthKbps | number | Uplink (from the device to the network) bandwidth.| -| linkDownBandwidthKbps | number | Downlink (from the network to the device) bandwidth.| -| networkCap | Array<[NetCap](#netcap)> | Network capability. | -| bearerTypes | Array<[NetBearType](#netbeartype)> | Network type. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| linkUpBandwidthKbps | number | No | Uplink (from the device to the network) bandwidth.| +| linkDownBandwidthKbps | number | No | Downlink (from the network to the device) bandwidth.| +| networkCap | Array<[NetCap](#netcap)> | No | Network capability. | +| bearerTypes | Array<[NetBearType](#netbeartype)> | Yes | Network type. | ## NetCap @@ -1109,14 +1189,14 @@ Defines the network connection properties. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ------------- | ---------------------------------- | ---------------- | -| interfaceName | string | NIC card name. | -| domains | string | Domain. The default value is **""**.| -| linkAddresses | Array<[LinkAddress](#linkaddress)> | Link information. | -| routes | Array<[RouteInfo](#routeinfo)> | Route information. | -| dnses | Array<[NetAddress](#netaddress)> | Network address. For details, see [NetAddress](#netaddress).| -| mtu | number | Maximum transmission unit (MTU). | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| interfaceName | string | Yes | NIC card name. | +| domains | string | Yes | Domain. The default value is **""**.| +| linkAddresses | Array\<[LinkAddress](#linkaddress)> | Yes | Link information. | +| routes | Array\<[RouteInfo](#routeinfo)> | Yes | Route information. | +| dnses | Array\<[NetAddress](#netaddress)>; | Yes | Network address. For details, see [NetAddress](#netaddress).| +| mtu | number | Yes | Maximum transmission unit (MTU). | ## LinkAddress @@ -1124,10 +1204,10 @@ Network link information. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| ------------ | ------------------------- | -------------------- | -| address | [NetAddress](#netaddress) | Link address. | -| prefixLength | number | Length of the link address prefix.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| address | [NetAddress](#netaddress) | Yes | Link address. | +| prefixLength | number | Yes | Length of the link address prefix.| ## RouteInfo @@ -1135,13 +1215,13 @@ Network route information. **System capability**: SystemCapability.Communication.NetManager.Core -| Name | Type | Description | -| -------------- | --------------------------- | ---------------- | -| interface | string | NIC card name. | -| destination | [LinkAddress](#linkaddress) | Destination IP address. | -| gateway | [NetAddress](#netaddress) | Gateway address. | -| hasGateway | boolean | Whether a gateway is present. | -| isDefaultRoute | boolean | Whether the route is the default route.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| interface | string | Yes | NIC card name. | +| destination | [LinkAddress](#linkaddress) | Yes | Destination IP address. | +| gateway | [NetAddress](#netaddress) | Yes | Gateway address. | +| hasGateway | boolean | Yes | Whether a gateway is present. | +| isDefaultRoute | boolean | Yes | Whether the route is the default route.| ## NetAddress @@ -1149,8 +1229,8 @@ Defines the network address. **System capability**: SystemCapability.Communication.NetManager.Core -| 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**. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| address | string | Yes | Network address. | +| family | number | Yes | Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.| +| port | number | No | Port number. The value ranges from **0** to **65535**. | diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md index bf132f3c63710fc83b04a3411eb2477f2fe8b855..d41845ec1859507bb96a071dff2a57e16f4cf12b 100644 --- a/en/application-dev/reference/apis/js-apis-net-ethernet.md +++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md @@ -1,9 +1,8 @@ -# Ethernet Connection Management +# @ohos.net.ethernet (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. +The **ethernet** 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** -> +> **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 @@ -14,7 +13,7 @@ import ethernet from '@ohos.net.ethernet' ## ethernet.setIfaceConfig -setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void; +setIfaceConfig(iface: string, ic: InterfaceConfiguration, callback: AsyncCallback\): void Sets the network interface configuration. This API uses an asynchronous callback to return the result. @@ -46,7 +45,7 @@ ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", ro ## ethernet.setIfaceConfig -setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\; +setIfaceConfig(iface: string, ic: InterfaceConfiguration): Promise\ Sets the network interface configuration. This API uses a promise to return the result. @@ -80,7 +79,7 @@ ethernet.setIfaceConfig("eth0", {mode:ethernet.STATIC,ipAddr:"192.168.1.123", ro ## ethernet.getIfaceConfig -getIfaceConfig(iface: string, callback: AsyncCallback\): void; +getIfaceConfig(iface: string, callback: AsyncCallback\): void Obtains the configuration of a network interface. This API uses an asynchronous callback to return the result. @@ -115,7 +114,7 @@ ethernet.getIfaceConfig("eth0", (error, value) => { ## ethernet.getIfaceConfig -getIfaceConfig(iface: string): Promise\; +getIfaceConfig(iface: string): Promise\ Obtains the configuration of a network interface. This API uses a promise to return the result. @@ -153,7 +152,7 @@ ethernet.getIfaceConfig("eth0").then((data) => { ## ethernet.isIfaceActive -isIfaceActive(iface?: string, callback: AsyncCallback\): void; +isIfaceActive(iface?: string, callback: AsyncCallback\): void Checks whether a network interface is active. This API uses an asynchronous callback to return the result. @@ -165,7 +164,7 @@ Checks whether a network interface is active. This API uses an asynchronous call | 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. | +| iface | string | Yes | 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** @@ -182,7 +181,7 @@ ethernet.isIfaceActive("eth0", (error, value) => { ## ethernet.isIfaceActive -isIfaceActive(iface?: string): Promise\; +isIfaceActive(iface: string): Promise\ Checks whether a network interface is active. This API uses a promise to return the result. @@ -194,7 +193,7 @@ Checks whether a network interface is active. This API uses a promise to return | 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.| +| iface | string | Yes | Name of the network interface. If this parameter is left empty, the API checks for any active network interface.| **Return value** @@ -214,7 +213,7 @@ ethernet.isIfaceActive("eth0").then((data) => { ## ethernet.getAllActiveIfaces -getAllActiveIfaces(callback: AsyncCallback\>): void; +getAllActiveIfaces(callback: AsyncCallback\>): void Obtains all active network interfaces. This API uses an asynchronous callback to return the result. @@ -245,7 +244,7 @@ ethernet.getAllActiveIfaces((error, value) => { ## ethernet.getAllActiveIfaces -getAllActiveIfaces(): Promise\>; +getAllActiveIfaces(): Promise\> Obtains all active network interfaces. This API uses a promise to return the result. @@ -280,14 +279,14 @@ 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 (,).| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| mode | [IPSetMode](#ipsetmode) | Yes | Configuration mode of the Ethernet connection.| +| ipAddr | string | Yes | 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 | Yes | 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 | Yes | 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 | Yes | 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 | Yes | 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 diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md index 23284aeb1715a3f8aed9ec7b2d79ad55d1408319..144ffa9c6e2d405c83e7cf14fdb7278c616759d3 100644 --- a/en/application-dev/reference/apis/js-apis-net-sharing.md +++ b/en/application-dev/reference/apis/js-apis-net-sharing.md @@ -1,9 +1,8 @@ -# Network Sharing Management +# @ohos.net.sharing (Network Sharing) -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. +The **sharing** 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** -> +> **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 @@ -18,9 +17,11 @@ isSharingSupported(callback: AsyncCallback\): void Checks whether network sharing is supported. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -43,9 +44,11 @@ isSharingSupported(): Promise\ Checks whether network sharing is supported. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -69,9 +72,11 @@ isSharing(callback: AsyncCallback\): void Checks whether network sharing is in progress. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -96,7 +101,9 @@ Checks whether network sharing is in progress. This API uses a promise to return **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -122,7 +129,9 @@ Starts network sharing of a specified type. This API uses an asynchronous callba **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -146,9 +155,11 @@ startSharing(type: SharingIfaceType): Promise\ Starts network sharing of a specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -179,9 +190,11 @@ stopSharing(type: SharingIfaceType, callback: AsyncCallback\): void Stops network sharing of a specified type. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -205,9 +218,11 @@ stopSharing(type: SharingIfaceType): Promise\ Stops network sharing of a specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -238,9 +253,11 @@ 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. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -263,9 +280,11 @@ getStatsRxBytes(): Promise\ Obtains the volume of mobile data traffic received via network sharing. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -289,9 +308,11 @@ 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. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -314,9 +335,11 @@ getStatsTxBytes(): Promise\ Obtains the volume of mobile data traffic sent via network sharing. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -340,9 +363,11 @@ 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. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -365,9 +390,11 @@ getStatsTotalBytes(): Promise\ Obtains the volume of mobile data traffic sent and received via network sharing. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Return value** @@ -391,21 +418,23 @@ getSharingIfaces(state: SharingIfaceState, callback: AsyncCallback\> | Yes | Callback used to return an array of NIC names.| **Example** ```js -import SharingIfaceState from '@ohos.net.sharing' +import SharingIfaceType from '@ohos.net.sharing' sharing.getSharingIfaces(SharingIfaceState.SHARING_NIC_CAN_SERVER, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); @@ -418,15 +447,17 @@ getSharingIfaces(state: SharingIfaceState): Promise\> Obtains the names of NICs in the specified network sharing state. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| state | state: [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| +| state | [SharingIfaceState](#sharingifacestate) | Yes | Network sharing state.| **Return value** @@ -451,9 +482,11 @@ getSharingState(type: SharingIfaceType, callback: AsyncCallback\ Obtains the network sharing state of the specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -498,7 +533,7 @@ Obtains the network sharing state of the specified type. This API uses a promise ```js import SharingIfaceType from '@ohos.net.sharing' -sharing.getSharingIfaces(SharingIfaceType.SHARING_WIFI).then(data => { +sharing.getSharingState(SharingIfaceType.SHARING_WIFI).then(data => { console.log(JSON.stringify(data)); }).catch(error => { console.log(JSON.stringify(error)); @@ -511,9 +546,11 @@ getSharableRegexes(type: SharingIfaceType, callback: AsyncCallback\ { +import SharingIfaceType from '@ohos.net.sharing' +sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI, (error, data) => { console.log(JSON.stringify(error)); console.log(JSON.stringify(data)); }); @@ -538,9 +575,11 @@ getSharableRegexes(type: SharingIfaceType): Promise\> Obtains regular expressions of NICs of a specified type. This API uses a promise to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -565,15 +604,17 @@ sharing.getSharableRegexes(SharingIfaceType.SHARING_WIFI).then(data => { }); ``` -## on('sharingStateChange') +## sharing.on('sharingStateChange') on(type: 'sharingStateChange', callback: Callback\): void Subscribes to network sharing state changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -591,15 +632,17 @@ sharing.on('sharingStateChange', (error, data) => { }); ``` -## off('sharingStateChange') +## sharing.off('sharingStateChange') off(type: 'sharingStateChange', callback?: Callback\): void Unsubscribes from network sharing state changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -617,15 +660,17 @@ sharing.off('sharingStateChange', (error, data) => { }); ``` -## on('interfaceSharingStateChange') +## sharing.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. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -643,21 +688,23 @@ sharing.on('interfaceSharingStateChange', (error, data) => { }); ``` -## off('interfaceSharingStateChange') +## sharing.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. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------------------------- | ---- | ---------- | -| type | string | No | Event name.| +| type | string | Yes | Event name.| | callback | AsyncCallback\<{ type: [SharingIfaceType](#sharingifacetype), iface: string, state: SharingIfaceState(#sharingifacestate) }> | No | Callback used for unsubscription.| **Example** @@ -669,15 +716,17 @@ sharing.off('interfaceSharingStateChange', (error, data) => { }); ``` -## on('sharingUpstreamChange') +## sharing.on('sharingUpstreamChange') on(type: 'sharingUpstreamChange', callback: Callback\): void Subscribes to upstream network changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -695,15 +744,17 @@ sharing.on('sharingUpstreamChange', (error, data) => { }); ``` -## off('sharingUpstreamChange') +## sharing.off('sharingUpstreamChange') off(type: 'sharingUpstreamChange', callback?: Callback\): void Unsubscribes from upstream network changes. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **Required permissions**: ohos.permission.CONNECTIVITY_INTERNAL -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing **Parameters** @@ -725,7 +776,9 @@ sharing.off('sharingUpstreamChange', (error, data) => { Enumerates the network sharing states of an NIC. -**System capability**: SystemCapability.Communication.NetManager.Core +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.NetManager.NetSharing | Name | Value | Description | | ------------------------ | ---- | ---------------------- | @@ -735,12 +788,14 @@ Enumerates the network sharing states of an NIC. ## SharingIfaceType -Enumerates the network sharing types of an NIC. +Enumerates the network sharing types of an NIC. + +**System API**: This is a system API. -**System capability**: SystemCapability.Communication.NetManager.Core +**System capability**: SystemCapability.Communication.NetManager.NetSharing | Name | Value | Description | | ------------------------ | ---- | ---------------------- | | SHARING_WIFI | 0 | Wi-Fi hotspot sharing.| -| SHARING_USB | 1 | USB sharing.| +| SHARING_USB | 1 | USB sharing (not supported currently).| | SHARING_BLUETOOTH | 2 | Bluetooth sharing.| diff --git a/en/application-dev/reference/apis/js-apis-nfcTag.md b/en/application-dev/reference/apis/js-apis-nfcTag.md index 2f3a208fe1f95b2c4f936709d047fa4c9581f8b6..704b9084ff4f3ebecf2720f6c40ebeb98f5dc775 100644 --- a/en/application-dev/reference/apis/js-apis-nfcTag.md +++ b/en/application-dev/reference/apis/js-apis-nfcTag.md @@ -1,8 +1,9 @@ -# NFC Tags +# @ohos.nfc.tag The **nfcTag** module provides APIs for managing Near-Field Communication (NFC) tags. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## **Declaration** @@ -47,12 +48,10 @@ Before developing applications related to tag read and write, you must declare N } ``` > **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. - +1. The **actions** field is mandatory. It must be **ohos.nfc.tag.action.TAG_FOUND** and cannot be changed. +2. The **name** field under **metadata** is mandatory. It must be **tag-tech** and cannot be changed. +3. The **value** field under **metadata** is mandatory. It can be **NfcA**, **NfcB**, **NfcF**, **NfcV**, **IsoDep**, **Ndef**, **MifareClassic**, **MifareUL**, **NdefFormatable** or any of their combinations. Incorrect settings of this field will cause a parsing failure. +4. The **name** field under **requestPermissions** is mandatory. It must be **ohos.permission.NFC_TAG** and cannot be changed. ## **Modules to Import** @@ -61,34 +60,63 @@ 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. + +Before a card with tags is read or written, **TagInfo** must be obtained to determine the tag technologies supported by the card. In this way, 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) { + // want is initialized by the NFC service and contains tagInfo. + var tagInfo; + try { + tagInfo = tag.getTagInfo(want); + } catch (error) { + console.log("tag.getTagInfo catched error: " + error); + } + if (tagInfo == null || tagInfo == undefined) { console.log("no TagInfo to be created, ignore it."); return; } + + // get the supported technologies for this found tag. var isNfcATag = false; + var isIsoDepTag = false; for (var i = 0; i < tagInfo.technology.length; i++) { if (tagInfo.technology[i] == tag.NFC_A) { isNfcATag = true; - break; + } + + if (tagInfo.technology[i] == tag.ISO_DEP) { + isIsoDepTag = true; } // Also check for technology tag.NFC_B, NFC_F, NFC_V, ISO_DEP, NDEF, MIFARE_CLASSIC, MIFARE_ULTRALIGHT, and NDEF_FORMATABLE. } + + // use NfcA APIs to access the found tag. if (isNfcATag) { - var nfcA = tag.getNfcATag(taginfo); + var nfcA; + try { + nfcA = tag.getNfcATag(taginfo); + } catch (error) { + console.log("tag.getNfcATag catched error: " + error); + } + // Other code to read or write this tag. + } + + // use getIsoDep APIs to access the found tag. + if (isIsoDepTag) { + var isoDep; + try { + isoDep = tag.getIsoDep(taginfo); + } catch (error) { + console.log("tag.getIsoDep catched error: " + error); + } // 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); + // Use the same code to handle "NfcA/NfcB/NfcF/NfcV/Ndef/MifareClassic/MifareUL/NdefFormatable". } ``` @@ -156,78 +184,122 @@ Obtains an **NfcVTag** object, which allows access to the tags that use the NFC- | -------- | ---------------- | | [NfcVTag](js-apis-nfctech.md#nfcvtag) | **NfcVTag** object obtained.| -## tag.getIsoDepTag9+ +## tag.getIsoDep9+ -getIsoDepTag(tagInfo: [TagInfo](#taginfo)): [IsoDepTag](js-apis-nfctech.md#isoDepTag9 ) +getIsoDep(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 +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes| Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ---------- | ------------------| | [IsoDepTag](js-apis-nfctech.md#isodeptag9) | **IsoDepTag** object obtained.| -## tag.getNdefTag9+ +**Error codes** -getNdefTag(tagInfo: [TagInfo](#taginfo)): [NdefTag](js-apis-nfctech.md#ndeftag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefTag** object, which allows access to the tags in the NFC Data Exchange Format (NDEF). +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | +## tag.getNdef9+ -**Required permissions**: ohos.permission.NFC_TAG +getNdef(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). **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ---------| -------------- | | [NdefTag](js-apis-nfctech.md#ndeftag9) | **NdefTag** object obtained.| -## tag.getMifareClassicTag9+ +**Error codes** -getMifareClassicTag(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareClassic9+ + +getMifareClassic(tagInfo: [TagInfo](#taginfo)): [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) + +Obtains a **MifareClassicTag** object, which allows access to the tags that use MIFARE Classic. **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | ----------------- | ------------------------| -| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag-9) | **MifareClassicTag** object obtained.| +| [MifareClassicTag](js-apis-nfctech.md#mifareclassictag9) | **MifareClassicTag** object obtained.| -## tag.getMifareUltralightTag9+ +**Error codes** -getMifareUltralightTag(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getMifareUltralight9+ + +getMifareUltralight(tagInfo: [TagInfo](#taginfo)): [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) + +Obtains a **MifareUltralightTag** object, which allows access to the tags that use MIFARE Ultralight. **System capability**: SystemCapability.Communication.NFC.Core +**Parameters** +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| taginfo | [TagInfo](#taginfo) | Yes | Tag information including the technology type and related parameters, which are obtained from **tag.getTagInfo(want: Want)**. | + **Return value** | **Type**| **Description** | | -------------------- | ---------------------------| | [MifareUltralightTag](js-apis-nfctech.md#mifareultralighttag9) | **MifareUltralightTag** object obtained.| -## tag.getNdefFormatableTag9+ +**Error codes** -getNdefFormatableTag(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | -**Required permissions**: ohos.permission.NFC_TAG +## tag.getNdefFormatable9+ + +getNdefFormatable(tagInfo: [TagInfo](#taginfo)): [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag9) + +Obtains an **NdefFormatableTag** object, which allows access to the tags that are NDEF formattable. **System capability**: SystemCapability.Communication.NFC.Core @@ -237,89 +309,376 @@ Obtains an **NdefFormatableTag** object, which allows access to the tags that ar | ------------------ | --------------------------| | [NdefFormatableTag](js-apis-nfctech.md#ndefformatabletag) | **NdefFormatableTag** object obtained.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + ## tag.getTagInfo9+ -getTagInfo(want: Want): [TagInfo](#taginfo) +getTagInfo(want: [Want](js-apis-app-ability-want.md#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 +**Parameters** + +| Name | Type | Mandatory | Description | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| want | [Want](js-apis-app-ability-want.md#Want) | Yes | Data obtained from the parameters of the **onCreate** entry function when an ability is dispatched. | + **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. +## tag.ndef.makeUriRecord9+ -**Required permissions**: ohos.permission.NFC_TAG +makeUriRecord(uri: string): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified URI. **System capability**: SystemCapability.Communication.NFC.Core -| **Name**| **Type**| **Description**| -| -------- | -------- | -------- | -| 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**.| +**Parameters** -## NdefRecord9+ -Defines an NDEF tag record. For details, see *NFCForum-TS-NDEF_1.0*. +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| uri | string | Yes| Data to write to the NDEF record.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let uri = "https://gitee.com/openharmony"; // change it to be correct. + let ndefRecord = tag.ndef.makeUriRecord(uri); + if (ndefRecord != undefined) { + console.log("ndefMessage makeUriRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeUriRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeUriRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeUriRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.makeTextRecord9+ + +makeTextRecord(text: string, locale: string): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified text data and encoding type. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| text | string | Yes | Text to write to the NDEF record.| +| locale | string | Yes | Encoding mode of the text.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let text = "Hello World"; // change it to be correct. + let locale = "en"; // change it to be correct. + let ndefRecord = tag.ndef.makeTextRecord(text, locale); + if (ndefRecord != undefined) { + console.log("ndefMessage makeTextRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeTextRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeTextRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeTextRecord catched busiError: " + busiError); +} +``` + + +## tag.ndef.makeMimeRecord9+ + +makeMimeRecord(mimeType: string, mimeData: number[]): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on the specified MIME data and type. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| mimeType | string | Yes | MIME type that complies with RFC rules, for example, **text/plain** or **image/jpeg**.| +| mimeData | number[] | Yes | MIME data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let mimeType = "text/plain"; // change it to be correct. + let mimeData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeMimeRecord(mimeType, mimeData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeMimeRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeMimeRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeMimeRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeMimeRecord catched busiError: " + busiError); +} +``` +## tag.ndef.makeExternalRecord9+ + +makeExternalRecord(domainName: string, type: string, externalData: number[]): [NdefRecord](#ndefrecord9); + +Creates an NDEF record based on application-specific data. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| domainName | string | Yes | Bundle name of the application or domain name of the organization that releases the applications.| +| type | string | Yes | Type of the application data.| +| externalData | number[] | Yes | Application data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefRecord](#ndefrecord9) | NDEF record created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +try { + let domainName = "ohos.nfc.application"; // change it to be correct. + let type = "test"; // change it to be correct. + let externalData = [0x01, 0x02, 0x03, 0x04]; // change it to be correct. + let ndefRecord = tag.ndef.makeExternalRecord(domainName, type, externalData); + if (ndefRecord != undefined) { + console.log("ndefMessage makeExternalRecord rtdType: " + ndefRecord.rtdType); + console.log("ndefMessage makeExternalRecord payload: " + ndefRecord.payload); + } else { + console.log("ndefMessage makeExternalRecord ndefRecord: " + ndefRecord); + } +} catch (busiError) { + console.log("ndefMessage makeExternalRecord catched busiError: " + busiError); +} +``` + +## tag.ndef.messageToBytes9+ + +messageToBytes(ndefMessage: [NdefMessage](js-apis-nfctech.md#ndefmessage9)): number[]; + +Converts an NDEF message to bytes. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| ndefMessage | [NdefMessage](js-apis-nfctech.md#ndefmessage9) | Yes | NDEF message to convert.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number[] | NDEF message in bytes, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} + +try { + let rawData2 = tag.ndef.messageToBytes(ndefMessage); + console.log("ndefMessage messageToBytes rawData2: " + rawData2); +} catch (busiError) { + console.log("ndefMessage messageToBytes catched busiError: " + busiError); +} +``` +## tag.ndef.createNdefMessage9+ + +createNdefMessage(data: number[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +Creates an NDEF message from raw byte data. The data must comply with the NDEF record format. Otherwise, the NDE record list contained in the **NdefMessage** object will be empty. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| data | number[] | Yes| Raw byte data, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**. The data must comply with the NDEF record format.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +let rawData = [0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]; // MUST can be parsed as NDEF Record. +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(rawData); + console.log("ndef createNdefMessage, ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## tag.ndef.createNdefMessage9+ + +createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](js-apis-nfctech.md#ndefmessage9) + +Creates an NDEF message from the NDEF records list. + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| ndefRecords | [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] | Yes| NDEF record list used to create the NDEF message. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| [NdefMessage](js-apis-nfctech.md#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +let uriRecord = tag.ndef.makeUriRecord("https://gitee.com/openharmony"); +let textRecord = tag.ndef.makeTextRecord("Hello World", "en"); +let ndefRecords = [uriRecord, textRecord]; +let ndefMessage; +try { + ndefMessage = tag.ndef.createNdefMessage(ndefRecords); + console.log("ndef createNdefMessage ndefMessage: " + ndefMessage); +} catch (busiError) { + console.log("ndef createNdefMessage busiError: " + busiError); +} +``` + +## TagInfo + +Defines the **TagInfo** object, which provides information about the tag technologies supported by a card. + +**System capability**: SystemCapability.Communication.NFC.Core **Required permissions**: ohos.permission.NFC_TAG +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| uid9+ | number[] | Yes| No| Tag unique identifier (UID), which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| technology9+ | number[] | Yes| No| Supported technologies. Each number is a constant indicating the supported technology.| +| supportedProfiles | number[] | Yes| No| Supported profiles. This parameter is not supported since API version 9. Use [tag.TagInfo#technology](#taginfo) instead.| +| extrasData9+ | [PacMap](js-apis-inner-ability-dataAbilityHelper.md#pacmap)[] | Yes| No| Extended attribute value of the tag technology.
**System API**: This is a system API.| +| tagRfDiscId9+ | number | Yes| No| ID allocated when the tag is discovered.
**System API**: This is a system API.| +| remoteTagService9+ | [rpc.RemoteObject](js-apis-rpc.md#remoteobject) | Yes| No| Remote object of the NFC service process used for interface communication between the client and the service.
**System API**: This is a system API.| +## NdefRecord9+ +Defines an NDEF record. For details, see *NFCForum-TS-NDEF_1.0*. + **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**.| + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| tnf | number | Yes| No| Type name field (TNF) of the NDEF record.| +| rtdType| number[] | Yes| No| Record type definition (RTD) of the NDEF record. It consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| id | number[] | Yes| No| NDEF record ID, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| payload | number[] | Yes| No| NDEF payload, which consists of hexadecimal numbers 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).| +| NFC_B | 2 | NFC-B (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.| +| NDEF_FORMATABLE9+ | 7 | NDEF formattable.| | 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).| +| TNF_WELL_KNOWN | 0x1 | NFC Forum Well Known Type [NFC RTD].| +| TNF_MEDIA | 0x2 | Media-type as defined in RFC 2046 [RFC 2046].| +| TNF_ABSOLUTE_URI | 0x3 | Absolute URI as defined in RFC 3986 [RFC 3986].| +| TNF_EXT_APP | 0x4 | NFC Forum external type [NFC RTD].| +| TNF_UNKNOWN | 0x5 | Unknown.| +| TNF_UNCHANGED | 0x6 | Unchanged (see section 2.3.3 in *NFCForum-TS-NDEF_1.0*).| ## 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.| @@ -328,36 +687,33 @@ Enumerates the NDEF record types. For details about the RTD, see *NFCForum-TS-ND ## 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.| +| MIFARE_CLASSIC | 101 | MIFARE Classic.| ## 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.| +| TYPE_UNKNOWN | 0 | Unknown type.| +| TYPE_CLASSIC | 1 | MIFARE Classic.| +| TYPE_PLUS | 2 | MIFARE Plus.| +| TYPE_PRO | 3 | MIFARE Pro.| ## MifareClassicSize9+ -Enumerates the storage sizes of MIFARE Classic tags. - -**Required permissions**: ohos.permission.NFC_TAG +Enumerates the sizes of MIFARE Classic tags. **System capability**: SystemCapability.Communication.NFC.Core + | **Name**| **Value**| **Description**| | -------- | -------- | -------- | | MC_SIZE_MINI | 320 | Each tag has 5 sectors, and each sector has 4 blocks.| @@ -365,15 +721,14 @@ Enumerates the storage sizes of MIFARE Classic tags. | 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+ +## 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_UNKNOWN | 0 | 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 9817e5fd5c1f2a7f797f2c20fa7b6eff18dc25a5..e28864fc7bd2002838b7ae982bcb7b5269e2c086 100644 --- a/en/application-dev/reference/apis/js-apis-nfctech.md +++ b/en/application-dev/reference/apis/js-apis-nfctech.md @@ -1,11 +1,12 @@ -# NFC Tag Technologies +# nfctech The **nfctech** module provides APIs for reading and writing tags that use different Near-Field Communication (NFC) technologies. > **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -## **Modules to Import** +## Modules to Import ```js import tag from '@ohos.nfc.tag'; @@ -13,11 +14,11 @@ import tag from '@ohos.nfc.tag'; ## NfcATag -Provides access to NFC-A (ISO 14443-3A) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-A (ISO 14443-3A) properties and perform I/O operations on a tag. This class inherits from **[TagSession](js-apis-tagSession.md)**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcATag**. +The following describes the unique APIs of **NfcATag**. ### NfcATag.getSak @@ -40,8 +41,7 @@ Obtains the SAK value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. - +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let sak = nfcA.getSak(); console.log("nfcA sak: " + sak); ``` @@ -67,18 +67,18 @@ Obtains the ATQA value of this NFC-A tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcA' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcA' correctly. let atqa = nfcA.getAtqa(); console.log("nfcA atqa: " + atqa); ``` ## NfcBTag -Provides access to NFC-B (ISO 14443-3B) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-B (ISO 14443-3B) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcBTag**. +The following describes the unique APIs of **NfcBTag**. ### NfcBTag.getRespAppData @@ -94,14 +94,14 @@ Obtains the application data of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Application data obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Application data obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respAppData = nfcB.getRespAppData(); console.log("nfcB respAppData: " + respAppData); ``` @@ -120,25 +120,25 @@ Obtains the protocol information of this NFC-B tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Protocol information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Protocol information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcB' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcB' correctly. let respProtocol = nfcB.getRespProtocol(); console.log("nfcB respProtocol: " + respProtocol); ``` ## NfcFTag -Provides access to NFC-F (JIS 6319-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-F (JIS 6319-4) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcFTag**. +The following describes the unique APIs of **NfcFTag**. ### NfcFTag.getSystemCode @@ -154,14 +154,14 @@ Obtains the system code from this NFC-F tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | System code obtained. Each number in the system code is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | System code obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let systemCode = nfcF.getSystemCode(); console.log("nfcF systemCode: " + systemCode); ``` @@ -174,31 +174,31 @@ Obtains the PMm (consisting of the IC code and manufacturer parameters) informat **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | PMm information obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | PMm information obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcF' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcF' correctly. let pmm = nfcF.getPmm(); console.log("nfcF pmm: " + pmm); ``` ## NfcVTag -Provides access to NFC-V (ISO 15693) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access NFC-V (ISO 15693) properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NfcVTag**. +The following describes the unique APIs of **NfcVTag**. ### NfcvTag.getResponseFlags @@ -208,20 +208,20 @@ Obtains the response flags from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | Response flags obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | Response flags obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let responseFlags = nfcV.getResponseFlags(); console.log("nfcV responseFlags: " + responseFlags); ``` @@ -234,54 +234,52 @@ Obtains the data storage format identifier (DSFID) from this NFC-V tag. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number | DSFID obtained. The value is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number | DSFID obtained, which consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'nfcV' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'nfcV' correctly. let dsfId = nfcV.getDsfId(); console.log("nfcV dsfId: " + dsfId); ``` ## IsoDepTag9+ -Provides access to ISO-DEP (ISO 14443-4) properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access ISO-DEP (ISO 14443-4) properties and I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **IsoDepTag**. +The following describes the unique APIs of **IsoDepTag**. ### IsoDepTag.getHistoricalBytes9+ getHistoricalBytes(): number[] -Obtains the historical bytes of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the historical bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-A technology. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | Historical bytes obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Historical bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-B technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let historicalBytes = isoDep.getHistoricalBytes(); console.log("isoDep historicalBytes: " + historicalBytes); ``` @@ -290,24 +288,22 @@ console.log("isoDep historicalBytes: " + historicalBytes); getHiLayerResponse(): number[] -Obtains the HiLayer response of this tag. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the higher-layer response bytes for the given tag. This API applies only to the IsoDep cards that use the NFC-B technology. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| number[] | HiLayer response obtained. Each number in the return result is a hexadecimal number ranging from **0x00** to **0xFF**.| +| number[] | Higher-layer response bytes obtained, which consist of hexadecimal numbers ranging from **0x00** to **0xFF**. If the IsoDep tag uses the NFC-A technology, **null** will be returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. let hiLayerResponse = isoDep.getHiLayerResponse(); console.log("isoDep hiLayerResponse: " + hiLayerResponse); ``` @@ -320,7 +316,7 @@ Checks whether an extended application protocol data unit (APDU) is supported. T **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -328,18 +324,39 @@ Checks whether an extended application protocol data unit (APDU) is supported. T | ------------------ | --------------------------| | Promise<boolean> | Promise used to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'isoDep' correctly. -isoDep.isExtendedApduSupported() - .then((data) => { - console.log("isoDep isExtendedApduSupported data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported().then((response) => { + console.log("isoDep isExtendedApduSupported Promise response: " + response); }).catch((err)=> { - console.log("isoDep isExtendedApduSupported err: " + err); + console.log("isoDep isExtendedApduSupported Promise err: " + err); }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported Promise busiError: " + busiError); +} + ``` ### IsoDepTag.isExtendedApduSupported9+ @@ -350,7 +367,7 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -358,251 +375,159 @@ Checks whether an extended APDU is supported. This API uses an asynchronous call | -------- | ----------------------- | ---- | -------------------------------------- | | callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the extended APDU is supported, **true** is returned; otherwise, **false** is returned.| -```js -import tag from '@ohos.nfc.tag'; - -// 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+ - -Provides access to the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. - -**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - -The following describes the unique interfaces of **NdefTag**. - -### NdefTag.createNdefMessage9+ - -createNdefMessage(data: number[]): [NdefMessage](#ndefmessage9) +**Error codes** -Creates an NDEF message using raw bytes. +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** - -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| 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. For details, see *NFCForum-TS-NDEF_1.0*.| +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'isoDep' correctly. + +// Connect to the tag if it is not connected. +if (!isoDep.isTagConnected()) { + if (!isoDep.connectTag()) { + console.log("isoDep connectTag failed."); + return; + } +} + +try { + isoDep.isExtendedApduSupported((err, response)=> { + if (err) { + console.log("isoDep isExtendedApduSupported AsyncCallback err: " + err); + } else { + console.log("isoDep isExtendedApduSupported AsyncCallback response: " + response); + } + }); +} catch (busiError) { + console.log("isoDep isExtendedApduSupported AsyncCallback busiError: " + busiError); +} ``` ## NdefMessage9+ ### NdefMessage.getNdefRecords9+ -getNdefRecords(): [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] +getNdefRecords(): [tag.NdefRecord](js-apis-nfcTag.md#ndefrecord9)[] Obtains all NDEF records. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefRecord](js-apis-nfcTag.md#ndefrecord9)[ ] | List of NDEF records obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [tag.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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefRecords = ndef.getNdefRecords(); +// Obtain ndefMessage from tag.ndef.createNdefMessage or ndefTag.getNdefMessage. +// var ndefMessage = tag.ndef.createNdefMessage(...); +// var ndefMessage = ndefTag.getNdefMessage(); + +let ndefRecords = ndefMessage.getNdefRecords(); console.log("ndef ndefRecords number: " + ndefRecords.length); ``` -### NdefTag.createNdefMessage9+ - -createNdefMessage(ndefRecords: NdefRecord[]): [NdefMessage](#ndefmessage9) - -Creates an NDEF message using the NDEF records. - -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC - -**Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| 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. For details, see *NFCForum-TS-NDEF_1.0*.| - -**Example** +## NdefTag9+ -```js -import tag from '@ohos.nfc.tag'; +Provides APIs to access the tags in the NFC Data Exchange Format (NDEF). This class inherits from **TagSession**. -// 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, ...]}, +**TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). - // 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); -``` +The following describes the unique APIs of **NdefTag**. ### NdefTag.getNdefTagType9+ -getNdefTagType(): NfcForumType +getNdefTagType(): [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) -Obtains the type of this NDEF tag. +Obtains the NDEF tag type. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | NDEF tag type obtained. It can be NFC FORUM TYPE 1, 2, 3, or 4.| +| [tag.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'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefTagType = ndef.getNdefTagType(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefTagType = ndefTag.getNdefTagType(); console.log("ndef ndefTagType: " + ndefTagType); ``` ### NdefTag.getNdefMessage9+ -getNdefMessage(): NdefMessage +getNdefMessage(): [NdefMessage](#ndefmessage9) -Obtains the NDEF message. +Obtains the NDEF message from this NDEF tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [NdefMessage](#ndefmessage9) | NDEF message obtained. For details, see *NFCForum-TS-NDEF_1.0*.| +| [NdefMessage](#ndefmessage9) | NDEF message created. For details, see *NFCForum-TS-NDEF_1.0*.| **Example** - ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -let ndefMessage = ndef.getNdefMessage(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +let ndefMessage = ndefTag.getNdefMessage(); console.log("ndef ndefMessage: " + ndefMessage); ``` ### NdefTag.isNdefWritable9+ -isNdefWritable(): Promise<boolean> - -Checks whether the NDEF tag is writable. This API uses a promise to return the result. +isNdefWritable(): boolean; -**Required permissions**: ohos.permission.NFC_TAG +Check whether this NDEF tag is writable. Before calling the data write API, check whether the write operation is supported. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise<boolean> | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| - -**Example** - -```js -import tag from '@ohos.nfc.tag'; - -// 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+ - -isNdefWritable(callback: AsyncCallback<boolean>): void; - -Checks whether the NDEF tag is writable. 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 is writable, **true** is returned; otherwise, **false** is returned.| +| boolean | Promise used to return the result. If the tag is writable, **true** is returned; otherwise, **false** is returned.| **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); - } -}); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var isWritable = ndefTag.isNdefWritable(); +console.log("ndef isNdefWritable: " + isWritable); ``` ### NdefTag.readNdef9+ -readNdef(): Promise\ +readNdef(): Promise\<[NdefMessage](#ndefmessage9)> Reads the NDEF message from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -610,18 +535,38 @@ Reads the NDEF message from this tag. This API uses a promise to return the resu | ------------------ | --------------------------| | Promise\<[NdefMessage](#ndefmessage9)> | Promise used to return the message read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.readNdef() - .then((data) => { - console.log("ndef readNdef data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.readNdef().then((ndefmessage) => { + console.log("ndef readNdef Promise ndefmessage: " + ndefmessage); }).catch((err)=> { - console.log("ndef readNdef err: " + err); + console.log("ndef readNdef Promise err: " + err); }); +} catch (busiError) { + console.log("ndef readNdef Promise catched busiError: " + busiError); +} ``` ### NdefTag.readNdef9+ @@ -632,38 +577,59 @@ Reads the NDEF message from this tag. This API uses an asynchronous callback to **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\<[NdefMessage](#ndefmessage9)> | Yes | Callback invoked to return the NDEF message read.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.readNdef((err, ndefmessage)=> { + if (err) { + console.log("ndef readNdef AsyncCallback err: " + err); + } else { + console.log("ndef readNdef AsyncCallback ndefmessage: " + ndefmessage); + } + }); +} catch (busiError) { + console.log("ndef readNdef AsyncCallback catched busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage): Promise\; +writeNdef(msg: NdefMessage): Promise\; Writes an NDEF message to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -671,59 +637,97 @@ Writes an NDEF message to this tag. This API uses a promise to return the result | -------- | ----------------------- | ---- | -------------------------------------- | | msg | NdefMessage | Yes | NDEF message to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) -ndef.writeNdef(ndefMessage) - .then((data) => { - console.log("ndef writeNdef data: " + data); +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.writeNdef(ndefMessage).then(() => { + console.log("ndef writeNdef Promise success."); }).catch((err)=> { console.log("ndef writeNdef err: " + err); }); +} catch (busiError) { + console.log("ndef writeNdef Promise catch busiError: " + busiError); +} ``` ### NdefTag.writeNdef9+ -writeNdef(msg: NdefMessage, callback: AsyncCallback\): void +writeNdef(msg: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Writes an NDEF message to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| msg | NdefMessage | Yes | NDEF message to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| msg | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +// NDEF message created from raw data, such as: +let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. +// or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.writeNdef(ndefMessage, (err)=> { + if (err) { + console.log("ndef writeNdef AsyncCallback err: " + err); + } else { + console.log("ndef writeNdef AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef writeNdef AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.canSetReadOnly9+ @@ -734,7 +738,7 @@ Checks whether this NDEF tag can be set to read-only. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -742,92 +746,133 @@ Checks whether this NDEF tag can be set to read-only. | ------------------ | --------------------------| | boolean| Returns **true** if the tag can be set to read-only; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -var canSetReadOnly = ndef.canSetReadOnly(); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. +var canSetReadOnly = ndefTag.canSetReadOnly(); console.log("ndef canSetReadOnly: " + canSetReadOnly); ``` ### NdefTag.setReadOnly9+ -setReadOnly(): Promise\ +setReadOnly(): Promise\ Sets this NDEF tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise<number> | Promise used to return the result. If the operation is successful, **0** is returned; otherwise, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'ndef' correctly. -ndef.setReadOnly() - .then((data) => { - console.log("ndef setReadOnly data: " + data); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; + } +} + +try { + ndefTag.setReadOnly().then(() => { + console.log("ndef setReadOnly Promise success."); }).catch((err)=> { - console.log("ndef setReadOnly err: " + err); + console.log("ndef setReadOnly Promise err: " + err); }); +} catch (busiError) { + console.log("ndef setReadOnly Promise catch busiError: " + busiError); +} ``` ### 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. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +// Connect to the tag if it is not connected. +if (!ndefTag.isTagConnected()) { + if (!ndefTag.connectTag()) { + console.log("ndefTag connectTag failed."); + return; } -}); +} + +try { + ndefTag.setReadOnly((err)=> { + if (err) { + console.log("ndef setReadOnly AsyncCallback err: " + err); + } else { + console.log("ndef setReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndef setReadOnly AsyncCallback catch busiError: " + busiError); +} ``` ### NdefTag.getNdefTagTypeString9+ -getNdefTagTypeString(type: [NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string - -Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. +getNdefTagTypeString(type: [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9)): string -**Required permissions**: ohos.permission.NFC_TAG +Converts an NFC Forum Type tag to a string defined in the NFC Forum. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| type | [NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| +| type | [tag.NfcForumType](js-apis-nfcTag.md#nfcforumtype9) | Yes | NDEF tag type. It can be NFC FORUM type 1, 2, 3, or 4.| **Return value** @@ -840,110 +885,149 @@ Converts an NFC Forum Type tag to a byte array defined in the NFC Forum. ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'ndefTag' correctly. + +try { + let ndefTypeString = ndefTag.getNdefTagTypeString(tag.NFC_FORUM_TYPE_1); + console.log("ndef ndefTypeString: " + ndefTypeString); +} catch (busiError) { + console.log("ndef getNdefTagTypeString catch busiError: " + busiError); +} ``` ## MifareClassicTag9+ -Provides access to MIFARE Classic properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Classic properties and perform I/O operations on a tag. This class inherits from [TagSession](js-apis-tagSession.md). **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareClassicTag**. +The following describes the unique APIs of **MifareClassicTag**. ### MifareClassicTag.authenticateSector9+ -authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ +authenticateSector(sectorIndex: number, key: number[], isKeyA: boolean): Promise\ -Authenticates a sector using the key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If the authentication is successful, **true** is returned. Otherwise, **false** is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true).then(() => { + console.log("mifareClassic authenticateSector Promise success."); }).catch((err)=> { - console.log("mifareClassic authenticateSector err: " + err); + console.log("mifareClassic authenticateSector Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic authenticateSector Promise catch busiError: " + busiError); +} ``` ### 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. +Authenticates a sector using a key. The sector can be accessed only after the authentication is successful. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector to authenticate.| -| key | number[]| Yes | Key (6 bytes) used for authentication.| +| sectorIndex | number | Yes | Index of the sector to authenticate. The sector indexes start from **0**.| +| key | number[]| Yes | Key (6 bytes) used for sector authentication.| | isKeyA | boolean | Yes | Whether the key is key A. The value **true** indicates key A, and **false** indicates key B.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| -**Example** +**Error codes** +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + +**Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let sectorIndex = 1; // Change it as required. + let key = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06] // The key must be of 6 bytes. + mifareClassic.authenticateSector(sectorIndex, key, true, (err)=> { + if (err) { + console.log("mifareClassic authenticateSector AsyncCallback err: " + err); + } else { + console.log("mifareClassic authenticateSector AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic authenticateSector AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number): Promise\ -Reads a block (16 bytes) on the tag. This API uses a promise to return the result. +Reads a block (16 bytes) on this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| **Return value** @@ -951,421 +1035,632 @@ Reads a block (16 bytes) on the tag. This API uses a promise to return the resul | ------------------ | --------------------------| | Promise\ | Promise used to return the block data read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex).then((data) => { + console.log("mifareClassic readSingleBlock Promise data: " + data); + }).catch((err)=> { + console.log("mifareClassic readSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.readSingleBlock9+ readSingleBlock(blockIndex: number, callback: AsyncCallback\): void -Reads a block (16 bytes) on the tag. This API uses an asynchronous callback to return the result. +Reads a block (16 bytes) on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to read.| +| blockIndex | number | Yes | Index of the block to read. The block indexes start from **0**.| | callback | AsyncCallback\ | Yes | Callback invoked to return the block read.| +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | + **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.readSingleBlock(blockIndex, (err, data)=> { + if (err) { + console.log("mifareClassic readSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic readSingleBlock AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareClassic readSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[]): Promise\ +writeSingleBlock(blockIndex: number, data: number[]): Promise\ -Writes data to a block on the tag. This API uses a promise to return the result. +Writes data to a block on this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData).then(() => { + console.log("mifareClassic writeSingleBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic writeSingleBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.writeSingleBlock9+ -writeSingleBlock(blockIndex: number, data: number[], 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. +Writes data to a block on this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the target block.| -| data | number[] | Yes | Data to write.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The block indexes start from **0**.| +| data | number[] | Yes | 16-byte data to write.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0A, + 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x10]; // MUST be 16 bytes, change it to be correct data. + mifareClassic.writeSingleBlock(blockIndex, rawData, (err)=> { + if (err) { + console.log("mifareClassic writeSingleBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic writeSingleBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic writeSingleBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number): Promise\ +incrementBlock(blockIndex: number, value: number): Promise\ Increments a block with data. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic incrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic incrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.incrementBlock9+ -incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +incrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void Increments a block with data. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to increment.| -| value | number | Yes | Block data to increment. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to increment. The block indexes start from **0**.| +| value | number | Yes | Block data to increment. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.incrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic incrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic incrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic incrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number): Promise\ +decrementBlock(blockIndex: number, value: number): Promise\ -Decrements a block with data. This API uses a promise to return the result. +Decrements a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value).then(() => { + console.log("mifareClassic decrementBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic decrementBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.decrementBlock9+ -decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void +decrementBlock(blockIndex: number, value: number, callback: AsyncCallback\): void -Decrements a block with data. This API uses an asynchronous callback to return the result. +Decrements a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block to decrement.| -| value | number | Yes | Block data to decrement. The value is a non-negative number.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the block to decrement. The block indexes start from **0**.| +| value | number | Yes | Block data to decrement. The value cannot be a negative number.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + let value = 0x20; // Change it as required. + mifareClassic.decrementBlock(blockIndex, value, (err)=> { + if (err) { + console.log("mifareClassic decrementBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic decrementBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic decrementBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number): Promise\ +transferToBlock(blockIndex: number): Promise\ -Copies data from the register to a block. This API uses a promise to return the result. +Transfers data from the temporary register to a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js - import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex).then(() => { + console.log("mifareClassic transferToBlock Promise success."); + }).catch((err)=> { + console.log("mifareClassic transferToBlock Promise err: " + err); + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.transferToBlock9+ -transferToBlock(blockIndex: number, callback: AsyncCallback\): void +transferToBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from the register to a block. This API uses an asynchronous callback to return the result. +Transfers data from the temporary register to a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the destination block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the destination block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.transferToBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic transferToBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic transferToBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic transferToBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number): Promise\ +restoreFromBlock(blockIndex: number): Promise\ -Copies data from a block to the register. This API uses a promise to return the result. +Restores data in the temporary register from a block. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js - import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; + } +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex).then(() => { + console.log("mifareClassic restoreFromBlock Promise success."); }).catch((err)=> { - console.log("mifareClassic isExtendrestoreFromBlockedApduSupported err: " + err); + console.log("mifareClassic restoreFromBlock Promise err: " + err); }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock Promise catch busiError: " + busiError); +} ``` ### MifareClassicTag.restoreFromBlock9+ -restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void +restoreFromBlock(blockIndex: number, callback: AsyncCallback\): void -Copies data from a block to the register. This API uses an asynchronous callback to return the result. +Restores data in the temporary register from a block. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the source block.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| blockIndex | number | Yes | Index of the target block. The value starts form **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +// Connect to the tag if it is not connected. +if (!mifareClassic.isTagConnected()) { + if (!mifareClassic.connectTag()) { + console.log("mifareClassic connectTag failed."); + return; } -}); +} + +try { + let blockIndex = 1; // Change it as required. + mifareClassic.restoreFromBlock(blockIndex, (err)=> { + if (err) { + console.log("mifareClassic restoreFromBlock AsyncCallback err: " + err); + } else { + console.log("mifareClassic restoreFromBlock AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareClassic restoreFromBlock AsyncCallback catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorCount9+ @@ -1374,9 +1669,7 @@ getSectorCount(): number Obtains the number of sectors in this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1389,7 +1682,7 @@ Obtains the number of sectors in this MIFARE Classic tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let sectorCount = mifareClassic.getSectorCount(); console.log("mifareClassic sectorCount: " + sectorCount); ``` @@ -1400,15 +1693,13 @@ getBlockCountInSector(sectorIndex: number): number Obtains the number of blocks in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1421,33 +1712,37 @@ Obtains the number of blocks in a sector. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. -let blockCountInSector = mifareClassic.getBlockCountInSector(); -console.log("mifareClassic blockCountInSector: " + blockCountInSector); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockCnt = mifareClassic.getBlockCountInSector(sectorIndex); + console.log("mifareClassic blockCnt: " + blockCnt); +} catch (busiError) { + console.log("mifareClassic getBlockCountInSector catch busiError: " + busiError); +} ``` ### MifareClassicTag.getType9+ -getType(): [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) +getType(): [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) Obtains the type of this MIFARE Classic tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| [MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| +| [tag.MifareClassicType](js-apis-nfcTag.md#mifareclassictype9) | Type of the MIFARE Classic tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let getType = mifareClassic.getType(); console.log("mifareClassic getType: " + getType); ``` @@ -1456,11 +1751,9 @@ console.log("mifareClassic getType: " + getType); getTagSize(): number -Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the size of this tag. For details, see [MifareClassicSize](js-apis-nfcTag.md#mifareclassicsize9). -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1473,7 +1766,7 @@ Obtains the tag size (in bytes). For details, see [MifareClassicSize](js-apis-nf ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let tagSize = mifareClassic.getTagSize(); console.log("mifareClassic tagSize: " + tagSize); ``` @@ -1482,11 +1775,9 @@ console.log("mifareClassic tagSize: " + tagSize); isEmulatedTag(): boolean -Checks whether the tag is an emulated tag. +Checks whether it is an emulated tag. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** @@ -1499,7 +1790,7 @@ Checks whether the tag is an emulated tag. ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareClassic' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. let isEmulatedTag = mifareClassic.isEmulatedTag(); console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); ``` @@ -1508,17 +1799,15 @@ console.log("mifareClassic isEmulatedTag: " + isEmulatedTag); getBlockIndex(sectorIndex: number): number -Obtains the first block of a sector. +Obtains the index of the first block in a sector. -**Required permissions**: ohos.permission.NFC_TAG - -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| sectorIndex | number | Yes | Index of the sector.| +| sectorIndex | number | Yes | Index of the target sector. The sector indexes start from **0**.| **Return value** @@ -1531,27 +1820,30 @@ Obtains the first block of a sector. ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let sectorIndex = 1; // Change it as required. + let blockIndex = mifareClassic.getBlockIndex(sectorIndex); + console.log("mifareClassic blockIndex: " + blockIndex); +} catch (busiError) { + console.log("mifareClassic getBlockIndex catch busiError: " + busiError); +} ``` ### MifareClassicTag.getSectorIndex9+ getSectorIndex(blockIndex: number): number -Obtains the index of a sector that contains the specified block. - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the index of a sector that holds the specified block. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| blockIndex | number | Yes | Index of the block contained in the sector.| +| blockIndex | number | Yes| Index of the block. The block indexes start from **0**.| **Return value** @@ -1564,41 +1856,54 @@ Obtains the index of a sector that contains the specified block. ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareClassic' correctly. + +try { + let blockIndex = 1; // Change it as required. + let sectorIndex = mifareClassic.getSectorIndex(blockIndex); + console.log("mifareClassic sectorIndex: " + sectorIndex); +} catch (busiError) { + console.log("mifareClassic getSectorIndex catch busiError: " + busiError); +} ``` ## MifareUltralightTag9+ -Provides access to MIFARE Ultralight properties and I/O operations. This class inherits from **TagSession**. +Provides APIs to access MIFARE Ultralight properties and perform I/O operations on a tag. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **MifareUltralightTag**. +The following describes the unique APIs of **MifareUltralightTag**. ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number): Promise\ -Reads multiple pages (4 bytes per page). This API uses a promise to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------ | -| pageIndex | number | Yes | Indexes of the pages to read.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| Promise\ | Promise used to return the data read.| +| Promise\ | Promise used to return the data read, which is 16 bytes in total.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** @@ -1606,207 +1911,286 @@ Reads multiple pages (4 bytes per page). This API uses a promise to return the r import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex).then((data) => { + console.log("mifareUltralight readMultiplePages Promise data = " + data); }).catch((err)=> { - console.log("mifareUltralight readMultiplePages err: " + err); + console.log("mifareUltralight readMultiplePages Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages Promise catch busiError: " + busiError); +} ``` ### MifareUltralightTag.readMultiplePages9+ readMultiplePages(pageIndex: number, callback: AsyncCallback\): void -Reads multiple pages (4 bytes per page). This API uses an asynchronous callback to return the result. +Reads four pages (4 bytes per page) from this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Indexes of the pages to read.| -| callback | AsyncCallback\ | Yes | Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the first page to read. The page indexes start from **0**.| +| callback | AsyncCallback\ | Yes | Callback invoked to return the data read, which is 16 bytes in total.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + mifareUltralight.readMultiplePages(pageIndex, (err, data)=> { + if (err) { + console.log("mifareUltralight readMultiplePages AsyncCallback err: " + err); + } else { + console.log("mifareUltralight readMultiplePages AsyncCallback data: " + data); + } + }); +} catch (busiError) { + console.log("mifareUltralight readMultiplePages AsyncCallback catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[]): Promise\ +writeSinglePage(pageIndex: number, data: number[]): Promise\ -Writes a page of data. This API uses a promise to return the result. +Writes one page (4 bytes) of data to this tag. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------------------- | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; + } +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData).then(() => { + console.log("mifareUltralight writeSinglePage Promise success."); }).catch((err)=> { - console.log("mifareUltralight writeSinglePages err: " + err); + console.log("mifareUltralight writeSinglePage Promise err: " + err); }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage Promise catch busiError: " + busiError); +} ``` -### MifareUltralightTag.writeSinglePages9+ +### MifareUltralightTag.writeSinglePage9+ -writeSinglePages(pageIndex: number, data: number[], callback: AsyncCallback\): void +writeSinglePage(pageIndex: number, data: number[], callback: AsyncCallback\): void -Writes a page of data. This API uses an asynchronous callback to return the result. +Writes one page (4 bytes) of data to this tag. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------ | -| pageIndex | number | Yes | Index of the page.| -| data | number[] | Yes | Data to write.| -| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| +| pageIndex | number | Yes | Index of the page to write. The page indexes start from **0**.| +| data | number[] | Yes | 4-byte data to write.| +| callback|AsyncCallback\ |Yes| Callback invoked to return the result.| + +**Error codes** + +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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); +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. + +// Connect to the tag if it is not connected. +if (!mifareUltralight.isTagConnected()) { + if (!mifareUltralight.connectTag()) { + console.log("mifareUltralight connectTag failed."); + return; } -}); +} + +try { + let pageIndex = 1; // Change it as required. + let rawData = [0x01, 0x02, 0x03, 0x04]; // MUST be 4 bytes, change it to be correct raw data. + mifareUltralight.writeSinglePage(pageIndex, rawData, (err)=> { + if (err) { + console.log("mifareUltralight writeSinglePage AsyncCallback err: " + err); + } else { + console.log("mifareUltralight writeSinglePage AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("mifareUltralight writeSinglePage AsyncCallback catch busiError: " + busiError); +} ``` ### MifareUltralightTag.getType9+ -getType(): MifareUltralightType +getType(): [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) -Obtains the MIFARE Ultralight tag type, in bytes. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9). - -**Required permissions**: ohos.permission.NFC_TAG +Obtains the type of this MIFARE Ultralight tag. -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Return value** | **Type**| **Description** | | ------------------ | --------------------------| -| MifareUltralightType | MIFARE Ultralight tag type obtained. For details, see [MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9).| +| [tag.MifareUltralightType](js-apis-nfcTag.md#mifareultralighttype9) | Type of the MIFARE Ultralight tag obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// Check whether 'tag.TagInfo' at 'js-apis-nfcTag' has obtained the 'mifareUltralight' correctly. +// Check whether 'tag.TagInfo' in 'js-apis-nfcTag.md' has obtained 'mifareUltralight' correctly. let getType = mifareClassic.getType(); console.log("mifareUltralight getType: " + getType); ``` ## NdefFormatableTag9+ -Provides APIs for operating NDEF formattable tags. This class inherits from **TagSession**. +Provides APIs for formatting NDEF formattable tags. This class inherits from **TagSession**. **TagSession** is the base class of all NFC tag technologies. It provides common interfaces for establishing connections and transferring data. For more details, see [TagSession](js-apis-tagSession.md). -The following describes the unique interfaces of **NdefFormatableTag**. +The following describes the unique APIs of **NdefFormatableTag**. ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9)): Promise\ +format(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses a promise to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | 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 (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// 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); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage).then(() => { + console.log("ndefFormatable format Promise success."); + }).catch((err)=> { + console.log("ndefFormatable format Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable format Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.format9+ -format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +format(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void -Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API uses an asynchronous callback to return the result. +Formats this tag as an NDEF tag, and writes an NDEF message to it. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** @@ -1818,7 +2202,7 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API | **Type**| **Description** | | ------------------ | --------------------------| -| callback: AsyncCallback\ | Callback invoked to return the result.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1826,82 +2210,108 @@ Formats this tag as an NDEF tag, and writes an NDEF message to the tag. This API ```js import tag from '@ohos.nfc.tag'; -// 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' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// 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); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.format(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable format AsyncCallback err: " + err); + } else { + console.log("ndefFormatable format AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable format AsyncCallback catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ +formatReadOnly(message: [NdefMessage](#ndefmessage9)): Promise\ -Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses a promise to return the result. +Formats this tag as an NDEF tag, writes an NDEF message to it, and then sets the tag to read-only. This API uses a promise to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | 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 (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. If this parameter is **null**, the tag is formatted only (no data will be written).| -**Return value** +**Error codes** -| **Type**| **Description** | -| ------------------ | --------------------------| -| Promise\ | Promise used to return the result. If **0** is returned, the operation is successful. If the operation fails, an error code is returned.| +For details about the error codes, see [NFC Error Codes](../errorcodes/errorcode-nfc.md). + +| ID| Error Message| +| ------- | -------| +| 3100201 | Tag running state is abnormal in service. | **Example** ```js import tag from '@ohos.nfc.tag'; -// 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' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// 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); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage).then(() => { + console.log("ndefFormatable formatReadOnly Promise success."); + }).catch((err)=> { + console.log("ndefFormatable formatReadOnly Promise err: " + err); + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly Promise catch busiError: " + busiError); +} ``` ### NdefFormatableTag.formatReadOnly9+ -formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void +formatReadOnly(message: [NdefMessage](#ndefmessage9), callback: AsyncCallback\): void Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and then sets the tag to read-only. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.NFC_TAG -**System capability**: SystemCapability.Communication.NFC +**System capability**: SystemCapability.Communication.NFC.Core **Parameters** | 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 (no data will be written).| +| message | [NdefMessage](#ndefmessage9) | Yes | NDEF message to write. 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.| +| callback: AsyncCallback\ | Callback invoked to return the result.| **Example** @@ -1909,16 +2319,29 @@ Formats this tag as an NDEF tag, writes an NDEF message to the NDEF tag, and the ```js import tag from '@ohos.nfc.tag'; -// 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' in 'js-apis-nfcTag.md' has obtained 'ndefFormatable' correctly. -// 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); +// Connect to the tag if it is not connected. +if (!ndefFormatable.isTagConnected()) { + if (!ndefFormatable.connectTag()) { + console.log("ndefFormatable connectTag failed."); + return; } -}); +} + +try { + // NDEF message created from raw data, such as: + let ndefMessage = tag.ndef.createNdefMessage([0xD1, 0x01, 0x03, 0x54, 0x4E, 0x46, 0x43]); // It must be parsed as NDEF Record. + // or ndefMessage created from tag.ndef.createNdefMessage(ndefRecords: NdefRecord[]) + + ndefFormatable.formatReadOnly(ndefMessage, (err)=> { + if (err) { + console.log("ndefFormatable formatReadOnly AsyncCallback err: " + err); + } else { + console.log("ndefFormatable formatReadOnly AsyncCallback success."); + } + }); +} catch (busiError) { + console.log("ndefFormatable formatReadOnly AsyncCallback catch busiError: " + busiError); +} ``` diff --git a/en/application-dev/reference/apis/js-apis-notification.md b/en/application-dev/reference/apis/js-apis-notification.md index ff80fc8564758868ec979ff6bf033b7084fea561..9fdf5e1f345b68fcd99e6e027cfb0c44d5da29d8 100644 --- a/en/application-dev/reference/apis/js-apis-notification.md +++ b/en/application-dev/reference/apis/js-apis-notification.md @@ -1,12 +1,12 @@ -# Notification +# @ohos.notification The **Notification** module provides notification management capabilities, covering notifications, notification slots, notification subscription, notification enabled status, and notification badge status. -Generally, only system applications have the permission to subscribe to and unsubscribe from notifications. - > **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. +> +> Notification subscription and unsubscription APIs are available only to system applications. ## Modules to Import @@ -26,8 +26,8 @@ Publishes a notification. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -69,7 +69,7 @@ Publishes a notification. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| **Example** @@ -87,7 +87,7 @@ var notificationRequest = { } } Notification.publish(notificationRequest).then(() => { - console.info("publish sucess"); + console.info("publish success"); }); ``` @@ -96,7 +96,7 @@ Notification.publish(notificationRequest).then(() => { publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void -Publishes a notification. This API uses an asynchronous callback to return the result. +Publishes a notification to a specified user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -108,8 +108,8 @@ Publishes a notification. This API uses an asynchronous callback to return the r | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| -| userId | number | Yes | ID of the user who receives the notification. | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| userId | number | Yes | User ID. | | callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -123,7 +123,7 @@ function publishCallback(err) { console.info("publish success"); } } -// ID of the user who receives the notification +// User ID var userId = 1 // NotificationRequest object var notificationRequest = { @@ -144,7 +144,7 @@ Notification.publish(notificationRequest, userId, publishCallback); publish(request: NotificationRequest, userId: number): Promise\ -Publishes a notification. This API uses a promise to return the result. +Publishes a notification to a specified user. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -156,8 +156,8 @@ Publishes a notification. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ----------------------------------------- | ---- | ------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| -| userId | number | Yes | ID of the user who receives the notification. | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| userId | number | Yes | User ID. | **Example** @@ -177,7 +177,7 @@ var notificationRequest = { var userId = 1 Notification.publish(notificationRequest, userId).then(() => { - console.info("publish sucess"); + console.info("publish success"); }); ``` @@ -218,7 +218,7 @@ Notification.cancel(0, "label", cancelCallback) cancel(id: number, label?: string): Promise\ -Cancels a notification with the specified ID and label. This API uses a promise to return the result. +Cancels a notification with the specified ID and optional label. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -233,7 +233,7 @@ Cancels a notification with the specified ID and label. This API uses a promise ```js Notification.cancel(0).then(() => { - console.info("cancel sucess"); + console.info("cancel success"); }); ``` @@ -312,7 +312,7 @@ Cancels all notifications. This API uses a promise to return the result. ```js Notification.cancelAll().then(() => { - console.info("cancelAll sucess"); + console.info("cancelAll success"); }); ``` @@ -383,7 +383,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.addSlot(notificationSlot).then(() => { - console.info("addSlot sucess"); + console.info("addSlot success"); }); ``` @@ -393,7 +393,7 @@ Notification.addSlot(notificationSlot).then(() => { addSlot(type: SlotType, callback: AsyncCallback\): void -Adds a notification slot. This API uses an asynchronous callback to return the result. +Adds a notification slot of a specified type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -424,7 +424,7 @@ Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack addSlot(type: SlotType): Promise\ -Adds a notification slot. This API uses a promise to return the result. +Adds a notification slot of a specified type. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -438,7 +438,7 @@ Adds a notification slot. This API uses a promise to return the result. ```js Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { - console.info("addSlot sucess"); + console.info("addSlot success"); }); ``` @@ -448,7 +448,7 @@ Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { addSlots(slots: Array\, callback: AsyncCallback\): void -Adds multiple notification slots. This API uses an asynchronous callback to return the result. +Adds an array of notification slots. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -491,7 +491,7 @@ Notification.addSlots(notificationSlotArray, addSlotsCallBack) addSlots(slots: Array\): Promise\ -Adds multiple notification slots. This API uses a promise to return the result. +Adds an array of notification slots. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -517,7 +517,7 @@ var notificationSlotArray = new Array(); notificationSlotArray[0] = notificationSlot; Notification.addSlots(notificationSlotArray).then(() => { - console.info("addSlots sucess"); + console.info("addSlots success"); }); ``` @@ -527,7 +527,7 @@ Notification.addSlots(notificationSlotArray).then(() => { getSlot(slotType: SlotType, callback: AsyncCallback\): void -Obtains a notification slot of the specified type. This API uses an asynchronous callback to return the result. +Obtains a notification slot of a specified type. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -542,7 +542,7 @@ Obtains a notification slot of the specified type. This API uses an asynchronous ```js // getSlot callback -function getSlotCallback(err,data) { +function getSlotCallback(err, data) { if (err.code) { console.info("getSlot failed " + JSON.stringify(err)); } else { @@ -559,7 +559,7 @@ Notification.getSlot(slotType, getSlotCallback) getSlot(slotType: SlotType): Promise\ -Obtains a notification slot of the specified type. This API uses a promise to return the result. +Obtains a notification slot of a specified type. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -580,7 +580,7 @@ Obtains a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.getSlot(slotType).then((data) => { - console.info("getSlot sucess, data: " + JSON.stringify(data)); + console.info("getSlot success, data: " + JSON.stringify(data)); }); ``` @@ -604,7 +604,7 @@ Obtains all notification slots. This API uses an asynchronous callback to return ```js // getSlots callback -function getSlotsCallback(err,data) { +function getSlotsCallback(err, data) { if (err.code) { console.info("getSlots failed " + JSON.stringify(err)); } else { @@ -634,7 +634,7 @@ Obtains all notification slots of this application. This API uses a promise to r ```js Notification.getSlots().then((data) => { - console.info("getSlots sucess, data: " + JSON.stringify(data)); + console.info("getSlots success, data: " + JSON.stringify(data)); }); ``` @@ -644,7 +644,7 @@ Notification.getSlots().then((data) => { removeSlot(slotType: SlotType, callback: AsyncCallback\): void -Removes a notification slot of the specified type. This API uses an asynchronous callback to return the result. +Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -676,7 +676,7 @@ Notification.removeSlot(slotType,removeSlotCallback) removeSlot(slotType: SlotType): Promise\ -Removes a notification slot of the specified type. This API uses a promise to return the result. +Removes a notification slot of a specified type. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -691,7 +691,7 @@ Removes a notification slot of the specified type. This API uses a promise to re ```js var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; Notification.removeSlot(slotType).then(() => { - console.info("removeSlot sucess"); + console.info("removeSlot success"); }); ``` @@ -738,7 +738,7 @@ Removes all notification slots. This API uses a promise to return the result. ```js Notification.removeAllSlots().then(() => { - console.info("removeAllSlots sucess"); + console.info("removeAllSlots success"); }); ``` @@ -761,7 +761,7 @@ Subscribes to a notification with the subscription information specified. This A | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ---------------- | | subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Subscription information. | +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Notification subscription information.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -782,7 +782,7 @@ var subscriber = { onConsume: onConsumeCallback } var info = { - bundleNames: ["bundleName1","bundleName2"] + bundleNames: ["bundleName1", "bundleName2"] } Notification.subscribe(subscriber, info, subscribeCallback); ``` @@ -793,7 +793,7 @@ Notification.subscribe(subscriber, info, subscribeCallback); subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void -Subscribes to a notification with the subscription information specified. This API uses an asynchronous callback to return the result. +Subscribes to notifications of all applications under this user. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -846,23 +846,19 @@ Subscribes to a notification with the subscription information specified. This A | Name | Type | Mandatory| Description | | ---------- | ------------------------- | ---- | ------------ | | subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| -| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Subscription information. | +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Notification subscription information. | **Example** ```js function onConsumeCallback(data) { - if (err.code) { - console.info("subscribe failed " + JSON.stringify(err)); - } else { - console.info("subscribe success"); - } + console.info("Consume callback: " + JSON.stringify(data)); } var subscriber = { onConsume: onConsumeCallback }; Notification.subscribe(subscriber).then(() => { - console.info("subscribe sucess"); + console.info("subscribe success"); }); ``` @@ -897,11 +893,11 @@ function unsubscribeCallback(err) { console.info("unsubscribe success"); } } -function onCancelCallback(data) { +function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onCancel: onCancelCallback + onDisconnect: onDisconnectCallback } Notification.unsubscribe(subscriber, unsubscribeCallback); ``` @@ -929,14 +925,14 @@ Unsubscribes from a notification. This API uses a promise to return the result. **Example** ```js -function onCancelCallback(data) { +function onDisconnectCallback(data) { console.info("Cancel callback: " + JSON.stringify(data)); } var subscriber = { - onCancel: onCancelCallback + onDisconnect: onDisconnectCallback }; Notification.unsubscribe(subscriber).then(() => { - console.info("unsubscribe sucess"); + console.info("unsubscribe success"); }); ``` @@ -946,7 +942,7 @@ Notification.unsubscribe(subscriber).then(() => { enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -Sets whether to enable notification for a specified bundle. This API uses an asynchronous callback to return the result. +Sets whether to enable notification for a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -958,7 +954,7 @@ Sets whether to enable notification for a specified bundle. This API uses an asy | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -984,7 +980,7 @@ Notification.enableNotification(bundle, false, enableNotificationCallback); enableNotification(bundle: BundleOption, enable: boolean): Promise\ -Sets whether to enable notification for a specified bundle. This API uses a promise to return the result. +Sets whether to enable notification for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -996,7 +992,7 @@ Sets whether to enable notification for a specified bundle. This API uses a prom | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| | enable | boolean | Yes | Whether to enable notification. | **Example** @@ -1006,7 +1002,7 @@ var bundle = { bundle: "bundleName1", } Notification.enableNotification(bundle, false).then(() => { - console.info("enableNotification sucess"); + console.info("enableNotification success"); }); ``` @@ -1016,7 +1012,7 @@ Notification.enableNotification(bundle, false).then(() => { isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void -Checks whether notification is enabled for a specified bundle. This API uses an asynchronous callback to return the result. +Checks whether notification is enabled for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1028,7 +1024,7 @@ Checks whether notification is enabled for a specified bundle. This API uses an | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1053,7 +1049,7 @@ Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); isNotificationEnabled(bundle: BundleOption): Promise\ -Checks whether notification is enabled for a specified bundle. This API uses a promise to return the result. +Checks whether notification is enabled for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1065,12 +1061,12 @@ Checks whether notification is enabled for a specified bundle. This API uses a p | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ------------------ | --------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** @@ -1080,7 +1076,7 @@ var bundle = { bundle: "bundleName1", } Notification.isNotificationEnabled(bundle).then((data) => { - console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); + console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1136,7 +1132,7 @@ Checks whether notification is enabled for this application. This API uses a pro | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| **Return value** @@ -1148,7 +1144,7 @@ Checks whether notification is enabled for this application. This API uses a pro ```js Notification.isNotificationEnabled().then((data) => { - console.info("isNotificationEnabled sucess, data: " + JSON.stringify(data)); + console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); }); ``` @@ -1158,7 +1154,7 @@ Notification.isNotificationEnabled().then((data) => { displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -Sets whether to enable the notification badge for a specified bundle. This API uses an asynchronous callback to return the result. +Sets whether to enable the notification badge for a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1170,7 +1166,7 @@ Sets whether to enable the notification badge for a specified bundle. This API u | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1196,7 +1192,7 @@ Notification.displayBadge(bundle, false, displayBadgeCallback); displayBadge(bundle: BundleOption, enable: boolean): Promise\ -Sets the notification slot for a specified bundle. This API uses a promise to return the result. +Sets whether to enable the notification badge for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1208,7 +1204,7 @@ Sets the notification slot for a specified bundle. This API uses a promise to re | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| | enable | boolean | Yes | Whether to enable notification. | **Example** @@ -1218,7 +1214,7 @@ var bundle = { bundle: "bundleName1", } Notification.displayBadge(bundle, false).then(() => { - console.info("displayBadge sucess"); + console.info("displayBadge success"); }); ``` @@ -1228,7 +1224,7 @@ Notification.displayBadge(bundle, false).then(() => { isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void -Checks whether the notification badge is enabled for a specified bundle. This API uses an asynchronous callback to return the result. +Checks whether the notification badge is enabled for a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1240,7 +1236,7 @@ Checks whether the notification badge is enabled for a specified bundle. This AP | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------ | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1265,7 +1261,7 @@ Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); isBadgeDisplayed(bundle: BundleOption): Promise\ -Checks whether the notification badge is enabled for a specified bundle. This API uses a promise to return the result. +Checks whether the notification badge is enabled for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1277,7 +1273,7 @@ Checks whether the notification badge is enabled for a specified bundle. This AP | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| **Return value** @@ -1292,7 +1288,7 @@ var bundle = { bundle: "bundleName1", } Notification.isBadgeDisplayed(bundle).then((data) => { - console.info("isBadgeDisplayed sucess, data: " + JSON.stringify(data)); + console.info("isBadgeDisplayed success, data: " + JSON.stringify(data)); }); ``` @@ -1302,7 +1298,7 @@ Notification.isBadgeDisplayed(bundle).then((data) => { setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void -Sets the notification slot for a specified bundle. This API uses an asynchronous callback to return the result. +Sets the notification slot for a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1314,7 +1310,7 @@ Sets the notification slot for a specified bundle. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | slot | [NotificationSlot](#notificationslot) | Yes | Notification slot. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1343,7 +1339,7 @@ Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ -Sets the notification slot for a specified bundle. This API uses a promise to return the result. +Sets the notification slot for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1355,8 +1351,8 @@ Sets the notification slot for a specified bundle. This API uses a promise to re | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| -| slot | [NotificationSlot](#notificationslot) | Yes | Whether to enable notification. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot.| **Example** @@ -1368,7 +1364,7 @@ var notificationSlot = { type: Notification.SlotType.SOCIAL_COMMUNICATION } Notification.setSlotByBundle(bundle, notificationSlot).then(() => { - console.info("setSlotByBundle sucess"); + console.info("setSlotByBundle success"); }); ``` @@ -1378,7 +1374,7 @@ Notification.setSlotByBundle(bundle, notificationSlot).then(() => { getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void -Obtains the notification slots of a specified bundle. This API uses an asynchronous callback to return the result. +Obtains the notification slots of a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1390,7 +1386,7 @@ Obtains the notification slots of a specified bundle. This API uses an asynchron | Name | Type | Mandatory| Description | | -------- | ---------------------------------------- | ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | callback | AsyncCallback> | Yes | Callback used to return the result.| **Example** @@ -1415,7 +1411,7 @@ Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); getSlotsByBundle(bundle: BundleOption): Promise> -Obtains the notification slots of a specified bundle. This API uses a promise to return the result. +Obtains the notification slots of a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1427,7 +1423,7 @@ Obtains the notification slots of a specified bundle. This API uses a promise to | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| **Return value** @@ -1442,7 +1438,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotsByBundle(bundle).then((data) => { - console.info("getSlotsByBundle sucess, data: " + JSON.stringify(data)); + console.info("getSlotsByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -1452,7 +1448,7 @@ Notification.getSlotsByBundle(bundle).then((data) => { getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void -Obtains the number of notification slots of a specified bundle. This API uses an asynchronous callback to return the result. +Obtains the number of notification slots of a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1464,7 +1460,7 @@ Obtains the number of notification slots of a specified bundle. This API uses an | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1489,7 +1485,7 @@ Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); getSlotNumByBundle(bundle: BundleOption): Promise\ -Obtains the number of notification slots of a specified bundle. This API uses a promise to return the result. +Obtains the number of notification slots of a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1501,7 +1497,7 @@ Obtains the number of notification slots of a specified bundle. This API uses a | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| **Return value** @@ -1516,7 +1512,7 @@ var bundle = { bundle: "bundleName1", } Notification.getSlotNumByBundle(bundle).then((data) => { - console.info("getSlotNumByBundle sucess, data: " + JSON.stringify(data)); + console.info("getSlotNumByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -1538,7 +1534,7 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | --------------- | ----------------------------------| ---- | -------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | | reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -1582,7 +1578,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | --------------- | --------------- | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information.| +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| | notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | | reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | @@ -1598,7 +1594,7 @@ var notificationKey = { } var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(bundle, notificationKey, reason).then(() => { - console.info("remove sucess"); + console.info("remove success"); }); ``` @@ -1620,8 +1616,8 @@ Removes a notification for a specified bundle. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | -------------------- | -| hashCode | string | Yes | Unique notification ID. | -| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | +| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](#onconsume) callback.| +| reason | [RemoveReason](#removereason9) | Yes | Indicates the reason for deleting a notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1659,7 +1655,7 @@ Removes a notification for a specified bundle. This API uses a promise to return | Name | Type | Mandatory| Description | | -------- | ---------- | ---- | ---------- | | hashCode | string | Yes | Unique notification ID.| -| reason | [RemoveReason](#removereason9) | Yes | Reason for removing the notification. | +| reason | [RemoveReason](#removereason9) | Yes | Reason for deleting the notification. | **Example** @@ -1667,7 +1663,7 @@ Removes a notification for a specified bundle. This API uses a promise to return var hashCode = 'hashCode' var reason = Notification.RemoveReason.CLICK_REASON_REMOVE; Notification.remove(hashCode, reason).then(() => { - console.info("remove sucess"); + console.info("remove success"); }); ``` @@ -1677,7 +1673,7 @@ Notification.remove(hashCode, reason).then(() => { removeAll(bundle: BundleOption, callback: AsyncCallback\): void -Removes all notifications for a specified bundle. This API uses an asynchronous callback to return the result. +Removes all notifications for a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1689,7 +1685,7 @@ Removes all notifications for a specified bundle. This API uses an asynchronous | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1748,7 +1744,7 @@ Notification.removeAll(removeAllCallback); removeAll(bundle?: BundleOption): Promise\ -Removes all notifications for a specified user. This API uses a promise to return the result. +Removes all notifications for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1760,13 +1756,14 @@ Removes all notifications for a specified user. This API uses a promise to retur | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| bundle | [BundleOption](#bundleoption) | No | Bundle information.| +| bundle | [BundleOption](#bundleoption) | No | Bundle information of the application.| **Example** ```js +// If no application is specified, notifications of all applications are deleted. Notification.removeAll().then(() => { - console.info("removeAll sucess"); + console.info("removeAll success"); }); ``` @@ -1786,7 +1783,7 @@ Removes all notifications for a specified user. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| userId | number | Yes | ID of the user who receives the notification.| +| userId | number | Yes | User ID.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -1801,7 +1798,6 @@ function removeAllCallback(err) { } var userId = 1 - Notification.removeAll(userId, removeAllCallback); ``` @@ -1821,22 +1817,15 @@ Removes all notifications for a specified user. This API uses a promise to retur | Name | Type | Mandatory| Description | | ------ | ------------ | ---- | ---------- | -| userId | number | Yes | ID of the user who receives the notification.| +| userId | number | Yes | User ID.| **Example** ```js -function removeAllCallback(err) { - if (err.code) { - console.info("removeAll failed " + JSON.stringify(err)); - } else { - console.info("removeAll success"); - } -} - var userId = 1 - -Notification.removeAll(userId, removeAllCallback); +Notification.removeAll(userId).then(() => { + console.info("removeAll success"); +}); ``` @@ -1896,7 +1885,7 @@ Obtains all active notifications. This API uses a promise to return the result. ```js Notification.getAllActiveNotifications().then((data) => { - console.info("getAllActiveNotifications sucess, data: " + JSON.stringify(data)); + console.info("getAllActiveNotifications success, data: " + JSON.stringify(data)); }); ``` @@ -1906,7 +1895,7 @@ Notification.getAllActiveNotifications().then((data) => { getActiveNotificationCount(callback: AsyncCallback\): void -Obtains the number of active notifications. This API uses an asynchronous callback to return the result. +Obtains the number of active notifications of this application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -1936,21 +1925,21 @@ Notification.getActiveNotificationCount(getActiveNotificationCountCallback); getActiveNotificationCount(): Promise\ -Obtains the number of active notifications. This API uses a promise to return the result. +Obtains the number of active notifications of this application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ----------------- | ------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** ```js Notification.getActiveNotificationCount().then((data) => { - console.info("getActiveNotificationCount sucess, data: " + JSON.stringify(data)); + console.info("getActiveNotificationCount success, data: " + JSON.stringify(data)); }); ``` @@ -1996,15 +1985,15 @@ Obtains active notifications of this application. This API uses a promise to ret **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ------------------------------------------------------------ | --------------------------------------- | | Promise\\> | Promise used to return the result.| **Example** ```js Notification.getActiveNotifications().then((data) => { - console.info("removeGroupByBundle sucess, data: " + JSON.stringify(data)); + console.info("removeGroupByBundle success, data: " + JSON.stringify(data)); }); ``` @@ -2014,7 +2003,7 @@ Notification.getActiveNotifications().then((data) => { cancelGroup(groupName: string, callback: AsyncCallback\): void -Cancels a notification group of this application. This API uses an asynchronous callback to return the result. +Cancels notifications under a notification group of this application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2022,7 +2011,7 @@ Cancels a notification group of this application. This API uses an asynchronous | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------- | -| groupName | string | Yes | Name of the notification group. | +| groupName | string | Yes | Name of the notification group, which is specified through [NotificationRequest](#notificationrequest) when the notification is published.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2047,7 +2036,7 @@ Notification.cancelGroup(groupName, cancelGroupCallback); cancelGroup(groupName: string): Promise\ -Cancels a notification group of this application. This API uses a promise to return the result. +Cancels notifications under a notification group of this application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2062,7 +2051,7 @@ Cancels a notification group of this application. This API uses a promise to ret ```js var groupName = "GroupName"; Notification.cancelGroup(groupName).then(() => { - console.info("cancelGroup sucess"); + console.info("cancelGroup success"); }); ``` @@ -2072,7 +2061,7 @@ Notification.cancelGroup(groupName).then(() => { removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void -Removes a notification group for a specified bundle. This API uses an asynchronous callback to return the result. +Removes notifications under a notification group of a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2084,7 +2073,7 @@ Removes a notification group for a specified bundle. This API uses an asynchrono | Name | Type | Mandatory| Description | | --------- | --------------------- | ---- | ---------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | groupName | string | Yes | Name of the notification group. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -2111,7 +2100,7 @@ Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCal removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ -Removes a notification group for a specified bundle. This API uses a promise to return the result. +Removes notifications under a notification group of a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2123,7 +2112,7 @@ Removes a notification group for a specified bundle. This API uses a promise to | Name | Type | Mandatory| Description | | --------- | ------------ | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | groupName | string | Yes | Name of the notification group.| **Example** @@ -2132,7 +2121,7 @@ Removes a notification group for a specified bundle. This API uses a promise to var bundleOption = {bundle: "Bundle"}; var groupName = "GroupName"; Notification.removeGroupByBundle(bundleOption, groupName).then(() => { - console.info("removeGroupByBundle sucess"); + console.info("removeGroupByBundle success"); }); ``` @@ -2206,7 +2195,7 @@ var doNotDisturbDate = { end: new Date(2021, 11, 15, 18, 0) } Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { - console.info("setDoNotDisturbDate sucess"); + console.info("setDoNotDisturbDate success"); }); ``` @@ -2228,7 +2217,7 @@ Sets the DND time for a specified user. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------------------- | | date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set. | -| userId | number | Yes | User ID.| +| userId | number | Yes | ID of the user for whom you want to set the DND time.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -2249,7 +2238,6 @@ var doNotDisturbDate = { } var userId = 1 - Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); ``` @@ -2272,7 +2260,7 @@ Sets the DND time for a specified user. This API uses a promise to return the re | Name | Type | Mandatory| Description | | ------ | ---------------- | ---- | -------------- | | date | [DoNotDisturbDate](#donotdisturbdate8) | Yes | DND time to set.| -| userId | number | Yes | User ID.| +| userId | number | Yes | ID of the user for whom you want to set the DND time.| **Example** @@ -2286,7 +2274,7 @@ var doNotDisturbDate = { var userId = 1 Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { - console.info("setDoNotDisturbDate sucess"); + console.info("setDoNotDisturbDate success"); }); ``` @@ -2312,7 +2300,7 @@ Obtains the DND time. This API uses an asynchronous callback to return the resul **Example** ```js -function getDoNotDisturbDateCallback(err,data) { +function getDoNotDisturbDateCallback(err, data) { if (err.code) { console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); } else { @@ -2339,15 +2327,15 @@ Obtains the DND time. This API uses a promise to return the result. **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ------------------------------------------------- | ----------------------------------------- | | Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| **Example** ```js Notification.getDoNotDisturbDate().then((data) => { - console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); + console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` @@ -2409,8 +2397,8 @@ Obtains the DND time of a specified user. This API uses a promise to return the **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ------------------------------------------------- | ----------------------------------------- | | Promise\<[DoNotDisturbDate](#donotdisturbdate8)\> | Promise used to return the result.| **Example** @@ -2419,7 +2407,7 @@ Obtains the DND time of a specified user. This API uses a promise to return the var userId = 1 Notification.getDoNotDisturbDate(userId).then((data) => { - console.info("getDoNotDisturbDate sucess, data: " + JSON.stringify(data)); + console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); }); ``` @@ -2428,7 +2416,7 @@ Notification.getDoNotDisturbDate(userId).then((data) => { supportDoNotDisturbMode(callback: AsyncCallback\): void -Checks whether the DND mode is supported. This API uses an asynchronous callback to return the result. +Checks whether DND mode is supported. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2462,7 +2450,7 @@ Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); supportDoNotDisturbMode(): Promise\ -Checks whether the DND mode is supported. This API uses a promise to return the result. +Checks whether DND mode is supported. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2480,7 +2468,7 @@ Checks whether the DND mode is supported. This API uses a promise to return the ```js Notification.supportDoNotDisturbMode().then((data) => { - console.info("supportDoNotDisturbMode sucess, data: " + JSON.stringify(data)); + console.info("supportDoNotDisturbMode success, data: " + JSON.stringify(data)); }); ``` @@ -2567,7 +2555,7 @@ Requests notification to be enabled for this application. This API uses an async **Example** ```javascript -function requestEnableNotificationCallback() { +function requestEnableNotificationCallback(err) { if (err.code) { console.info("requestEnableNotification failed " + JSON.stringify(err)); } else { @@ -2591,10 +2579,9 @@ Requests notification to be enabled for this application. This API uses a promis **Example** ```javascript -Notification.requestEnableNotification() - .then(() => { - console.info("requestEnableNotification sucess"); - }); +Notification.requestEnableNotification().then(() => { + console.info("requestEnableNotification success"); +}); ``` @@ -2614,13 +2601,13 @@ Sets whether this device supports distributed notifications. This API uses an as | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| enable | boolean | Yes | Whether the device supports distributed notifications.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| +| enable | boolean | Yes | Whether the device supports distributed notifications.| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```javascript -function enabledNotificationCallback() { +function enabledNotificationCallback(err) { if (err.code) { console.info("enableDistributed failed " + JSON.stringify(err)); } else { @@ -2651,17 +2638,15 @@ Sets whether this device supports distributed notifications. This API uses a pro | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| enable | boolean | Yes | Whether the device supports distributed notifications.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| +| enable | boolean | Yes | Whether the device supports distributed notifications.| **Example** ```javascript var enable = true - -Notification.enableDistributed(enable) - .then(() => { - console.info("enableDistributed sucess"); - }); +Notification.enableDistributed(enable).then(() => { + console.info("enableDistributed success"); +}); ``` @@ -2669,7 +2654,7 @@ Notification.enableDistributed(enable) isDistributedEnabled(callback: AsyncCallback\): void -Obtains whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. +Checks whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2682,11 +2667,11 @@ Obtains whether this device supports distributed notifications. This API uses an **Example** ```javascript -function isDistributedEnabledCallback() { +function isDistributedEnabledCallback(err, data) { if (err.code) { console.info("isDistributedEnabled failed " + JSON.stringify(err)); } else { - console.info("isDistributedEnabled success"); + console.info("isDistributedEnabled success " + JSON.stringify(data)); } }; @@ -2699,23 +2684,22 @@ Notification.isDistributedEnabled(isDistributedEnabledCallback); isDistributedEnabled(): Promise\ -Obtains whether this device supports distributed notifications. This API uses a promise to return the result. +Checks whether this device supports distributed notifications. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification **Return value** -| Type | Description | -| ------------------ | --------------- | -| Promise\ | Promise used to return the result.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| +| Type | Description | +| ------------------ | --------------------------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```javascript -Notification.isDistributedEnabled() - .then((data) => { - console.info("isDistributedEnabled sucess, data: " + JSON.stringify(data)); - }); +Notification.isDistributedEnabled().then((data) => { + console.info("isDistributedEnabled success, data: " + JSON.stringify(data)); +}); ``` @@ -2723,7 +2707,7 @@ Notification.isDistributedEnabled() enableDistributedByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void -Sets whether an application supports distributed notifications based on the bundle. This API uses an asynchronous callback to return the result. +Sets whether a specified application supports distributed notifications. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2735,14 +2719,14 @@ Sets whether an application supports distributed notifications based on the bund | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | -------------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Application bundle. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | enable | boolean | Yes | Whether the device supports distributed notifications. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```javascript -function enableDistributedByBundleCallback() { +function enableDistributedByBundleCallback(err) { if (err.code) { console.info("enableDistributedByBundle failed " + JSON.stringify(err)); } else { @@ -2765,7 +2749,7 @@ Notification.enableDistributedByBundle(bundle, enable, enableDistributedByBundle enableDistributedByBundle(bundle: BundleOption, enable: boolean): Promise\ -Sets whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. +Sets whether a specified application supports distributed notifications. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2788,11 +2772,9 @@ var bundle = { } var enable = true - -Notification.enableDistributedByBundle(bundle, enable) - .then(() => { - console.info("enableDistributedByBundle sucess"); - }); +Notification.enableDistributedByBundle(bundle, enable).then(() => { + console.info("enableDistributedByBundle success"); +}); ``` ## Notification.isDistributedEnabledByBundle8+ @@ -2817,11 +2799,11 @@ Obtains whether an application supports distributed notifications based on the b **Example** ```javascript -function isDistributedEnabledByBundleCallback(data) { +function isDistributedEnabledByBundleCallback(err, data) { if (err.code) { console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); } else { - console.info("isDistributedEnabledByBundle success"); + console.info("isDistributedEnabledByBundle success" + JSON.stringify(data)); } }; @@ -2838,7 +2820,7 @@ Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCa isDistributedEnabledByBundle(bundle: BundleOption): Promise\ -Obtains whether an application supports distributed notifications based on the bundle. This API uses a promise to return the result. +Checks whether a specified application supports distributed notifications. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -2854,9 +2836,9 @@ Obtains whether an application supports distributed notifications based on the b **Return value** -| Type | Description | -| ------------------ | --------------- | -| Promise\ | Promise used to return the result.
**true**: The device supports distributed notifications.
**false**: The device does not support distributed notifications.| +| Type | Description | +| ------------------ | ------------------------------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -2865,10 +2847,9 @@ var bundle = { bundle: "bundleName1", } -Notification.isDistributedEnabledByBundle(bundle) - .then((data) => { - console.info("isDistributedEnabledByBundle sucess, data: " + JSON.stringify(data)); - }); +Notification.isDistributedEnabledByBundle(bundle).then((data) => { + console.info("isDistributedEnabledByBundle success, data: " + JSON.stringify(data)); +}); ``` @@ -2893,7 +2874,7 @@ Obtains the notification reminder type. This API uses an asynchronous callback t **Example** ```javascript -function getDeviceRemindTypeCallback(data) { +function getDeviceRemindTypeCallback(err,data) { if (err.code) { console.info("getDeviceRemindType failed " + JSON.stringify(err)); } else { @@ -2927,10 +2908,9 @@ Obtains the notification reminder type. This API uses a promise to return the re **Example** ```javascript -Notification.getDeviceRemindType() - .then((data) => { - console.info("getDeviceRemindType sucess, data: " + JSON.stringify(data)); - }); +Notification.getDeviceRemindType().then((data) => { + console.info("getDeviceRemindType success, data: " + JSON.stringify(data)); +}); ``` @@ -2948,18 +2928,18 @@ Publishes an agent-powered notification. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| -| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | -| userId | number | Yes | ID of the user who receives the notification. | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------- | ---- | ---------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | +| userId | number | Yes | User ID. | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** ```js -// Callback for publishAsBundle -function publishAsBundleCallback(err) { +// publishAsBundle callback +function callback(err) { if (err.code) { console.info("publishAsBundle failed " + JSON.stringify(err)); } else { @@ -2968,10 +2948,10 @@ function publishAsBundleCallback(err) { } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" -// ID of the user who receives the notification +// User ID let userId = 100 // NotificationRequest object -let notificationRequest = { +let request = { id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -2983,7 +2963,7 @@ let notificationRequest = { } } -Notification.publishAsBundle(notificationRequest, representativeBundle, userId, publishAsBundleCallback); +Notification.publishAsBundle(request, representativeBundle, userId, callback); ``` ## Notification.publishAsBundle9+ @@ -3003,19 +2983,19 @@ Publishes a notification through the reminder agent. This API uses a promise to | Name | Type | Mandatory| Description | | -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | -| request | [NotificationRequest](#notificationrequest) | Yes | **NotificationRequest** object.| +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| | representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | -| userId | number | Yes | ID of the user who receives the notification. | +| userId | number | Yes | User ID. | **Example** ```js // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" -// ID of the user who receives the notification +// User ID let userId = 100 // NotificationRequest object -var notificationRequest = { +var request = { id: 1, content: { contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, @@ -3027,8 +3007,8 @@ var notificationRequest = { } } -Notification.publishAsBundle(notificationRequest, representativeBundle, userId).then(() => { - console.info("publishAsBundle sucess"); +Notification.publishAsBundle(request, representativeBundle, userId).then(() => { + console.info("publishAsBundle success"); }); ``` @@ -3052,13 +3032,13 @@ Cancels a notification published by the reminder agent. This API uses an asynchr | -------------------- | ------------- | ---- | ------------------------ | | id | number | Yes | Notification ID. | | representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | -| userId | number | Yes | ID of the user who receives the notification. | +| userId | number | Yes | User ID. | | callback | AsyncCallback | Yes | Callback used to return the result.| **Example** ```js -//cancelAsBundle +// cancelAsBundle function cancelAsBundleCallback(err) { if (err.code) { console.info("cancelAsBundle failed " + JSON.stringify(err)); @@ -3068,7 +3048,7 @@ function cancelAsBundleCallback(err) { } // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" -// ID of the user who receives the notification +// User ID let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); @@ -3078,7 +3058,7 @@ Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallb cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise\ -Publishes a notification through the reminder agent. This API uses a promise to return the result. +Cancels a notification published by the reminder agent. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3094,14 +3074,14 @@ Publishes a notification through the reminder agent. This API uses a promise to | -------------------- | ------ | ---- | ------------------ | | id | number | Yes | Notification ID. | | representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent.| -| userId | number | Yes | ID of the user who receives the notification.| +| userId | number | Yes | User ID.| **Example** ```js // Bundle name of the application whose notification function is taken over by the reminder agent let representativeBundle = "com.example.demo" -// ID of the user who receives the notification +// User ID let userId = 100 Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { @@ -3113,7 +3093,7 @@ Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback\): void -Sets the enabled status for a notification slot of a specified type. This API uses an asynchronous callback to return the result. +Sets the enabled status of a notification slot type for a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3125,7 +3105,7 @@ Sets the enabled status for a notification slot of a specified type. This API us | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type. | | enable | boolean | Yes | Whether to enable notification. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| @@ -3133,7 +3113,7 @@ Sets the enabled status for a notification slot of a specified type. This API us **Example** ```js -//enableNotificationSlot +// enableNotificationSlot function enableSlotCallback(err) { if (err.code) { console.info("enableNotificationSlot failed " + JSON.stringify(err)); @@ -3153,7 +3133,7 @@ Notification.enableNotificationSlot( enableNotificationSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise\ -Sets the enabled status for a notification slot of a specified type. This API uses a promise to return the result. +Sets the enabled status of a notification slot type for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3165,27 +3145,25 @@ Sets the enabled status for a notification slot of a specified type. This API us | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type.| | enable | boolean | Yes | Whether to enable notification. | **Example** ```js -//enableNotificationSlot -Notification.enableNotificationSlot( - { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION, - true).then(() => { - console.info("enableNotificationSlot sucess"); - }); +// enableNotificationSlot +Notification.enableNotificationSlot({ bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION,true).then(() => { + console.info("enableNotificationSlot success"); +}); ``` ## Notification.isNotificationSlotEnabled 9+ isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback\): void -Obtains the enabled status of the notification slot of a specified type. This API uses an asynchronous callback to return the result. +Checks whether a specified notification slot type is enabled for a specified application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3197,14 +3175,14 @@ Obtains the enabled status of the notification slot of a specified type. This AP | Name | Type | Mandatory| Description | | -------- | ----------------------------- | ---- | ---------------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js -//isNotificationSlotEnabled +// isNotificationSlotEnabled function getEnableSlotCallback(err, data) { if (err.code) { console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); @@ -3223,7 +3201,7 @@ Notification.isNotificationSlotEnabled( isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ -Obtains the enabled status of the notification slot of a specified type. This API uses a promise to return the result. +Checks whether a specified notification slot type is enabled for a specified application. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3235,25 +3213,23 @@ Obtains the enabled status of the notification slot of a specified type. This AP | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | -| bundle | [BundleOption](#bundleoption) | Yes | Bundle information. | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | | type | [SlotType](#slottype) | Yes | Notification slot type.| **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the enabled status of the notification slot of the specified type.| +| Type | Description | +| ------------------ | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** ```js -//isNotificationSlotEnabled -Notification.isNotificationSlotEnabled( - { bundle: "ohos.samples.notification", }, - Notification.SlotType.SOCIAL_COMMUNICATION - ).then((data) => { - console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); - }); +// isNotificationSlotEnabled +Notification.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION).then((data) => { + console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); +}); ``` @@ -3261,7 +3237,7 @@ Notification.isNotificationSlotEnabled( setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: AsyncCallback\): void -Sets whether to sync notifications to devices where the application is not installed. This API uses an asynchronous callback to return the result. +Sets whether to enable the notification sync feature for devices where the application is not installed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3274,7 +3250,7 @@ Sets whether to sync notifications to devices where the application is not insta | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | | userId | number | Yes | User ID. | -| enable | boolean | Yes | Whether the feature is enabled.
**true**: enabled
**false**: disabled | +| enable | boolean | Yes | Whether the feature is enabled. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** @@ -3283,7 +3259,7 @@ Sets whether to sync notifications to devices where the application is not insta let userId = 100; let enable = true; -function setSyncNotificationEnabledWithoutAppCallback(err) { +function callback(err) { if (err.code) { console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); } else { @@ -3291,7 +3267,7 @@ function setSyncNotificationEnabledWithoutAppCallback(err) { } } -Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotificationEnabledWithoutAppCallback); +Notification.setSyncNotificationEnabledWithoutApp(userId, enable, callback); ``` @@ -3299,7 +3275,7 @@ Notification.setSyncNotificationEnabledWithoutApp(userId, enable, setSyncNotific setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\ -Sets whether to sync notifications to devices where the application is not installed. This API uses a promise to return the result. +Sets whether to enable the notification sync feature for devices where the application is not installed. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3312,7 +3288,7 @@ Sets whether to sync notifications to devices where the application is not insta | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | | userId | number | Yes | User ID. | -| enable | boolean | Yes | Whether the feature is enabled.
**true**: enabled
**false**: disabled | +| enable | boolean | Yes | Whether the feature is enabled. | **Return value** @@ -3326,13 +3302,11 @@ Sets whether to sync notifications to devices where the application is not insta let userId = 100; let enable = true; -Notification.setSyncNotificationEnabledWithoutApp(userId, enable) - .then(() => { - console.info('setSyncNotificationEnabledWithoutApp'); - }) - .catch((err) => { - console.info('setSyncNotificationEnabledWithoutApp, err:', err); - }); +Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { + console.info('setSyncNotificationEnabledWithoutApp success'); +}).catch((err) => { + console.info('setSyncNotificationEnabledWithoutApp, err:' + JSON.stringify(err)); +}); ``` @@ -3340,7 +3314,7 @@ Notification.setSyncNotificationEnabledWithoutApp(userId, enable) getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void -Obtains whether notifications are synced to devices where the application is not installed. This API uses an asynchronous callback to return the result. +Obtains whether the notification sync feature is enabled for devices where the application is not installed. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3353,18 +3327,18 @@ Obtains whether notifications are synced to devices where the application is not | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | -------------- | | userId | number | Yes | User ID. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: Notifications are synced to devices where the application is not installed.
**false**: Notifications are not synced to devices where the application is not installed.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js let userId = 100; -function getSyncNotificationEnabledWithoutAppCallback(data, err) { +function getSyncNotificationEnabledWithoutAppCallback(err, data) { if (err) { - console.info('getSyncNotificationEnabledWithoutAppCallback, err' + err); + console.info('getSyncNotificationEnabledWithoutAppCallback, err:' + err); } else { - console.info('getSyncNotificationEnabledWithoutAppCallback, data' + data); + console.info('getSyncNotificationEnabledWithoutAppCallback, data:' + data); } } @@ -3376,7 +3350,7 @@ Notification.getSyncNotificationEnabledWithoutApp(userId, getSyncNotificationEna getSyncNotificationEnabledWithoutApp(userId: number): Promise\ -Obtains whether notifications are synced to devices where the application is not installed. This API uses a promise to return the result. +Obtains whether the notification sync feature is enabled for devices where the application is not installed. This API uses a promise to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3392,28 +3366,27 @@ Obtains whether notifications are synced to devices where the application is not **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
**true**: Notifications are synced to devices where the application is not installed.
**false**: Notifications are not synced to devices where the application is not installed.| +| Type | Description | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| **Example** ```js let userId = 100; - -Notification.getSyncNotificationEnabledWithoutApp(userId) - .then((data) => { - console.info('getSyncNotificationEnabledWithoutApp, data:', data); - }) - .catch((err) => { - console.info('getSyncNotificationEnabledWithoutApp, err:', err); - }); +Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { + console.info('getSyncNotificationEnabledWithoutApp, data:' + data); +}).catch((err) => { + console.info('getSyncNotificationEnabledWithoutApp, err:' + err); +}); ``` ## NotificationSubscriber +Provides callbacks for receiving or removing notifications and serves as the input parameter of [subscribe](#notificationsubscribe). + **System API**: This is a system API and cannot be called by third-party applications. ### onConsume @@ -3430,7 +3403,7 @@ Callback for receiving notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification received.| **Example** @@ -3444,18 +3417,8 @@ function subscribeCallback(err) { }; function onConsumeCallback(data) { - console.info('===> onConsume in test'); let req = data.request; console.info('===> onConsume callback req.id:' + req.id); - let wantAgent = data.wantAgent; - wantAgent .getWant(wantAgent) - .then((data1) => { - console.info('===> getWant success want:' + JSON.stringify(data1)); - }) - .catch((err) => { - console.error('===> getWant failed because' + JSON.stringify(err)); - }); - console.info('===> onConsume callback req.wantAgent:' + JSON.stringify(req.wantAgent)); }; var subscriber = { @@ -3469,7 +3432,7 @@ Notification.subscribe(subscriber, subscribeCallback); onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void -Callback for removing notifications. +Callback for canceling notifications. **System capability**: SystemCapability.Notification.Notification @@ -3479,7 +3442,7 @@ Callback for removing notifications. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | AsyncCallback\<[SubscribeCallbackData](#subscribecallbackdata)\> | Yes| Notification information returned.| +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification to cancel.| **Example** @@ -3493,7 +3456,6 @@ function subscribeCallback(err) { }; function onCancelCallback(data) { - console.info('===> onCancel in test'); let req = data.request; console.info('===> onCancel callback req.id:' + req.id); } @@ -3519,7 +3481,7 @@ Callback for notification sorting updates. | Name| Type| Mandatory| Description| | ------------ | ------------------------ | ---- | -------------------------- | -| data | [NotificationSortingMap](#notificationsortingmap) | Yes| Notification information returned.| +| data | [NotificationSortingMap](#notificationsortingmap) | Yes| Latest notification sorting list.| **Example** @@ -3532,8 +3494,8 @@ function subscribeCallback(err) { } }; -function onUpdateCallback() { - console.info('===> onUpdate in test'); +function onUpdateCallback(map) { + console.info('===> onUpdateCallback map:' + JSON.stringify(map)); } var subscriber = { @@ -3595,16 +3557,30 @@ function subscribeCallback(err) { console.info("subscribeCallback"); } }; +function unsubscribeCallback(err) { + if (err.code) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribeCallback"); + } +}; +function onConnectCallback() { + console.info('===> onConnect in test'); +} function onDisconnectCallback() { console.info('===> onDisconnect in test'); } var subscriber = { + onConnect: onConnectCallback, onDisconnect: onDisconnectCallback }; +// The onConnect callback is invoked when subscription to the notification is complete. Notification.subscribe(subscriber, subscribeCallback); +// The onDisconnect callback is invoked when unsubscription to the notification is complete. +Notification.unsubscribe(subscriber, unsubscribeCallback); ``` ### onDestroy @@ -3665,15 +3641,24 @@ function subscribeCallback(err) { } }; -function onDoNotDisturbDateChangeCallback() { - console.info('===> onDoNotDisturbDateChange in test'); +function onDoNotDisturbDateChangeCallback(mode) { + console.info('===> onDoNotDisturbDateChange:' + mode); } var subscriber = { onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback }; - Notification.subscribe(subscriber, subscribeCallback); + +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} +// Set the onDoNotDisturbDateChange callback for DND time setting updates. +Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { + console.info("setDoNotDisturbDate sucess"); +}); ``` @@ -3681,7 +3666,7 @@ Notification.subscribe(subscriber, subscribeCallback); onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata8)) => void -Listens for the notification enable status changes. This API uses an asynchronous callback to return the result. +Listens for the notification enabled status changes. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Notification.Notification @@ -3705,16 +3690,23 @@ function subscribeCallback(err) { }; function onEnabledNotificationChangedCallback(callbackData) { - console.info("bundle: ", callbackData.bundle); - console.info("uid: ", callbackData.uid); - console.info("enable: ", callbackData.enable); + console.info("bundle: " + callbackData.bundle); + console.info("uid: " + callbackData.uid); + console.info("enable: " + callbackData.enable); }; var subscriber = { onEnabledNotificationChanged: onEnabledNotificationChangedCallback }; - Notification.subscribe(subscriber, subscribeCallback); + +var bundle = { + bundle: "bundleName1", +} +// Set the onEnabledNotificationChanged callback that is triggered when the notification enabled status changes. +Notification.enableNotification(bundle, false).then(() => { + console.info("enableNotification sucess"); +}); ``` ## SubscribeCallbackData @@ -3723,13 +3715,13 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| --------------- | ---- | --- | ------------------------------------------------- | -------- | -| request | Yes | No | [NotificationRequest](#notificationrequest) | Notification content.| -| sortingMap | Yes | No | [NotificationSortingMap](#notificationsortingmap) | Notification sorting information.| -| reason | Yes | No | number | Reason for deletion.| -| sound | Yes | No | string | Sound used for notification.| -| vibrationValues | Yes | No | Array\ | Vibration used for notification.| +| Name | Type | Readable| Writable| Description | +| --------------- | ------------------------------------------------- | ---- | --- | -------- | +| request | [NotificationRequest](#notificationrequest) | Yes | No | Notification content.| +| sortingMap | [NotificationSortingMap](#notificationsortingmap) | Yes | No | Notification sorting information.| +| reason | number | Yes | No | Reason for deletion.| +| sound | string | Yes | No | Sound used for notification.| +| vibrationValues | Array\ | Yes | No | Vibration used for notification.| ## EnabledNotificationCallbackData8+ @@ -3738,11 +3730,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ------ | ---- | --- | ------- | ---------------- | -| bundle | Yes | No | string | Bundle name of the application. | -| uid | Yes | No | number | UID of the application. | -| enable | Yes | No | boolean | Notification enabled status of the application.| +| Name | Type | Readable| Writable| Description | +| ------ | ------- | ---- | --- | ---------------- | +| bundle | string | Yes | No | Bundle name of the application. | +| uid | number | Yes | No | UID of the application. | +| enable | boolean | Yes | No | Notification enabled status of the application.| ## DoNotDisturbDate8+ @@ -3751,13 +3743,11 @@ Notification.subscribe(subscriber, subscribeCallback); **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ----- | ---- | --- | ------------------------------------- | ------------------------ | -| type | Yes | No | [DoNotDisturbType](#donotdisturbtype8) | DND time type.| -| begin | Yes | No | Date | DND start time.| -| end | Yes | No | Date | DND end time.| - - +| Name | Type | Readable| Writable| Description | +| ----- | -------------------------------------- | ---- | ---- | ---------------------- | +| type | [DoNotDisturbType](#donotdisturbtype8) | Yes | Yes | DND time type.| +| begin | Date | Yes | Yes | DND start time.| +| end | Date | Yes | Yes | DND end time.| ## DoNotDisturbType8+ @@ -3802,10 +3792,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ------ | ---- | --- | ------ | ------ | -| bundle | Yes | Yes | string | Bundle name. | -| uid | Yes | Yes | number | User ID.| +| Name | Type | Readable| Writable| Description | +| ------ | ------ |---- | --- | ------ | +| bundle | string | Yes | Yes | Bundle information of the application.| +| uid | number | Yes | Yes | User ID.| @@ -3813,10 +3803,10 @@ Notification.subscribe(subscriber, subscribeCallback); **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ----- | ---- | --- | ------ | -------- | -| id | Yes | Yes | number | Notification ID. | -| label | Yes | Yes | string | Notification label.| +| Name | Type | Readable| Writable| Description | +| ----- | ------ | ---- | --- | -------- | +| id | number | Yes | Yes | Notification ID. | +| label | string | Yes | Yes | Notification label.| ## SlotType @@ -3834,84 +3824,98 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationActionButton +Describes the button displayed in the notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| --------- | --- | ---- | ----------------------------------------------- | ------------------------- | -| title | Yes | Yes | string | Button title. | -| wantAgent | Yes | Yes | WantAgent | **WantAgent** of the button.| -| extras | Yes | Yes | { [key: string]: any } | Extra information of the button. | -| userInput8+ | Yes | Yes | [NotificationUserInput](#notificationuserinput8) | User input object. | +| Name | Type | Readable| Writable| Description | +| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | +| title | string | Yes | Yes | Button title. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** of the button.| +| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | +| userInput8+ | [NotificationUserInput](#notificationuserinput8) | Yes | Yes | User input object. | ## NotificationBasicContent +Describes the normal text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | ---- | ------ | ---------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | ---------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| ## NotificationLongTextContent +Describes the long text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | ------ | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| longText | Yes | Yes | string | Long text of the notification. | -| briefText | Yes | Yes | string | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| longText | string | Yes | Yes | Long text of the notification. | +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | ## NotificationMultiLineContent +Describes the multi-line text notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | --- | --- | --------------- | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| briefText | Yes | Yes | string | Brief text of the notification.| -| longTitle | Yes | Yes | string | Title of the notification in the expanded state. | -| lines | Yes | Yes | Array\ | Multi-line text of the notification. | +| Name | Type | Readable| Writable| Description | +| -------------- | --------------- | --- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| lines | Array\ | Yes | Yes | Multi-line text of the notification. | ## NotificationPictureContent +Describes the picture-attached notification. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | -------------- | -------------------------------- | -| title | Yes | Yes | string | Notification title. | -| text | Yes | Yes | string | Notification content. | -| additionalText | Yes | Yes | string | Additional information of the notification.| -| briefText | Yes | Yes | string | Brief text of the notification.| -| expandedTitle | Yes | Yes | string | Title of the notification in the expanded state. | -| picture | Yes | Yes | image.PixelMap | Picture attached to the notification. | +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Picture attached to the notification. | ## NotificationContent +Describes the notification content. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ----------- | ---- | --- | ------------------------------------------------------------ | ------------------ | -| contentType | Yes | Yes | [ContentType](#contenttype) | Notification content type. | -| normal | Yes | Yes | [NotificationBasicContent](#notificationbasiccontent) | Normal text. | -| longText | Yes | Yes | [NotificationLongTextContent](#notificationlongtextcontent) | Long text.| -| multiLine | Yes | Yes | [NotificationMultiLineContent](#notificationmultilinecontent) | Multi-line text. | -| picture | Yes | Yes | [NotificationPictureContent](#notificationpicturecontent) | Picture-attached. | +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | +| contentType | [ContentType](#contenttype) | Yes | Yes | Notification content type. | +| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | +| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | ## NotificationFlagStatus8+ +Describes the notification flag status. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. @@ -3925,133 +3929,148 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationFlags8+ +Enumerates notification flags. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ---------------- | ---- | ---- | ---------------------- | --------------------------------- | -| soundEnabled | Yes | No | NotificationFlagStatus | Whether to enable the sound alert for the notification. | -| vibrationEnabled | Yes | No | NotificationFlagStatus | Whether to enable vibration for the notification. | +| Name | Type | Readable| Writable| Description | +| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | +| soundEnabled | [NotificationFlagStatus](#notificationflagstatus8) | Yes | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus8) | Yes | No | Whether to enable vibration for the notification. | ## NotificationRequest -**System capability**: SystemCapability.Notification.Notification - -| Name | Readable| Writable| Type | Description | -| --------------------- | ---- | --- | --------------------------------------------- | -------------------------- | -| content | Yes | Yes | [NotificationContent](#notificationcontent) | Notification content. | -| id | Yes | Yes | number | Notification ID. | -| slotType | Yes | Yes | [SlotType](#slottype) | Slot type. | -| isOngoing | Yes | Yes | boolean | Whether the notification is an ongoing notification. | -| isUnremovable | Yes | Yes | boolean | Whether the notification can be removed. | -| deliveryTime | Yes | Yes | number | Time when the notification is sent. | -| tapDismissed | Yes | Yes | boolean | Whether the notification is automatically cleared. | -| autoDeletedTime | Yes | Yes | number | Time when the notification is automatically cleared. | -| wantAgent | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected after being clicked. | -| extraInfo | Yes | Yes | {[key: string]: any} | Extended parameters. | -| color | Yes | Yes | number | Background color of the notification. | -| colorEnabled | Yes | Yes | boolean | Whether the notification background color is enabled. | -| isAlertOnce | Yes | Yes | boolean | Whether the notification triggers an alert only once.| -| isStopwatch | Yes | Yes | boolean | Whether to display the stopwatch. | -| isCountDown | Yes | Yes | boolean | Whether to display the countdown time. | -| isFloatingIcon | Yes | Yes | boolean | Whether the notification is displayed as a floating icon. | -| label | Yes | Yes | string | Notification label. | -| badgeIconStyle | Yes | Yes | number | Notification badge type. | -| showDeliveryTime | Yes | Yes | boolean | Whether to display the time when the notification is delivered. | -| actionButtons | Yes | Yes | Array\<[NotificationActionButton](#notificationactionbutton)\> | Buttons in the notification. Up to two buttons are allowed. | -| smallIcon | Yes | Yes | PixelMap | Small notification icon. | -| largeIcon | Yes | Yes | PixelMap | Large notification icon. | -| creatorBundleName | Yes | No | string | Name of the bundle that creates the notification. | -| creatorUid | Yes | No | number | UID used for creating the notification. | -| creatorPid | Yes | No | number | PID used for creating the notification. | -| creatorUserId8+| Yes | No | number | ID of the user who creates the notification. | -| hashCode | Yes | No | string | Unique ID of the notification. | -| classification | Yes | Yes | string | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | -| groupName8+| Yes | Yes | string | Group notification name. | -| template8+ | Yes | Yes | [NotificationTemplate](#notificationtemplate8) | Notification template. | -| isRemoveAllowed8+ | Yes | No | boolean | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | -| source8+ | Yes | No | number | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| distributedOption8+ | Yes | Yes | [DistributedOptions](#distributedoptions8) | Option of distributed notification. | -| deviceId8+ | Yes | No | string | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | -| notificationFlags8+ | Yes | No | [NotificationFlags](#notificationflags8) | Notification flags. | -| removalWantAgent9+ | Yes | Yes | WantAgent | **WantAgent** instance to which the notification will be redirected when it is removed. | -| badgeNumber9+ | Yes | Yes | number | Number of notifications displayed on the application icon. | - +Describes the notification request. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | +| content | [NotificationContent](#notificationcontent) | Yes | Yes | Notification content. | +| id | number | Yes | Yes | Notification ID. | +| slotType | [SlotType](#slottype) | Yes | Yes | Slot type. | +| isOngoing | boolean | Yes | Yes | Whether the notification is an ongoing notification. | +| isUnremovable | boolean | Yes | Yes | Whether the notification can be removed. | +| deliveryTime | number | Yes | Yes | Time when the notification is sent. | +| tapDismissed | boolean | Yes | Yes | Whether the notification is automatically cleared. | +| autoDeletedTime | number | Yes | Yes | Time when the notification is automatically cleared. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected after being clicked. | +| extraInfo | {[key: string]: any} | Yes | Yes | Extended parameters. | +| color | number | Yes | Yes | Background color of the notification. Not supported currently.| +| colorEnabled | boolean | Yes | Yes | Whether the notification background color is enabled. Not supported currently.| +| isAlertOnce | boolean | Yes | Yes | Whether the notification triggers an alert only once.| +| isStopwatch | boolean | Yes | Yes | Whether to display the stopwatch. | +| isCountDown | boolean | Yes | Yes | Whether to display the countdown time. | +| isFloatingIcon | boolean | Yes | Yes | Whether the notification is displayed as a floating icon in the status bar. | +| label | string | Yes | Yes | Notification label. | +| badgeIconStyle | number | Yes | Yes | Notification badge type. | +| showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | +| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | Yes | Yes | Buttons in the notification. Up to two buttons are allowed. | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | +| creatorUid | number | Yes | No | UID used for creating the notification. | +| creatorPid | number | Yes | No | PID used for creating the notification. | +| creatorUserId8+| number | Yes | No | ID of the user who creates the notification. | +| hashCode | string | Yes | No | Unique ID of the notification. | +| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName8+| string | Yes | Yes | Notification group name. | +| template8+ | [NotificationTemplate](#notificationtemplate8) | Yes | Yes | Notification template. | +| isRemoveAllowed8+ | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| source8+ | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| distributedOption8+ | [DistributedOptions](#distributedoptions8) | Yes | Yes | Distributed notification options. | +| deviceId8+ | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| notificationFlags8+ | [NotificationFlags](#notificationflags8) | Yes | No | Notification flags. | +| removalWantAgent9+ | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber9+ | number | Yes | Yes | Number of notifications displayed on the application icon. | ## DistributedOptions8+ +Describes distributed notifications options. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| ---------------------- | ---- | ---- | -------------- | ---------------------------------- | -| isDistributed | Yes | Yes | boolean | Whether the notification is a distributed notification. | -| supportDisplayDevices | Yes | Yes | Array\ | Types of the devices to which the notification can be synchronized. | -| supportOperateDevices | Yes | Yes | Array\ | Devices on which notification can be enabled. | -| remindType | Yes | No | number | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | +| Name | Type | Readable| Writable| Description | +| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | +| isDistributed | boolean | Yes | Yes | Whether the notification is a distributed notification. | +| supportDisplayDevices | Array\ | Yes | Yes | List of the devices to which the notification can be synchronized. | +| supportOperateDevices | Array\ | Yes | Yes | List of the devices on which the notification can be opened. | +| remindType | number | Yes | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | ## NotificationSlot +Describes the notification slot. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------------------- | ---- | --- | --------------------- | ------------------------------------------ | -| type | Yes | Yes | [SlotType](#slottype) | Slot type. | -| level | Yes | Yes | number | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| -| desc | Yes | Yes | string | Notification slot description. | -| badgeFlag | Yes | Yes | boolean | Whether to display the badge. | -| bypassDnd | Yes | Yes | boolean | Whether to bypass the DND mode in the system. | -| lockscreenVisibility | Yes | Yes | number | Mode for displaying the notification on the lock screen. | -| vibrationEnabled | Yes | Yes | boolean | Whether vibration is supported for the notification. | -| sound | Yes | Yes | string | Notification alert tone. | -| lightEnabled | Yes | Yes | boolean | Whether the indicator blinks for the notification. | -| lightColor | Yes | Yes | number | Indicator color of the notification. | -| vibrationValues | Yes | Yes | Array\ | Vibration mode of the notification. | -| enabled9+ | Yes | No | boolean | Enabled status of the notification slot. | +| Name | Type | Readable| Writable| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| type | [SlotType](#slottype) | Yes | Yes | Slot type. | +| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | string | Yes | Yes | Notification slot description. | +| badgeFlag | boolean | Yes | Yes | Whether to display the badge. | +| bypassDnd | boolean | Yes | Yes | Whether to bypass DND mode in the system. | +| lockscreenVisibility | number | Yes | Yes | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | boolean | Yes | Yes | Whether vibration is enabled for the notification. | +| sound | string | Yes | Yes | Notification alert tone. | +| lightEnabled | boolean | Yes | Yes | Whether the indicator blinks for the notification. | +| lightColor | number | Yes | Yes | Indicator color of the notification. | +| vibrationValues | Array\ | Yes | Yes | Vibration mode of the notification. | +| enabled9+ | boolean | Yes | No | Whether the notification slot is enabled. | ## NotificationSorting +Provides sorting information of active notifications. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| -------- | ---- | --- | ------------------------------------- | ------------ | -| slot | Yes | No | [NotificationSlot](#notificationslot) | Notification slot content.| -| hashCode | Yes | No | string | Unique ID of the notification.| -| ranking | Yes | No | number | Notification sequence number.| +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------- | ---- | --- | ------------ | +| slot | [NotificationSlot](#notificationslot) | Yes | No | Notification slot content.| +| hashCode | string | Yes | No | Unique ID of the notification.| +| ranking | number | Yes | No | Notification sequence number.| ## NotificationSortingMap +Provides sorting information of active notifications in all subscribed notifications. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| -------------- | ---- | --- | ------------------------------------------------------------ | ---------------- | -| sortings | Yes | No | {[key: string]: [NotificationSorting](#notificationsorting)} | Array of notification sorting information.| -| sortedHashCode | Yes | No | Array\ | Array of unique notification IDs.| +| Name | Type | Readable| Writable| Description | +| -------------- | ------------------------------------------------------------ | ---- | --- | ---------------- | +| sortings | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | No | Array of notification sorting information.| +| sortedHashCode | Array\ | Yes | No | Array of unique notification IDs.| ## NotificationSubscribeInfo +Provides the information about the publisher for notification subscription. + **System capability**: SystemCapability.Notification.Notification **System API**: This is a system API and cannot be called by third-party applications. -| Name | Readable| Writable| Type | Description | -| ----------- | --- | ---- | --------------- | ------------------------------- | -| bundleNames | Yes | Yes | Array\ | Bundle names of the applications whose notifications are to be subscribed to.| -| userId | Yes | Yes | number | User whose notifications are to be subscribed to. | +| Name | Type | Readable| Writable| Description | +| ----------- | --------------- | --- | ---- | ------------------------------- | +| bundleNames | Array\ | Yes | Yes | Bundle names of the applications whose notifications are to be subscribed to.| +| userId | number | Yes | Yes | User whose notifications are to be subscribed to. | ## NotificationTemplate8+ +Describes the notification template. + **System capability**: SystemCapability.Notification.Notification -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ---------------------- | ---- | ---- | ---------- | | name | string | Yes | Yes | Template name.| | data | {[key:string]: Object} | Yes | Yes | Template data.| @@ -4059,11 +4078,13 @@ Notification.subscribe(subscriber, subscribeCallback); ## NotificationUserInput8+ +Provides the notification user input. + **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Description | -| -------- | --- | ---- | ------ | ----------------------------- | -| inputKey | Yes | Yes | string | Key to identify the user input.| +| Name | Type | Readable| Writable| Description | +| -------- | ------ | --- | ---- | ----------------------------- | +| inputKey | string | Yes | Yes | Key to identify the user input.| ## DeviceRemindType8+ @@ -4100,5 +4121,5 @@ Notification.subscribe(subscriber, subscribeCallback); | Name | Value | Description | | -------------------- | --- | -------------------- | -| CLICK_REASON_REMOVE | 1 | The notification is removed due to a click on it. | +| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | | CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-notificationManager.md b/en/application-dev/reference/apis/js-apis-notificationManager.md new file mode 100644 index 0000000000000000000000000000000000000000..2d8f497bede97cc9c6d1a8d408b6e80770a2396f --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-notificationManager.md @@ -0,0 +1,3968 @@ +# @ohos.notificationManager + +The **notificationManager** module provides notification management capabilities, covering notifications, notification slots, notification enabled status, and notification badge status. + +> **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 Notification from '@ohos.notificationManager'; +``` + +## Notification.publish + +publish(request: NotificationRequest, callback: AsyncCallback\): void + +Publishes a notification. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600004 | Notification is not enabled. | +| 1600005 | Notification slot is not enabled. | +| 1600009 | Over max number notifications per second. | + +**Example** + +```js +// publish callback +function publishCallback(err) { + if (err) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } +} +// NotificationRequest object +var notificationRequest = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} +Notification.publish(notificationRequest, publishCallback) +``` + + + +## Notification.publish + +publish(request: NotificationRequest): Promise\ + +Publishes a notification. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600004 | Notification is not enabled. | +| 1600005 | Notification slot is not enabled. | +| 1600009 | Over max number notifications per second. | + +**Example** + +```js +// NotificationRequest object +var notificationRequest = { + notificationId: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} +Notification.publish(notificationRequest).then(() => { + console.info("publish success"); +}); + +``` + +## Notification.publish + +publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void + +Publishes a notification to a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| userId | number | Yes | User ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600004 | Notification is not enabled. | +| 1600005 | Notification slot is not enabled. | +| 1600008 | The user is not exist. | +| 1600009 | Over max number notifications per second. | + +**Example** + +```js +// publish callback +function publishCallback(err) { + if (err) { + console.info("publish failed " + JSON.stringify(err)); + } else { + console.info("publish success"); + } +} +// User ID +var userId = 1 +// NotificationRequest object +var notificationRequest = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} +Notification.publish(notificationRequest, userId, publishCallback); +``` + +## Notification.publish + +publish(request: NotificationRequest, userId: number): Promise\ + +Publishes a notification to a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| userId | number | Yes | User ID. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600004 | Notification is not enabled. | +| 1600005 | Notification slot is not enabled. | +| 1600008 | The user is not exist. | +| 1600009 | Over max number notifications per second. | + +**Example** + +```js +var notificationRequest = { + notificationId: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +var userId = 1 + +Notification.publish(notificationRequest, userId).then(() => { + console.info("publish success"); +}); +``` + + +## Notification.cancel + +cancel(id: number, label: string, callback: AsyncCallback\): void + +Cancels a notification with the specified ID and label. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| id | number | Yes | Notification ID. | +| label | string | Yes | Notification label. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | + +**Example** + +```js +// cancel callback +function cancelCallback(err) { + if (err) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } +} +Notification.cancel(0, "label", cancelCallback) +``` + + + +## Notification.cancel + +cancel(id: number, label?: string): Promise\ + +Cancels a notification with the specified ID and optional label. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | -------- | +| id | number | Yes | Notification ID. | +| label | string | No | Notification label.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | + +**Example** + +```js +Notification.cancel(0).then(() => { + console.info("cancel success"); +}); +``` + + + +## Notification.cancel + +cancel(id: number, callback: AsyncCallback\): void + +Cancels a notification with the specified ID. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| id | number | Yes | Notification ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | + +**Example** + +```js +// cancel callback +function cancelCallback(err) { + if (err) { + console.info("cancel failed " + JSON.stringify(err)); + } else { + console.info("cancel success"); + } +} +Notification.cancel(0, cancelCallback) +``` + + + +## Notification.cancelAll + +cancelAll(callback: AsyncCallback\): void + +Cancels all notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +// cancel callback +function cancelAllCallback(err) { + if (err) { + console.info("cancelAll failed " + JSON.stringify(err)); + } else { + console.info("cancelAll success"); + } +} +Notification.cancelAll(cancelAllCallback) +``` + + + +## Notification.cancelAll + +cancelAll(): Promise\ + +Cancels all notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.cancelAll().then(() => { + console.info("cancelAll success"); +}); +``` + + + +## Notification.addSlot + +addSlot(slot: NotificationSlot, callback: AsyncCallback\): void + +Adds a notification slot. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// addSlot callback +function addSlotCallBack(err) { + if (err) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } +} +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.addSlot(notificationSlot, addSlotCallBack) +``` + + + +## Notification.addSlot + +addSlot(slot: NotificationSlot): Promise\ + +Adds a notification slot. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ---------------- | ---- | -------------------- | +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot to add.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.addSlot(notificationSlot).then(() => { + console.info("addSlot success"); +}); +``` + + + +## Notification.addSlot + +addSlot(type: SlotType, callback: AsyncCallback\): void + +Adds a notification slot of a specified type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------- | +| type | [SlotType](#slottype) | Yes | Type of the notification slot to add.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// addSlot callback +function addSlotCallBack(err) { + if (err) { + console.info("addSlot failed " + JSON.stringify(err)); + } else { + console.info("addSlot success"); + } +} +Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION, addSlotCallBack) +``` + + + +## Notification.addSlot + +addSlot(type: SlotType): Promise\ + +Adds a notification slot of a specified type. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | -------- | ---- | ---------------------- | +| type | [SlotType](#slottype) | Yes | Type of the notification slot to add.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.addSlot(Notification.SlotType.SOCIAL_COMMUNICATION).then(() => { + console.info("addSlot success"); +}); +``` + + + +## Notification.addSlots + +addSlots(slots: Array\, callback: AsyncCallback\): void + +Adds an array of notification slots. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------ | +| slots | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// addSlots callback +function addSlotsCallBack(err) { + if (err) { + console.info("addSlots failed " + JSON.stringify(err)); + } else { + console.info("addSlots success"); + } +} +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +// NotificationSlotArray object +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; + +Notification.addSlots(notificationSlotArray, addSlotsCallBack) +``` + + + +## Notification.addSlots + +addSlots(slots: Array\): Promise\ + +Adds an array of notification slots. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----- | ------------------------- | ---- | ------------------------ | +| slots | Array\<[NotificationSlot](#notificationslot)\> | Yes | Notification slots to add.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// NotificationSlot object +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +// NotificationSlotArray object +var notificationSlotArray = new Array(); +notificationSlotArray[0] = notificationSlot; + +Notification.addSlots(notificationSlotArray).then(() => { + console.info("addSlots success"); +}); +``` + + + +## Notification.getSlot + +getSlot(slotType: SlotType, callback: AsyncCallback\): void + +Obtains a notification slot of a specified type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// getSlot callback +function getSlotCallback(err,data) { + if (err) { + console.info("getSlot failed " + JSON.stringify(err)); + } else { + console.info("getSlot success"); + } +} +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.getSlot(slotType, getSlotCallback) +``` + + + +## Notification.getSlot + +getSlot(slotType: SlotType): Promise\ + +Obtains a notification slot of a specified type. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.getSlot(slotType).then((data) => { + console.info("getSlot success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.getSlots + +getSlots(callback: AsyncCallback>): void + +Obtains all notification slots of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | -------------------- | +| callback | AsyncCallback\\> | Yes | Callback used to return all notification slots of the current application.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// getSlots callback +function getSlotsCallback(err,data) { + if (err) { + console.info("getSlots failed " + JSON.stringify(err)); + } else { + console.info("getSlots success"); + } +} +Notification.getSlots(getSlotsCallback) +``` + + + +## Notification.getSlots + +getSlots(): Promise\> + +Obtains all notification slots of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return all notification slots of the current application.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.getSlots().then((data) => { + console.info("getSlots success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.removeSlot + +removeSlot(slotType: SlotType, callback: AsyncCallback\): void + +Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// removeSlot callback +function removeSlotCallback(err) { + if (err) { + console.info("removeSlot failed " + JSON.stringify(err)); + } else { + console.info("removeSlot success"); + } +} +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.removeSlot(slotType,removeSlotCallback) +``` + + + +## Notification.removeSlot + +removeSlot(slotType: SlotType): Promise\ + +Removes a notification slot of a specified type. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | ----------------------------------------------------------- | +| slotType | [SlotType](#slottype) | Yes | Type of the notification slot, which can be used for social communication, service information, content consultation, and other purposes.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +var slotType = Notification.SlotType.SOCIAL_COMMUNICATION; +Notification.removeSlot(slotType).then(() => { + console.info("removeSlot success"); +}); +``` + + + +## Notification.removeAllSlots + +removeAllSlots(callback: AsyncCallback\): void + +Removes all notification slots. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function removeAllCallBack(err) { + if (err) { + console.info("removeAllSlots failed " + JSON.stringify(err)); + } else { + console.info("removeAllSlots success"); + } +} +Notification.removeAllSlots(removeAllCallBack) +``` + + + +## Notification.removeAllSlots + +removeAllSlots(): Promise\ + +Removes all notification slots. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.removeAllSlots().then(() => { + console.info("removeAllSlots success"); +}); +``` + + + +## Notification.setNotificationEnable + +setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void + +Sets whether to enable notification for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| enable | boolean | Yes | Whether to enable notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function setNotificationEnablenCallback(err) { + if (err) { + console.info("setNotificationEnablenCallback failed " + JSON.stringify(err)); + } else { + console.info("setNotificationEnablenCallback success"); + } +} +var bundle = { + bundle: "bundleName1", +} +Notification.setNotificationEnable(bundle, false, setNotificationEnablenCallback); +``` + + + +## Notification.setNotificationEnable + +setNotificationEnable(bundle: BundleOption, enable: boolean): Promise\ + +Sets whether to enable notification for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| enable | boolean | Yes | Whether to enable notification. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +Notification.setNotificationEnable(bundle, false).then(() => { + console.info("setNotificationEnable success"); +}); +``` + + + +## Notification.isNotificationEnabled + +isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void + +Checks whether notification is enabled for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function isNotificationEnabledCallback(err, data) { + if (err) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } +} +var bundle = { + bundle: "bundleName1", +} +Notification.isNotificationEnabled(bundle, isNotificationEnabledCallback); +``` + + + +## Notification.isNotificationEnabled + +isNotificationEnabled(bundle: BundleOption): Promise\ + +Checks whether notification is enabled for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| + +**Return value** + +| Type | Description | +| ------------------ | --------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +Notification.isNotificationEnabled(bundle).then((data) => { + console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.isNotificationEnabled + +isNotificationEnabled(callback: AsyncCallback\): void + +Checks whether notification is enabled for this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function isNotificationEnabledCallback(err, data) { + if (err) { + console.info("isNotificationEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationEnabled success"); + } +} + +Notification.isNotificationEnabled(isNotificationEnabledCallback); +``` + + + +## Notification.isNotificationEnabled + +isNotificationEnabled(): Promise\ + +Checks whether notification is enabled for the current application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +Notification.isNotificationEnabled().then((data) => { + console.info("isNotificationEnabled success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.displayBadge + +displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void + +Sets whether to enable the notification badge for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| enable | boolean | Yes | Whether to enable notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function displayBadgeCallback(err) { + if (err) { + console.info("displayBadge failed " + JSON.stringify(err)); + } else { + console.info("displayBadge success"); + } +} +var bundle = { + bundle: "bundleName1", +} +Notification.displayBadge(bundle, false, displayBadgeCallback); +``` + + + +## Notification.displayBadge + +displayBadge(bundle: BundleOption, enable: boolean): Promise\ + +Sets whether to enable the notification badge for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| enable | boolean | Yes | Whether to enable notification. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +Notification.displayBadge(bundle, false).then(() => { + console.info("displayBadge success"); +}); +``` + + + +## Notification.isBadgeDisplayed + +isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback\): void + +Checks whether the notification badge is enabled for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function isBadgeDisplayedCallback(err, data) { + if (err) { + console.info("isBadgeDisplayed failed " + JSON.stringify(err)); + } else { + console.info("isBadgeDisplayed success"); + } +} +var bundle = { + bundle: "bundleName1", +} +Notification.isBadgeDisplayed(bundle, isBadgeDisplayedCallback); +``` + + + +## Notification.isBadgeDisplayed + +isBadgeDisplayed(bundle: BundleOption): Promise\ + +Checks whether the notification badge is enabled for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +Notification.isBadgeDisplayed(bundle).then((data) => { + console.info("isBadgeDisplayed success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.setSlotByBundle + +setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback\): void + +Sets the notification slot for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + + + +**Example** + +```js +function setSlotByBundleCallback(err) { + if (err) { + console.info("setSlotByBundle failed " + JSON.stringify(err)); + } else { + console.info("setSlotByBundle success"); + } +} +var bundle = { + bundle: "bundleName1", +} +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.setSlotByBundle(bundle, notificationSlot, setSlotByBundleCallback); +``` + + + +## Notification.setSlotByBundle + +setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise\ + +Sets the notification slot for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| +| slot | [NotificationSlot](#notificationslot) | Yes | Notification slot.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +var notificationSlot = { + type: Notification.SlotType.SOCIAL_COMMUNICATION +} +Notification.setSlotByBundle(bundle, notificationSlot).then(() => { + console.info("setSlotByBundle success"); +}); +``` + + + +## Notification.getSlotsByBundle + +getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void + +Obtains the notification slots of a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------------------- | ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| callback | AsyncCallback> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function getSlotsByBundleCallback(err, data) { + if (err) { + console.info("getSlotsByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotsByBundle success"); + } +} +var bundle = { + bundle: "bundleName1", +} +Notification.getSlotsByBundle(bundle, getSlotsByBundleCallback); +``` + + + +## Notification.getSlotsByBundle + +getSlotsByBundle(bundle: BundleOption): Promise> + +Obtains the notification slots of a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +Notification.getSlotsByBundle(bundle).then((data) => { + console.info("getSlotsByBundle success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.getSlotNumByBundle + +getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback\): void + +Obtains the number of notification slots of a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function getSlotNumByBundleCallback(err, data) { + if (err) { + console.info("getSlotNumByBundle failed " + JSON.stringify(err)); + } else { + console.info("getSlotNumByBundle success"); + } +} +var bundle = { + bundle: "bundleName1", +} +Notification.getSlotNumByBundle(bundle, getSlotNumByBundleCallback); +``` + + + +## Notification.getSlotNumByBundle + +getSlotNumByBundle(bundle: BundleOption): Promise\ + +Obtains the number of notification slots of a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle of the application.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +Notification.getSlotNumByBundle(bundle).then((data) => { + console.info("getSlotNumByBundle success, data: " + JSON.stringify(data)); +}); +``` + + + + +## Notification.getAllActiveNotifications + +getAllActiveNotifications(callback: AsyncCallback>): void + +Obtains all active notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | -------------------- | +| callback | AsyncCallback> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function getAllActiveNotificationsCallback(err, data) { + if (err) { + console.info("getAllActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getAllActiveNotifications success"); + } +} + +Notification.getAllActiveNotifications(getAllActiveNotificationsCallback); +``` + + + +## Notification.getAllActiveNotifications + +getAllActiveNotifications(): Promise\\> + +Obtains all active notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.getAllActiveNotifications().then((data) => { + console.info("getAllActiveNotifications success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.getActiveNotificationCount + +getActiveNotificationCount(callback: AsyncCallback\): void + +Obtains the number of active notifications of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function getActiveNotificationCountCallback(err, data) { + if (err) { + console.info("getActiveNotificationCount failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotificationCount success"); + } +} + +Notification.getActiveNotificationCount(getActiveNotificationCountCallback); +``` + + + +## Notification.getActiveNotificationCount + +getActiveNotificationCount(): Promise\ + +Obtains the number of active notifications of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.getActiveNotificationCount().then((data) => { + console.info("getActiveNotificationCount success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.getActiveNotifications + +getActiveNotifications(callback: AsyncCallback>): void + +Obtains active notifications of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------ | +| callback | AsyncCallback> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function getActiveNotificationsCallback(err, data) { + if (err) { + console.info("getActiveNotifications failed " + JSON.stringify(err)); + } else { + console.info("getActiveNotifications success"); + } +} + +Notification.getActiveNotifications(getActiveNotificationsCallback); +``` + + + +## Notification.getActiveNotifications + +getActiveNotifications(): Promise\\> + +Obtains active notifications of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | --------------------------------------- | +| Promise\\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.getActiveNotifications().then((data) => { + console.info("removeGroupByBundle success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.cancelGroup + +cancelGroup(groupName: string, callback: AsyncCallback\): void + +Cancels notifications under a notification group of this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------- | +| groupName | string | Yes | Name of the notification group, which is specified through [NotificationRequest](#notificationrequest) when the notification is published.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function cancelGroupCallback(err) { + if (err) { + console.info("cancelGroup failed " + JSON.stringify(err)); + } else { + console.info("cancelGroup success"); + } +} + +var groupName = "GroupName"; + +Notification.cancelGroup(groupName, cancelGroupCallback); +``` + + + +## Notification.cancelGroup + +cancelGroup(groupName: string): Promise\ + +Cancels notifications under a notification group of this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------- | +| groupName | string | Yes | Name of the notification group.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +var groupName = "GroupName"; +Notification.cancelGroup(groupName).then(() => { + console.info("cancelGroup success"); +}); +``` + + + +## Notification.removeGroupByBundle + +removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback\): void + +Removes notifications under a notification group of a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | --------------------- | ---- | ---------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| groupName | string | Yes | Name of the notification group. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function removeGroupByBundleCallback(err) { + if (err) { + console.info("removeGroupByBundle failed " + JSON.stringify(err)); + } else { + console.info("removeGroupByBundle success"); + } +} + +var bundleOption = {bundle: "Bundle"}; +var groupName = "GroupName"; + +Notification.removeGroupByBundle(bundleOption, groupName, removeGroupByBundleCallback); +``` + + + +## Notification.removeGroupByBundle + +removeGroupByBundle(bundle: BundleOption, groupName: string): Promise\ + +Removes notifications under a notification group of a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------ | ---- | -------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| groupName | string | Yes | Name of the notification group.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundleOption = {bundle: "Bundle"}; +var groupName = "GroupName"; +Notification.removeGroupByBundle(bundleOption, groupName).then(() => { + console.info("removeGroupByBundle success"); +}); +``` + + + +## Notification.setDoNotDisturbDate + +setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback\): void + +Sets the DND time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------- | +| date | [DoNotDisturbDate](#donotdisturbdate) | Yes | DND time to set. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function setDoNotDisturbDateCallback(err) { + if (err) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } +} + +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +Notification.setDoNotDisturbDate(doNotDisturbDate, setDoNotDisturbDateCallback); +``` + + + +## Notification.setDoNotDisturbDate + +setDoNotDisturbDate(date: DoNotDisturbDate): Promise\ + +Sets the DND time. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type | Mandatory| Description | +| ---- | ---------------- | ---- | -------------- | +| date | [DoNotDisturbDate](#donotdisturbdate) | Yes | DND time to set.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} +Notification.setDoNotDisturbDate(doNotDisturbDate).then(() => { + console.info("setDoNotDisturbDate success"); +}); +``` + + +## Notification.setDoNotDisturbDate + +setDoNotDisturbDate(date: DoNotDisturbDate, userId: number, callback: AsyncCallback\): void + +Sets the DND time for a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------- | +| date | [DoNotDisturbDate](#donotdisturbdate) | Yes | DND time to set. | +| userId | number | Yes | ID of the user for whom you want to set the DND time.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +function setDoNotDisturbDateCallback(err) { + if (err) { + console.info("setDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("setDoNotDisturbDate success"); + } +} + +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +var userId = 1 + +Notification.setDoNotDisturbDate(doNotDisturbDate, userId, setDoNotDisturbDateCallback); +``` + + + +## Notification.setDoNotDisturbDate + +setDoNotDisturbDate(date: DoNotDisturbDate, userId: number): Promise\ + +Sets the DND time for a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ---------------- | ---- | -------------- | +| date | [DoNotDisturbDate](#donotdisturbdate) | Yes | DND time to set.| +| userId | number | Yes | ID of the user for whom you want to set the DND time.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +var doNotDisturbDate = { + type: Notification.DoNotDisturbType.TYPE_ONCE, + begin: new Date(), + end: new Date(2021, 11, 15, 18, 0) +} + +var userId = 1 + +Notification.setDoNotDisturbDate(doNotDisturbDate, userId).then(() => { + console.info("setDoNotDisturbDate success"); +}); +``` + + +## Notification.getDoNotDisturbDate + +getDoNotDisturbDate(callback: AsyncCallback\): void + +Obtains the DND time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------------------- | +| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate)\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function getDoNotDisturbDateCallback(err,data) { + if (err) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } +} + +Notification.getDoNotDisturbDate(getDoNotDisturbDateCallback); +``` + + + +## Notification.getDoNotDisturbDate + +getDoNotDisturbDate(): Promise\ + +Obtains the DND time. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type | Description | +| ------------------------------------------------ | ----------------------------------------- | +| Promise\<[DoNotDisturbDate](#donotdisturbdate)\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.getDoNotDisturbDate().then((data) => { + console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); +}); +``` + + +## Notification.getDoNotDisturbDate + +getDoNotDisturbDate(userId: number, callback: AsyncCallback\): void + +Obtains the DND time of a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------------------- | +| callback | AsyncCallback\<[DoNotDisturbDate](#donotdisturbdate)\> | Yes | Callback used to return the result.| +| userId | number | Yes | User ID.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +function getDoNotDisturbDateCallback(err,data) { + if (err) { + console.info("getDoNotDisturbDate failed " + JSON.stringify(err)); + } else { + console.info("getDoNotDisturbDate success"); + } +} + +var userId = 1 + +Notification.getDoNotDisturbDate(userId, getDoNotDisturbDateCallback); +``` + + + +## Notification.getDoNotDisturbDate + +getDoNotDisturbDate(userId: number): Promise\ + +Obtains the DND time of a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ---------------------- | +| userId | number | Yes | User ID.| + +**Return value** + +| Type | Description | +| ------------------------------------------------ | ----------------------------------------- | +| Promise\<[DoNotDisturbDate](#donotdisturbdate)\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +var userId = 1 + +Notification.getDoNotDisturbDate(userId).then((data) => { + console.info("getDoNotDisturbDate success, data: " + JSON.stringify(data)); +}); +``` + + +## Notification.supportDoNotDisturbMode + +supportDoNotDisturbMode(callback: AsyncCallback\): void + +Checks whether DND mode is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function supportDoNotDisturbModeCallback(err,data) { + if (err) { + console.info("supportDoNotDisturbMode failed " + JSON.stringify(err)); + } else { + console.info("supportDoNotDisturbMode success"); + } +} + +Notification.supportDoNotDisturbMode(supportDoNotDisturbModeCallback); +``` + + + +## Notification.supportDoNotDisturbMode + +supportDoNotDisturbMode(): Promise\ + +Checks whether DND mode is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +Notification.supportDoNotDisturbMode().then((data) => { + console.info("supportDoNotDisturbMode success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.isSupportTemplate + +isSupportTemplate(templateName: string, callback: AsyncCallback\): void + +Checks whether a specified template is supported. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------ | ---- | -------------------------- | +| templateName | string | Yes | Template name. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600011 | Read template config failed. | + +**Example** + +```javascript +var templateName = 'process'; +function isSupportTemplateCallback(err, data) { + if (err) { + console.info("isSupportTemplate failed " + JSON.stringify(err)); + } else { + console.info("isSupportTemplate success"); + } +} + +Notification.isSupportTemplate(templateName, isSupportTemplateCallback); +``` + + + +## Notification.isSupportTemplate + +isSupportTemplate(templateName: string): Promise\ + +Checks whether a specified template is supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------ | ------ | ---- | -------- | +| templateName | string | Yes | Template name.| + +**Return value** + +| Type | Description | +| ------------------ | --------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600011 | Read template config failed. | + +**Example** + +```javascript +var templateName = 'process'; + +Notification.isSupportTemplate(templateName).then((data) => { + console.info("isSupportTemplate success, data: " + JSON.stringify(data)); +}); +``` + + + +## Notification.requestEnableNotification + +requestEnableNotification(callback: AsyncCallback\): void + +Requests notification to be enabled for this application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```javascript +function requestEnableNotificationCallback(err) { + if (err) { + console.info("requestEnableNotification failed " + JSON.stringify(err)); + } else { + console.info("requestEnableNotification success"); + } +}; + +Notification.requestEnableNotification(requestEnableNotificationCallback); +``` + + + +## Notification.requestEnableNotification + +requestEnableNotification(): Promise\ + +Requests notification to be enabled for this application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```javascript +Notification.requestEnableNotification().then(() => { + console.info("requestEnableNotification success"); +}); +``` + + + +## Notification.setDistributedEnable + +setDistributedEnable(enable: boolean, callback: AsyncCallback\): void + +Sets whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether the device supports distributed notifications.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | + +**Example** + +```javascript +function setDistributedEnableCallback() { + if (err) { + console.info("setDistributedEnable failed " + JSON.stringify(err)); + } else { + console.info("setDistributedEnable success"); + } +}; + +var enable = true + +Notification.setDistributedEnable(enable, setDistributedEnableCallback); +``` + + + +## Notification.setDistributedEnable + +setDistributedEnable(enable: boolean): Promise\ + +Sets whether this device supports distributed notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| enable | boolean | Yes | Whether the device supports distributed notifications.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | + +**Example** + +```javascript +var enable = true + +Notification.setDistributedEnable(enable).then(() => { + console.info("setDistributedEnable success"); + }); +``` + + +## Notification.isDistributedEnabled + +isDistributedEnabled(callback: AsyncCallback\): void + +Checks whether this device supports distributed notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | + +**Example** + +```javascript +function isDistributedEnabledCallback(err, data) { + if (err) { + console.info("isDistributedEnabled failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabled success " + JSON.stringify(data)); + } +}; + +Notification.isDistributedEnabled(isDistributedEnabledCallback); +``` + + + +## Notification.isDistributedEnabled + +isDistributedEnabled(): Promise\ + +Checks whether this device supports distributed notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Return value** + +| Type | Description | +| ------------------ | --------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | + +**Example** + +```javascript +Notification.isDistributedEnabled() + .then((data) => { + console.info("isDistributedEnabled success, data: " + JSON.stringify(data)); + }); +``` + + +## Notification.setDistributedEnableByBundle + +setDistributedEnableByBundle(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void + +Sets whether a specified application supports distributed notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| enable | boolean | Yes | Whether the application supports distributed notifications. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```javascript +function setDistributedEnableByBundleCallback(err) { + if (err) { + console.info("enableDistributedByBundle failed " + JSON.stringify(err)); + } else { + console.info("enableDistributedByBundle success"); + } +}; + +var bundle = { + bundle: "bundleName1", +} + +var enable = true + +Notification.setDistributedEnableByBundle(bundle, enable, setDistributedEnableByBundleCallback); +``` + + + +## Notification.setDistributedEnableByBundle + +setDistributedEnableByBundle(bundle: BundleOption, enable: boolean): Promise\ + +Sets whether a specified application supports distributed notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| enable | boolean | Yes | Whether the application supports distributed notifications. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```javascript +var bundle = { + bundle: "bundleName1", +} + +var enable = true + +Notification.setDistributedEnableByBundle(bundle, enable).then(() => { + console.info("setDistributedEnableByBundle success"); + }); +``` + +## Notification.isDistributedEnabledByBundle + +isDistributedEnabledByBundle(bundle: BundleOption, callback: AsyncCallback\): void + +Checks whether a specified application supports distributed notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```javascript +function isDistributedEnabledByBundleCallback(data) { + if (err) { + console.info("isDistributedEnabledByBundle failed " + JSON.stringify(err)); + } else { + console.info("isDistributedEnabledByBundle success" + JSON.stringify(data)); + } +}; + +var bundle = { + bundle: "bundleName1", +} + +Notification.isDistributedEnabledByBundle(bundle, isDistributedEnabledByBundleCallback); +``` + + + +## Notification.isDistributedEnabledByBundle + +isDistributedEnabledByBundle(bundle: BundleOption): Promise\ + +Checks whether a specified application supports distributed notifications. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | -------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | + +**Return value** + +| Type | Description | +| ------------------ | ------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600010 | Distributed operation failed. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```javascript +var bundle = { + bundle: "bundleName1", +} + +Notification.isDistributedEnabledByBundle(bundle).then((data) => { + console.info("isDistributedEnabledByBundle success, data: " + JSON.stringify(data)); +}); +``` + + +## Notification.getDeviceRemindType + +getDeviceRemindType(callback: AsyncCallback\): void + +Obtains the notification reminder type. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | -------------------------- | +| callback | AsyncCallback\<[DeviceRemindType](#deviceremindtype)\> | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```javascript +function getDeviceRemindTypeCallback(err, data) { + if (err) { + console.info("getDeviceRemindType failed " + JSON.stringify(err)); + } else { + console.info("getDeviceRemindType success"); + } +}; + +Notification.getDeviceRemindType(getDeviceRemindTypeCallback); +``` + + + +## Notification.getDeviceRemindType + +getDeviceRemindType(): Promise\ + +Obtains the notification reminder type. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Return value** + +| Type | Description | +| ------------------ | --------------- | +| Promise\<[DeviceRemindType](#deviceremindtype)\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```javascript +Notification.getDeviceRemindType().then((data) => { + console.info("getDeviceRemindType success, data: " + JSON.stringify(data)); +}); +``` + + +## Notification.publishAsBundle + +publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number, callback: AsyncCallback\): void + +Publishes a notification through the reminder agent. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------- | ---- | ---------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | +| userId | number | Yes | User ID. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600004 | Notification is not enabled. | +| 1600005 | Notification slot is not enabled. | +| 1600008 | The user is not exist. | +| 1600009 | Over max number notifications per second. | + +**Example** + +```js +// publishAsBundle callback +function callback(err) { + if (err) { + console.info("publishAsBundle failed " + JSON.stringify(err)); + } else { + console.info("publishAsBundle success"); + } +} +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// User ID +let userId = 100 +// NotificationRequest object +let request = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +Notification.publishAsBundle(request, representativeBundle, userId, callback); +``` + +## Notification.publishAsBundle + +publishAsBundle(request: NotificationRequest, representativeBundle: string, userId: number): Promise\ + +Publishes a notification through the reminder agent. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + + +| Name | Type | Mandatory| Description | +| -------------------- | ------------------------------------------- | ---- | --------------------------------------------- | +| request | [NotificationRequest](#notificationrequest) | Yes | Content and related configuration of the notification to publish.| +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | +| userId | number | Yes | User ID. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600004 | Notification is not enabled. | +| 1600005 | Notification slot is not enabled. | +| 1600008 | The user is not exist. | +| 1600009 | Over max number notifications per second. | + +**Example** + +```js +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// User ID +let userId = 100 +// NotificationRequest object +var request = { + id: 1, + content: { + contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, + normal: { + title: "test_title", + text: "test_text", + additionalText: "test_additionalText" + } + } +} + +Notification.publishAsBundle(request, representativeBundle, userId).then(() => { + console.info("publishAsBundle success"); +}); +``` + +## Notification.cancelAsBundle + +cancelAsBundle(id: number, representativeBundle: string, userId: number, callback: AsyncCallback\): void + +Cancels a notification published by the reminder agent. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | ------------- | ---- | ------------------------ | +| id | number | Yes | Notification ID. | +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent. | +| userId | number | Yes | User ID. | +| callback | AsyncCallback | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | +| 1600008 | The user is not exist. | + +**Example** + +```js +// cancelAsBundle +function cancelAsBundleCallback(err) { + if (err) { + console.info("cancelAsBundle failed " + JSON.stringify(err)); + } else { + console.info("cancelAsBundle success"); + } +} +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// User ID +let userId = 100 + +Notification.cancelAsBundle(0, representativeBundle, userId, cancelAsBundleCallback); +``` + +## Notification.cancelAsBundle + +cancelAsBundle(id: number, representativeBundle: string, userId: number): Promise\ + +Cancels a notification published by the reminder agent. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER, ohos.permission.NOTIFICATION_AGENT_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | ------ | ---- | ------------------ | +| id | number | Yes | Notification ID. | +| representativeBundle | string | Yes | Bundle name of the application whose notification function is taken over by the reminder agent.| +| userId | number | Yes | User ID.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | +| 1600008 | The user is not exist. | + +**Example** + +```js +// Bundle name of the application whose notification function is taken over by the reminder agent +let representativeBundle = "com.example.demo" +// User ID +let userId = 100 + +Notification.cancelAsBundle(0, representativeBundle, userId).then(() => { + console.info("cancelAsBundle success"); +}); +``` + +## Notification.setNotificationEnableSlot + +setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean, callback: AsyncCallback\): void + +Sets whether to enable a specified notification slot type for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| type | [SlotType](#slottype) | Yes | Notification slot type. | +| enable | boolean | Yes | Whether to enable the notification slot type. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +// setNotificationEnableSlot +function setNotificationEnableSlotCallback(err) { + if (err) { + console.info("setNotificationEnableSlot failed " + JSON.stringify(err)); + } else { + console.info("setNotificationEnableSlot success"); + } +}; + +Notification.setNotificationEnableSlot( + { bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION, + true, + setNotificationEnableSlotCallback); +``` + +## Notification.setNotificationEnableSlot + +setNotificationEnableSlot(bundle: BundleOption, type: SlotType, enable: boolean): Promise\ + +Sets whether to enable a specified notification slot type for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| type | [SlotType](#slottype) | Yes | Notification slot type.| +| enable | boolean | Yes | Whether to enable the notification slot type. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +// setNotificationEnableSlot +Notification.setNotificationEnableSlot( + { bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION, + true).then(() => { + console.info("setNotificationEnableSlot success"); + }); +``` + +## Notification.isNotificationSlotEnabled + +isNotificationSlotEnabled(bundle: BundleOption, type: SlotType, callback: AsyncCallback\): void + +Checks whether a specified notification slot type is enabled for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ---------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| type | [SlotType](#slottype) | Yes | Notification slot type. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +// isNotificationSlotEnabled +function getEnableSlotCallback(err, data) { + if (err) { + console.info("isNotificationSlotEnabled failed " + JSON.stringify(err)); + } else { + console.info("isNotificationSlotEnabled success"); + } +}; + +Notification.isNotificationSlotEnabled( + { bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION, + getEnableSlotCallback); +``` + +## Notification.isNotificationSlotEnabled + +isNotificationSlotEnabled(bundle: BundleOption, type: SlotType): Promise\ + +Checks whether a specified notification slot type is enabled for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| type | [SlotType](#slottype) | Yes | Notification slot type.| + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +// isNotificationSlotEnabled +Notification.isNotificationSlotEnabled({ bundle: "ohos.samples.notification", }, + Notification.SlotType.SOCIAL_COMMUNICATION).then((data) => { + console.info("isNotificationSlotEnabled success, data: " + JSON.stringify(data)); +}); +``` + + +## Notification.setSyncNotificationEnabledWithoutApp + +setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: AsyncCallback\): void + +Sets whether to enable the notification sync feature for devices where the application is not installed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | +| enable | boolean | Yes | Whether the feature is enabled. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +let userId = 100; +let enable = true; + +function callback(err) { + if (err) { + console.info("setSyncNotificationEnabledWithoutApp failed " + JSON.stringify(err)); + } else { + console.info("setSyncNotificationEnabledWithoutApp success"); + } +} + +Notification.setSyncNotificationEnabledWithoutApp(userId, enable, callback); +``` + + +## Notification.setSyncNotificationEnabledWithoutApp + +setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\ + +Sets whether to enable the notification sync feature for devices where the application is not installed. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | +| enable | boolean | Yes | Whether the feature is enabled. | + +**Return value** + +| Type | Description | +| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +let userId = 100; +let enable = true; + +Notification.setSyncNotificationEnabledWithoutApp(userId, enable).then(() => { + console.info('setSyncNotificationEnabledWithoutApp success'); +}).catch((err) => { + console.info('setSyncNotificationEnabledWithoutApp, err:' + JSON.stringify(err)); +}); +``` + + +## Notification.getSyncNotificationEnabledWithoutApp + +getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void + +Obtains whether the notification sync feature is enabled for devices where the application is not installed. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +let userId = 100; + +function getSyncNotificationEnabledWithoutAppCallback(err, data) { + if (err) { + console.info('getSyncNotificationEnabledWithoutAppCallback, err:' + err); + } else { + console.info('getSyncNotificationEnabledWithoutAppCallback, data:' + data); + } +} + +Notification.getSyncNotificationEnabledWithoutApp(userId, getSyncNotificationEnabledWithoutAppCallback); +``` + + +## Notification.getSyncNotificationEnabledWithoutApp + +getSyncNotificationEnabledWithoutApp(userId: number): Promise\ + +Obtains whether the notification sync feature is enabled for devices where the application is not installed. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------- | +| userId | number | Yes | User ID. | + +**Return value** + +| Type | Description | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +let userId = 100; +Notification.getSyncNotificationEnabledWithoutApp(userId).then((data) => { + console.info('getSyncNotificationEnabledWithoutApp, data:' + data); +}).catch((err) => { + console.info('getSyncNotificationEnabledWithoutApp, err:' + err); +}); + .catch((err) => { + console.info('getSyncNotificationEnabledWithoutApp, err:', err); + }); +``` + + + + +## DoNotDisturbDate + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----- | ------------------------------------- | ---- | ---- | ---------------------- | +| type | [DoNotDisturbType](#donotdisturbtype) | Yes | Yes | DND time type.| +| begin | Date | Yes | Yes | DND start time.| +| end | Date | Yes | Yes | DND end time.| + + + +## DoNotDisturbType + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| ------------ | ---------------- | ------------------------------------------ | +| TYPE_NONE | 0 | Non-DND. | +| TYPE_ONCE | 1 | One-shot DND at the specified time segment (only considering the hour and minute).| +| TYPE_DAILY | 2 | Daily DND at the specified time segment (only considering the hour and minute).| +| TYPE_CLEARLY | 3 | DND at the specified time segment (considering the year, month, day, hour, and minute). | + + +## ContentType + +**System capability**: SystemCapability.Notification.Notification + +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| NOTIFICATION_CONTENT_BASIC_TEXT | NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification. | +| NOTIFICATION_CONTENT_LONG_TEXT | NOTIFICATION_CONTENT_LONG_TEXT | Long text notification. | +| NOTIFICATION_CONTENT_PICTURE | NOTIFICATION_CONTENT_PICTURE | Picture-attached notification. | +| NOTIFICATION_CONTENT_CONVERSATION | NOTIFICATION_CONTENT_CONVERSATION | Conversation notification. | +| NOTIFICATION_CONTENT_MULTILINE | NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.| + +## SlotLevel + +**System capability**: SystemCapability.Notification.Notification + +| Name | Value | Description | +| --------------------------------- | ----------- | ------------------ | +| LEVEL_NONE | 0 | Notification is disabled. | +| LEVEL_MIN | 1 | Notification is enabled, but the notification icon is not displayed in the status bar, with no banner or alert tone.| +| LEVEL_LOW | 2 | Notification is enabled, and the notification icon is displayed in the status bar, with no banner or alert tone.| +| LEVEL_DEFAULT | 3 | Notification is enabled, and the notification icon is displayed in the status bar, with an alert tone but no banner.| +| LEVEL_HIGH | 4 | Notification is enabled, and the notification icon is displayed in the status bar, with an alert tone and banner.| + + +## BundleOption + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ------ | ------ |---- | --- | ------ | +| bundle | string | Yes | Yes | Bundle information of the application.| +| uid | number | Yes | Yes | User ID.| + + +## SlotType + +**System capability**: SystemCapability.Notification.Notification + +| Name | Value | Description | +| -------------------- | -------- | ---------- | +| UNKNOWN_TYPE | 0 | Unknown type.| +| SOCIAL_COMMUNICATION | 1 | Notification slot for social communication.| +| SERVICE_INFORMATION | 2 | Notification slot for service information.| +| CONTENT_INFORMATION | 3 | Notification slot for content consultation.| +| OTHER_TYPES | 0xFFFF | Notification slot for other purposes.| + + +## NotificationActionButton + +Describes the button displayed in the notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| --------- | ----------------------------------------------- | --- | ---- | ------------------------- | +| title | string | Yes | Yes | Button title. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** of the button.| +| extras | { [key: string]: any } | Yes | Yes | Extra information of the button. | +| userInput | [NotificationUserInput](#notificationuserinput) | Yes | Yes | User input object. | + + +## NotificationBasicContent + +Describes the normal text notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | ---- | ---------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| + + +## NotificationLongTextContent + +Describes the long text notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | ------ | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| longText | string | Yes | Yes | Long text of the notification. | +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | + + +## NotificationMultiLineContent + +Describes the multi-line text notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | --------------- | --- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| longTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| lines | Array\ | Yes | Yes | Multi-line text of the notification. | + + +## NotificationPictureContent + +Describe the picture-attached notification. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------- | -------------- | ---- | --- | -------------------------------- | +| title | string | Yes | Yes | Notification title. | +| text | string | Yes | Yes | Notification content. | +| additionalText | string | Yes | Yes | Additional information of the notification.| +| briefText | string | Yes | Yes | Brief text of the notification.| +| expandedTitle | string | Yes | Yes | Title of the notification in the expanded state. | +| picture | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Picture attached to the notification. | + + +## NotificationContent + +Describes the notification content. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ----------- | ------------------------------------------------------------ | ---- | --- | ------------------ | +| contentType | [ContentType](#contenttype) | Yes | Yes | Notification content type. | +| normal | [NotificationBasicContent](#notificationbasiccontent) | Yes | Yes | Normal text. | +| longText | [NotificationLongTextContent](#notificationlongtextcontent) | Yes | Yes | Long text.| +| multiLine | [NotificationMultiLineContent](#notificationmultilinecontent) | Yes | Yes | Multi-line text. | +| picture | [NotificationPictureContent](#notificationpicturecontent) | Yes | Yes | Picture-attached. | + + +## NotificationFlagStatus + +Describes the notification flag status. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------- | --- | --------------------------------- | +| TYPE_NONE | 0 | The default flag is used. | +| TYPE_OPEN | 1 | The notification flag is enabled. | +| TYPE_CLOSE | 2 | The notification flag is disabled. | + + +## NotificationFlags + +Enumerates notification flags. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ---------------- | ---------------------- | ---- | ---- | --------------------------------- | +| soundEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable the sound alert for the notification. | +| vibrationEnabled | [NotificationFlagStatus](#notificationflagstatus) | Yes | No | Whether to enable vibration for the notification. | + + +## NotificationRequest + +Describes the notification request. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| --------------------- | --------------------------------------------- | ---- | --- | -------------------------- | +| content | [NotificationContent](#notificationcontent) | Yes | Yes | Notification content. | +| id | number | Yes | Yes | Notification ID. | +| slotType | [SlotType](#slottype) | Yes | Yes | Notification slot type. | +| isOngoing | boolean | Yes | Yes | Whether the notification is an ongoing notification. | +| isUnremovable | boolean | Yes | Yes | Whether the notification can be removed. | +| deliveryTime | number | Yes | Yes | Time when the notification is sent. | +| tapDismissed | boolean | Yes | Yes | Whether the notification is automatically cleared. | +| autoDeletedTime | number | Yes | Yes | Time when the notification is automatically cleared. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected after being clicked.| +| extraInfo | {[key: string]: any} | Yes | Yes | Extended parameters. | +| color | number | Yes | Yes | Background color of the notification. Not supported currently.| +| colorEnabled | boolean | Yes | Yes | Whether the notification background color can be enabled. Not supported currently.| +| isAlertOnce | boolean | Yes | Yes | Whether the notification triggers an alert only once.| +| isStopwatch | boolean | Yes | Yes | Whether to display the stopwatch. | +| isCountDown | boolean | Yes | Yes | Whether to display the countdown time. | +| isFloatingIcon | boolean | Yes | Yes | Whether the notification is displayed as a floating icon in the status bar. | +| label | string | Yes | Yes | Notification label. | +| badgeIconStyle | number | Yes | Yes | Notification badge type. | +| showDeliveryTime | boolean | Yes | Yes | Whether to display the time when the notification is delivered. | +| actionButtons | Array\<[NotificationActionButton](#notificationactionbutton)\> | Yes | Yes | Buttons in the notification. Up to two buttons are allowed. | +| smallIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Small notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| largeIcon | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes | Yes | Large notification icon. This field is optional, and the icon size cannot exceed 30 KB.| +| creatorBundleName | string | Yes | No | Name of the bundle that creates the notification. | +| creatorUid | number | Yes | No | UID used for creating the notification. | +| creatorPid | number | Yes | No | PID used for creating the notification. | +| creatorUserId| number | Yes | No | ID of the user who creates the notification. | +| hashCode | string | Yes | No | Unique ID of the notification. | +| classification | string | Yes | Yes | Notification category.
**System API**: This is a system API and cannot be called by third-party applications. | +| groupName| string | Yes | Yes | Notification group name. | +| template | [NotificationTemplate](#notificationtemplate) | Yes | Yes | Notification template. | +| isRemoveAllowed | boolean | Yes | No | Whether the notification can be removed.
**System API**: This is a system API and cannot be called by third-party applications. | +| source | number | Yes | No | Notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| distributedOption | [DistributedOptions](#distributedoptions) | Yes | Yes | Distributed notification options. | +| deviceId | string | Yes | No | Device ID of the notification source.
**System API**: This is a system API and cannot be called by third-party applications. | +| notificationFlags | [NotificationFlags](#notificationflags) | Yes | No | Notification flags. | +| removalWantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Yes | **WantAgent** instance to which the notification will be redirected when it is removed. | +| badgeNumber | number | Yes | Yes | Number of notifications displayed on the application icon. | + + +## DistributedOptions + +Describes distributed options. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ---------------------- | -------------- | ---- | ---- | ---------------------------------- | +| isDistributed | boolean | Yes | Yes | Whether the notification is a distributed notification. | +| supportDisplayDevices | Array\ | Yes | Yes | List of the devices to which the notification can be synchronized. | +| supportOperateDevices | Array\ | Yes | Yes | List of the devices on which the notification can be opened. | +| remindType | number | Yes | No | Notification reminder type.
**System API**: This is a system API and cannot be called by third-party applications. | + + +## NotificationSlot + +Describes the notification slot. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------------------- | --------------------- | ---- | --- | ------------------------------------------ | +| type | [SlotType](#slottype) | Yes | Yes | Notification slot type. | +| level | number | Yes | Yes | Notification level. If this parameter is not set, the default value is used based on the notification slot type.| +| desc | string | Yes | Yes | Notification slot description. | +| badgeFlag | boolean | Yes | Yes | Whether to display the badge. | +| bypassDnd | boolean | Yes | Yes | Whether to bypass DND mode in the system. | +| lockscreenVisibility | number | Yes | Yes | Mode for displaying the notification on the lock screen. | +| vibrationEnabled | boolean | Yes | Yes | Whether vibration is enabled for the notification. | +| sound | string | Yes | Yes | Notification alert tone. | +| lightEnabled | boolean | Yes | Yes | Whether the indicator blinks for the notification. | +| lightColor | number | Yes | Yes | Indicator color of the notification. | +| vibrationValues | Array\ | Yes | Yes | Vibration mode of the notification. | +| enabled9+ | boolean | Yes | No | Whether the notification slot is enabled. | + + +## NotificationTemplate + +Describes the notification template. + +**System capability**: SystemCapability.Notification.Notification + +| Name| Type | Readable| Writable| Description | +| ---- | ---------------------- | ---- | ---- | ---------- | +| name | string | Yes | Yes | Template name.| +| data | {[key:string]: Object} | Yes | Yes | Template data.| + + +## NotificationUserInput + +Provides the notification user input. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------- | ------ | --- | ---- | ----------------------------- | +| inputKey | string | Yes | Yes | Key to identify the user input.| + + +## DeviceRemindType + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | --------------------------------- | +| IDLE_DONOT_REMIND | 0 | The device is not in use. No notification is required. | +| IDLE_REMIND | 1 | The device is not in use. | +| ACTIVE_DONOT_REMIND | 2 | The device is in use. No notification is required. | +| ACTIVE_REMIND | 3 | The device is in use. | + + +## SourceType + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | -------------------- | +| TYPE_NORMAL | 0 | Normal notification. | +| TYPE_CONTINUOUS | 1 | Continuous notification. | +| TYPE_TIMER | 2 | Timed notification. | diff --git a/en/application-dev/reference/apis/js-apis-notificationSubscribe.md b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md new file mode 100644 index 0000000000000000000000000000000000000000..ed0ad9400ed59c637b5495c7b20f8770b0b4329c --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-notificationSubscribe.md @@ -0,0 +1,1074 @@ +# @ohos.notificationSubscribe + +The **NotificationSubscribe** module provides APIs for notification subscription, notification unsubscription, subscription removal, and more. In general cases, only system applications can call these APIs. + +> **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 NotificationSubscribe from '@ohos.notificationSubscribe'; +``` + + + +## NotificationSubscribe.subscribe + +subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void + +Subscribes to a notification with the subscription information specified. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ---------------- | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | Yes | Notification subscription information.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +// subscribe callback +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } +} +function onConsumeCallback(data) { + console.info("Consume callback: " + JSON.stringify(data)); +} +var subscriber = { + onConsume: onConsumeCallback +} +var info = { + bundleNames: ["bundleName1","bundleName2"] +} +NotificationSubscribe.subscribe(subscriber, info, subscribeCallback); +``` + + + +## NotificationSubscribe.subscribe + +subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void + +Subscribes to notifications of all applications under this user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | ---------------- | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribe success"); + } +} +function onConsumeCallback(data) { + console.info("Consume callback: " + JSON.stringify(data)); +} +var subscriber = { + onConsume: onConsumeCallback +} +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + + + +## NotificationSubscribe.subscribe + +subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise\ + +Subscribes to a notification with the subscription information specified. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------ | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| +| info | [NotificationSubscribeInfo](#notificationsubscribeinfo) | No | Notification subscription information. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function onConsumeCallback(data) { + console.info("Consume callback: " + JSON.stringify(data)); +} +var subscriber = { + onConsume: onConsumeCallback +}; +NotificationSubscribe.subscribe(subscriber).then(() => { + console.info("subscribe success"); +}); +``` + + + +## NotificationSubscribe.unsubscribe + +unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void + +Unsubscribes from a notification. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | -------------------- | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function unsubscribeCallback(err) { + if (err) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribe success"); + } +} +function onDisconnectCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); +} +var subscriber = { + onDisconnect: onDisconnectCallback +} +NotificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); +``` + + + +## NotificationSubscribe.unsubscribe + +unsubscribe(subscriber: NotificationSubscriber): Promise\ + +Unsubscribes from a notification. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ---------------------- | ---- | ------------ | +| subscriber | [NotificationSubscriber](#notificationsubscriber) | Yes | Notification subscriber.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function onDisconnectCallback(data) { + console.info("Cancel callback: " + JSON.stringify(data)); +} +var subscriber = { + onDisconnect: onDisconnectCallback +}; +NotificationSubscribe.unsubscribe(subscriber).then(() => { + console.info("unsubscribe success"); +}); +``` + + + +## NotificationSubscribe.remove + +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason, callback: AsyncCallback\): void + +Removes a notification for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | ----------------------------------| ---- | -------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function removeCallback(err) { + if (err) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } +} +var bundle = { + bundle: "bundleName1", +} +var notificationKey = { + id: 0, + label: "label", +} +var reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +NotificationSubscribe.remove(bundle, notificationKey, reason, removeCallback); +``` + + + +## NotificationSubscribe.remove + +remove(bundle: BundleOption, notificationKey: NotificationKey, reason: RemoveReason): Promise\ + +Removes a notification for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------- | --------------- | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application.| +| notificationKey | [NotificationKey](#notificationkey) | Yes | Notification key. | +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +var bundle = { + bundle: "bundleName1", +} +var notificationKey = { + id: 0, + label: "label", +} +var reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +NotificationSubscribe.remove(bundle, notificationKey, reason).then(() => { + console.info("remove success"); +}); +``` + + + +## NotificationSubscribe.remove + +remove(hashCode: string, reason: RemoveReason, callback: AsyncCallback\): void + +Removes a specified notification. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| hashCode | string | Yes | Unique notification ID. It is the **hashCode** in the [NotificationRequest](#notificationrequest) object of [SubscribeCallbackData](#subscribecallbackdata) of the [onConsume](#onconsume) callback.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | + +**Example** + +```js +var hashCode = 'hashCode' + +function removeCallback(err) { + if (err) { + console.info("remove failed " + JSON.stringify(err)); + } else { + console.info("remove success"); + } +} +var reason = NotificationSubscribe.RemoveReason.CANCEL_REASON_REMOVE; +NotificationSubscribe.remove(hashCode, reason, removeCallback); +``` + + + +## NotificationSubscribe.remove + +remove(hashCode: string, reason: RemoveReason): Promise\ + +Removes a specified notification. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------- | ---- | ---------- | +| hashCode | string | Yes | Unique notification ID.| +| reason | [RemoveReason](#removereason) | Yes | Reason for removing the notification. | + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600007 | The notification is not exist. | + +**Example** + +```js +var hashCode = 'hashCode' +var reason = NotificationSubscribe.RemoveReason.CLICK_REASON_REMOVE; +NotificationSubscribe.remove(hashCode, reason).then(() => { + console.info("remove success"); +}); +``` + + + +## NotificationSubscribe.removeAll + +removeAll(bundle: BundleOption, callback: AsyncCallback\): void + +Removes all notifications for a specified application. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------------------------- | +| bundle | [BundleOption](#bundleoption) | Yes | Bundle information of the application. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +function removeAllCallback(err) { + if (err) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } +} +var bundle = { + bundle: "bundleName1", +} +NotificationSubscribe.removeAll(bundle, removeAllCallback); +``` + + + +## NotificationSubscribe.removeAll + +removeAll(callback: AsyncCallback\): void + +Removes all notifications. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | -------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | + +**Example** + +```js +function removeAllCallback(err) { + if (err) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } +} + +NotificationSubscribe.removeAll(removeAllCallback); +``` + + + +## NotificationSubscribe.removeAll + +removeAll(bundle?: BundleOption): Promise\ + +Removes all notifications for a specified application. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| bundle | [BundleOption](#bundleoption) | No | Bundle information of the application.| + +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 17700001 | The specified bundle name was not found. | + +**Example** + +```js +// If no application is specified, notifications of all applications are deleted. +NotificationSubscribe.removeAll().then(() => { + console.info("removeAll success"); +}); +``` + +## NotificationSubscribe.removeAll + +removeAll(userId: number, callback: AsyncCallback\): void + +Removes all notifications for a specified user. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| userId | number | Yes | User ID.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +function removeAllCallback(err) { + if (err) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } +} + +var userId = 1 + +NotificationSubscribe.removeAll(userId, removeAllCallback); +``` + +## Notification.removeAll + +removeAll(userId: number): Promise\ + +Removes all notifications for a specified user. This API uses a promise to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**Required permissions**: ohos.permission.NOTIFICATION_CONTROLLER + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------ | ------------ | ---- | ---------- | +| userId | number | Yes | User ID.| + +**Error codes** + +| ID| Error Message | +| -------- | ----------------------------------- | +| 1600001 | Internal error. | +| 1600002 | Marshalling or unmarshalling error. | +| 1600003 | Failed to connect service. | +| 1600008 | The user is not exist. | + +**Example** + +```js +function removeAllCallback(err) { + if (err) { + console.info("removeAll failed " + JSON.stringify(err)); + } else { + console.info("removeAll success"); + } +} + +var userId = 1 + +NotificationSubscribe.removeAll(userId, removeAllCallback); +``` + + + +## NotificationSubscriber + +Provides callbacks for receiving or removing notifications and serves as the input parameter of [subscribe](#notificationsubscribe). + +**System API**: This is a system API and cannot be called by third-party applications. + +### onConsume + +onConsume?: (data: [SubscribeCallbackData](#subscribecallbackdata)) => void + +Callback for receiving notifications. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification received.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onConsumeCallback(data) { + console.info('===> onConsume in test'); + let req = data.request; + console.info('===> onConsume callback req.id:' + req.id); +}; + +var subscriber = { + onConsume: onConsumeCallback +}; + +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onCancel + +onCancel?:(data: [SubscribeCallbackData](#subscribecallbackdata)) => void + +Callback for canceling notifications. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [SubscribeCallbackData](#subscribecallbackdata) | Yes| Information about the notification to cancel.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onCancelCallback(data) { + console.info('===> onCancel in test'); + let req = data.request; + console.info('===> onCancel callback req.id:' + req.id); +} + +var subscriber = { + onCancel: onCancelCallback +}; + +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onUpdate + +onUpdate?:(data: [NotificationSortingMap](#notificationsortingmap)) => void + +Callback for notification sorting updates. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| data | [NotificationSortingMap](#notificationsortingmap) | Yes| Latest notification sorting list.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onUpdateCallback(map) { + console.info('===> onUpdateCallback map:' + JSON.stringify(map)); +} + +var subscriber = { + onUpdate: onUpdateCallback +}; + +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onConnect + +onConnect?:() => void + +Callback for subscription. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onConnectCallback() { + console.info('===> onConnect in test'); +} + +var subscriber = { + onConnect: onConnectCallback +}; + +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onDisconnect + +onDisconnect?:() => void + +Callback for unsubscription. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; +function unsubscribeCallback(err) { + if (err.code) { + console.info("unsubscribe failed " + JSON.stringify(err)); + } else { + console.info("unsubscribeCallback"); + } +}; + +function onConnectCallback() { + console.info('===> onConnect in test'); +} +function onDisconnectCallback() { + console.info('===> onDisconnect in test'); +} + +var subscriber = { + onConnect: onConnectCallback, + onDisconnect: onDisconnectCallback +}; + +// The onConnect callback is invoked when subscription to the notification is complete. +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +// The onDisconnect callback is invoked when unsubscription to the notification is complete. +NotificationSubscribe.unsubscribe(subscriber, unsubscribeCallback); +``` + +### onDestroy + +onDestroy?:() => void + +Callback for service disconnection. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onDestroyCallback() { + console.info('===> onDestroy in test'); +} + +var subscriber = { + onDestroy: onDestroyCallback +}; + +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +### onDoNotDisturbDateChange + +onDoNotDisturbDateChange?:(mode: notification.[DoNotDisturbDate](js-apis-notificationManager.md#donotdisturbdate)) => void + +Callback for DND time setting updates. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| mode | notification.[DoNotDisturbDate](js-apis-notificationManager.md#DoNotDisturbDate) | Yes| DND time setting updates.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onDoNotDisturbDateChangeCallback(mode) { + console.info('===> onDoNotDisturbDateChange:' + mode); +} + +var subscriber = { + onDoNotDisturbDateChange: onDoNotDisturbDateChangeCallback +}; + +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + + +### onEnabledNotificationChanged + +onEnabledNotificationChanged?:(callbackData: [EnabledNotificationCallbackData](#enablednotificationcallbackdata)) => void + +Listens for the notification enabled status changes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------------ | ------------------------ | ---- | -------------------------- | +| callback | AsyncCallback\<[EnabledNotificationCallbackData](#enablednotificationcallbackdata)\> | Yes| Callback used to return the result.| + +**Example** + +```javascript +function subscribeCallback(err) { + if (err) { + console.info("subscribe failed " + JSON.stringify(err)); + } else { + console.info("subscribeCallback"); + } +}; + +function onEnabledNotificationChangedCallback(callbackData) { + console.info("bundle: ", callbackData.bundle); + console.info("uid: ", callbackData.uid); + console.info("enable: ", callbackData.enable); +}; + +var subscriber = { + onEnabledNotificationChanged: onEnabledNotificationChangedCallback +}; + +NotificationSubscribe.subscribe(subscriber, subscribeCallback); +``` + +## BundleOption + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ------ | ------ |---- | --- | ------ | +| bundle | string | Yes | Yes | Bundle information of the application.| +| uid | number | Yes | Yes | User ID.| + +## NotificationKey + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| ----- | ------ | ---- | --- | -------- | +| id | number | Yes | Yes | Notification ID. | +| label | string | Yes | Yes | Notification label.| + +## SubscribeCallbackData + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable | Writable | Description | +| --------------- | ------------------------------------------------- | -------- | -------- | -------- | +| request | [NotificationRequest](js-apis-notificationManager.md#notificationrequest) | Yes| No| Notification content.| +| sortingMap | [NotificationSortingMap](#notificationsortingmap) | Yes| No| Notification sorting information.| +| reason | number | Yes | No | Reason for deletion.| +| sound | string | Yes | No | Sound used for notification.| +| vibrationValues | Array\ | Yes | No | Vibration used for notification.| + + +## EnabledNotificationCallbackData + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable | Writable | Description | +| ------ | ------- | ---------------- | ---------------- | ---------------- | +| bundle | string | Yes| No| Bundle name of the application. | +| uid | number | Yes| No| UID of the application. | +| enable | boolean | Yes| No| Notification enabled status of the application.| + + +## NotificationSorting + +Provides sorting information of activity notifications. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| -------- | ------------------------------------- | ---- | --- | ------------ | +| slot | [NotificationSlot](js-apis-notificationManager.md#notificationslot) | Yes | No | Notification slot.| +| hashCode | string | Yes | No | Unique ID of the notification.| +| ranking | number | Yes | No | Notification sequence number.| + + +## NotificationSortingMap + +Provides sorting information of active notifications in all subscribed notifications. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| -------------- | ------------------------------------------------------------ | ---- | --- | ---------------- | +| sortings | {[key: string]: [NotificationSorting](#notificationsorting)} | Yes | No | Array of notification sorting information.| +| sortedHashCode | Array\ | Yes | No | Array of unique notification IDs.| + + +## NotificationSubscribeInfo + +Provides the information about the publisher for notification subscription. + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Type | Readable| Writable| Description | +| ----------- | --------------- | --- | ---- | ------------------------------- | +| bundleNames | Array\ | Yes | Yes | Bundle names of the applications whose notifications are to be subscribed to.| +| userId | number | Yes | Yes | User whose notifications are to be subscribed to. | + + +## NotificationUserInput + +Provides the notification user input. + +**System capability**: SystemCapability.Notification.Notification + +| Name | Type | Readable| Writable| Description | +| -------- | ------ | --- | ---- | ----------------------------- | +| inputKey | string | Yes | Yes | Key to identify the user input.| + +## RemoveReason + +**System capability**: SystemCapability.Notification.Notification + +**System API**: This is a system API and cannot be called by third-party applications. + +| Name | Value | Description | +| -------------------- | --- | -------------------- | +| CLICK_REASON_REMOVE | 1 | The notification is removed after a click on it. | +| CANCEL_REASON_REMOVE | 2 | The notification is removed by the user. | diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md index a6fcacc4333ab0aa48dae7cd8b629e1e77bb399f..ae5b7999bd7e579179920a73fcaea6116890ff70 100644 --- a/en/application-dev/reference/apis/js-apis-observer.md +++ b/en/application-dev/reference/apis/js-apis-observer.md @@ -1,6 +1,6 @@ -# Observer +# @ohos.telephony.observer (Observer) -The observer module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. +The **observer** module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change. >**NOTE** > @@ -531,8 +531,8 @@ Enumerates SIM card types and states. **System capability**: SystemCapability.Telephony.StateRegistry -| Name | Type | Description | -| ----------------- | --------------------- | ------------------------------------------------------------ | -| type | [CardType](js-apis-sim.md#cardtype) | SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).| -| state | [SimState](js-apis-sim.md#simstate) | SIM card status. For details, see [SimState](js-apis-sim.md#simstate).| -| reason8+ | [LockReason](#lockreason8) | SIM card lock type.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| type | [CardType](js-apis-sim.md#cardtype) | Yes| SIM card type. For details, see [CardType](js-apis-sim.md#cardtype).| +| state | [SimState](js-apis-sim.md#simstate) | Yes| SIM card status. For details, see [SimState](js-apis-sim.md#simstate).| +| reason8+ | [LockReason](#lockreason8) | Yes| SIM card lock type.| diff --git a/en/application-dev/reference/apis/js-apis-osAccount.md b/en/application-dev/reference/apis/js-apis-osAccount.md index 36e075f0e24f3a01dfc7feddc29173c364e0b885..f903401701e9f68ae6277a687215310f59afc34c 100644 --- a/en/application-dev/reference/apis/js-apis-osAccount.md +++ b/en/application-dev/reference/apis/js-apis-osAccount.md @@ -1,8 +1,9 @@ -# OS Account Management +# @ohos.account.osAccount The **osAccount** module provides basic capabilities for managing OS accounts, including adding, deleting, querying, setting, subscribing to, and enabling an OS account. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -37,7 +38,7 @@ Enumerates the OS account types. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ------ | ------ | ----------- | | ADMIN | 0 | Administrator account| | NORMAL | 1 | Normal account | @@ -154,7 +155,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Error codes** @@ -191,7 +192,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Error codes** @@ -220,7 +221,7 @@ checkOsAccountActivated(localId: number, callback: AsyncCallback<boolean>) Checks whether an OS account is activated. 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 @@ -229,7 +230,7 @@ Checks whether an OS account is activated. This API uses an asynchronous callbac | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Error codes** @@ -277,7 +278,7 @@ Checks whether an OS account is activated. This API uses a promise to return the | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Error codes** @@ -309,7 +310,7 @@ checkConstraintEnabled(localId: number, constraint: string, callback: AsyncCallb 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 or ohos.permission.INTERACT_ACROSS_LOCAL_ACCOUNTS +**Required permissions**: ohos.permission.MANAGE_LOCAL_ACCOUNTS **System capability**: SystemCapability.Account.OsAccount @@ -319,7 +320,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | ---------- | ---------------------------- | ---- | ----------------------------------------------------------------- | | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Error codes** @@ -369,7 +370,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Error codes** @@ -408,7 +409,7 @@ Checks whether this OS account is a test account. This API uses an asynchronous | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Error codes** @@ -445,7 +446,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Error codes** @@ -482,7 +483,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If true is returned, the current account has been verified. If false is returned, the current account has not been verified.| **Error codes** @@ -523,8 +524,8 @@ Checks whether an OS account has been verified. This API uses an asynchronous ca | 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.| +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Error codes** @@ -572,7 +573,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Error codes** @@ -814,7 +815,7 @@ Sets a name for an OS account. This API uses an asynchronous callback to return | 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. | +| localName | string | Yes | Account name. 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** @@ -1918,7 +1919,7 @@ Obtains the type of the account to which the current process belongs. This API u 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. +Obtains the type of the account to which the current process belongs. This API uses a promise to return the result. **System capability**: SystemCapability.Account.OsAccount @@ -2130,7 +2131,7 @@ Sets a profile photo for an OS account. This API uses an asynchronous callback t | -------- | ------------------------- | ---- | ------------ | | localId | number | Yes | ID of the target OS account.| | photo | string | Yes | Profile photo information. | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. | +| 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** @@ -2381,7 +2382,7 @@ Obtains the SN of an OS account based on the account ID. This API uses a promise on(type: 'activate' | 'activating', name: string, callback: Callback<number>): void -Subscribes to OS account changes. This API uses a callback to return the result. +Subscribes to the OS account activation states, including the states of the account being activated and the account with activation completed. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2393,9 +2394,9 @@ Subscribes to OS account changes. This API uses a callback to return the result. | 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.| +| type | 'activate' \| 'activating' | Yes | Type of the event to subscribe to. The value **activate** indicates an event reported when the OS account activation is complete, and **activating** indicates an event reported when 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. | +| callback | Callback<number> | Yes | Callback invoked to return the ID of the OS account being activated or activated. | **Error codes** @@ -2423,7 +2424,7 @@ Subscribes to OS account changes. This API uses a callback to return the result. off(type: 'activate' | 'activating', name: string, callback?: Callback<number>): void -Unsubscribes from OS account changes. This API uses a callback to return the result. +Unsubscribes from the OS account activation states, including the states of the account being activated and the account with activation completed. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -2437,7 +2438,7 @@ Unsubscribes from OS account changes. This API uses a callback to return the res | -------- | -------------------------- | ---- | ------------------------------------------------------------ | | 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. | +| callback | Callback<number> | No | Callback to unregister. By default, **0** is returned. | **Error codes** @@ -2708,7 +2709,6 @@ Obtains the constraint source information of an OS account. This API uses a prom console.info('queryOsAccountConstraintSourceType exception:' + JSON.stringify(e)); } ``` - ### isMultiOsAccountEnable(deprecated) isMultiOsAccountEnable(callback: AsyncCallback<boolean>): void @@ -2725,7 +2725,7 @@ Checks whether multiple OS accounts are supported. This API uses an asynchronous | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Example** @@ -2756,7 +2756,7 @@ Checks whether multiple OS accounts are supported. This API uses a promise to re | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means multiple OS accounts are supported; the value false means the opposite.| **Example** @@ -2789,7 +2789,7 @@ Checks whether an OS account is activated. This API uses an asynchronous callbac | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Example**: Check whether OS account 100 is activated. @@ -2829,7 +2829,7 @@ Checks whether an OS account is activated. This API uses a promise to return the | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is activated; the value **false** means the opposite.| **Example**: Check whether OS account 100 is activated. @@ -2863,7 +2863,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | ---------- | ---------------------------- | ---- | ----------------------------------------------------------------- | | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Example**: Check whether OS account 100 is forbidden to use Wi-Fi. @@ -2905,7 +2905,7 @@ Checks whether the specified constraint is enabled for an OS account. This API u | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the specified constraint is enabled; the value **false** means the opposite.| **Example**: Check whether OS account 100 is forbidden to use Wi-Fi. @@ -2936,7 +2936,7 @@ Checks whether this OS account is a test account. This API uses an asynchronous | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Example** @@ -2967,7 +2967,7 @@ Checks whether this OS account is a test account. This API uses a promise to ret | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the account is a test account; the value **false** means the opposite.| **Example** @@ -2998,7 +2998,7 @@ Checks whether this OS account has been verified. This API uses an asynchronous | 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.| +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Example** @@ -3031,8 +3031,8 @@ Checks whether an OS account has been verified. This API uses an asynchronous ca | 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.| +| localId | number | Yes | ID of the target OS account. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Example** @@ -3072,7 +3072,7 @@ Checks whether an OS account has been verified. This API uses a promise to retur | 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.| +| Promise<boolean> | Promise used to return the result. The value **true** means the OS account has been verified; the value **false** means the opposite.| **Example** @@ -3337,7 +3337,7 @@ Obtains the OS account ID based on the domain account information. This API uses | Type | Description | | :-------------------- | :------------------------------------- | -| Promise<number> | Promise used to return the OS account ID obtained.| +| Promise<number> | Promise used to return the ID of the OS account associated with the domain account.| **Example** @@ -3985,7 +3985,7 @@ Obtains the executor property based on the request. This API uses a promise to r ### setProperty8+ -setProperty(request: SetPropertyRequest, callback: AsyncCallback<number>): void; +setProperty(request: SetPropertyRequest, callback: AsyncCallback<void>): void; Sets the property for the initialization algorithm. This API uses an asynchronous callback to return the result. @@ -4000,7 +4000,7 @@ Sets the property for the initialization algorithm. This API uses an asynchronou | Name | Type | Mandatory| Description | | -------- | ----------------------------------------------------- | ---- | ---------------------------------------------------------------------- | | 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.| +| 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** @@ -4018,9 +4018,12 @@ Sets the property for the initialization algorithm. This API uses an asynchronou setInfo: new Uint8Array([0]) }; try { - userAuth.setProperty(request, (err, result) => { - console.log('setProperty error = ' + JSON.stringify(err)); - console.log('setProperty result = ' + JSON.stringify(result)); + userAuth.setProperty(request, (err) => { + if (err) { + console.log('setProperty failed, error = ' + JSON.stringify(err)); + } else { + console.log('setProperty successfully'); + } }); } catch (e) { console.log('setProperty exception = ' + JSON.stringify(e)); @@ -4029,7 +4032,7 @@ Sets the property for the initialization algorithm. This API uses an asynchronou ### setProperty8+ -setProperty(request: SetPropertyRequest): Promise<number>; +setProperty(request: SetPropertyRequest): Promise<void>; Sets the property for the initialization algorithm. This API uses a promise to return the result. @@ -4049,7 +4052,7 @@ Sets the property for the initialization algorithm. This API uses a promise to r | Type | Description | | :-------------------- | :------------------------------------------------------------ | -| Promise<number> | Promise used to return the [result code](#resultcode8).| +| Promise<void> | Promise that returns no value.| **Error codes** @@ -4067,10 +4070,10 @@ Sets the property for the initialization algorithm. This API uses a promise to r setInfo: new Uint8Array([0]) }; try { - userAuth.setProperty(request).then((result) => { - console.log('setProperty result = ' + JSON.stringify(result)); + userAuth.setProperty(request).then(() => { + console.log('setProperty successfully'); }).catch((err) => { - console.log('setProperty error = ' + JSON.stringify(err)); + console.log('setProperty failed, error = ' + JSON.stringify(err)); }); } catch (e) { console.log('setProperty exception = ' + JSON.stringify(e)); @@ -4081,7 +4084,7 @@ Sets the property for the initialization algorithm. This API uses a promise to r auth(challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; -Performs authentication for the current user. This API uses a callback to return the result. +Performs authentication of the current user. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -4139,7 +4142,7 @@ Performs authentication for the current user. This API uses a callback to return authUser(userId: number, challenge: Uint8Array, authType: AuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array; -Performs authentication for a user. This API uses an asynchronous callback to return the result. +Performs authentication of the specified user. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -4277,17 +4280,12 @@ Register a PIN inputer. | ----------| ----------------------- | --- | -------------------------- | | inputer | [IInputer](#iinputer8) | Yes | PIN inputer, which is used to obtain the PIN.| -**Return value** - -| Type | Description | -| :------ | :-------------------------------------------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Error codes** | ID| Error Message | | -------- | --------------------------- | | 12300001 | System service exception. | +| 12300102 | Invalid inputer. | | 12300103 | Inputer already registered. | **Example** @@ -4296,8 +4294,8 @@ Register a PIN inputer. let password = new Uint8Array([0, 0, 0, 0, 0]); try { let result = pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); console.log('registerInputer result = ' + result); @@ -4324,6 +4322,91 @@ Unregisters this PIN inputer. pinAuth.unregisterInputer(); ``` +### InputerManager 10+ + +Provides APIs for managing credential inputers. + +### registerInputer10+ + +registerInputer(authType: AuthType, inputer: IInputer): void; + +Register a credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| +| inputer | [IInputer](#iinputer8) | Yes | Credential inputer to register.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300001 | System service exception. | +| 12300102 | Invalid authType or inputer. | +| 12300103 | The credential inputer has been registered. | +| 12300106 | Unsupported authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + let password = new Uint8Array([0, 0, 0, 0, 0]); + try { + InputerMgr.registerInputer(authType, { + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); + } + }); + console.log('registerInputer success.'); + } catch (e) { + console.log('registerInputer exception = ' + JSON.stringify(e)); + } + ``` + +### unregisterInputer10+ + +unregisterInputer(authType: AuthType): void; + +Unregisters this credential inputer. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Account.OsAccount + +**Required permissions**: ohos.permission.ACCESS_USER_AUTH_INTERNAL or ohos.permission.MANAGE_USER_IDM + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------| ----------------------- | --- | -------------------------- | +| authType | [AuthType](#authtype8) | Yes | Authentication credential type.| + +**Error codes** + +| ID| Error Message | +| -------- | --------------------------- | +| 12300002 | Invalid authType. | + +**Example** + ```js + let inputerMgr = new account_osAccount.InputerManager(); + let authType = account_osAccount.AuthType.DOMAIN; + try { + inputerMgr.unregisterInputer(authType); + console.log('unregisterInputer success.'); + } catch(err) { + console.log("unregisterInputer err:" + JSON.stringify(err)); + } + ``` + ## UserIdentityManager8+ Provides APIs for user identity management (IDM). @@ -4453,8 +4536,8 @@ Adds credential information, including the credential type, subtype, and token ( let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let pinAuth = new account_osAccount.PINAuth(); pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); let credentialInfo = { @@ -4467,12 +4550,12 @@ Adds credential information, including the credential type, subtype, and token ( try { userIDM.addCredential(credentialInfo, { onResult: (result, extraInfo) => { - console.log('updateCredential result = ' + result); - console.log('updateCredential extraInfo = ' + extraInfo); + console.log('addCredential result = ' + result); + console.log('addCredential extraInfo = ' + extraInfo); } }); } catch (e) { - console.log('updateCredential exception = ' + JSON.stringify(e)); + console.log('addCredential exception = ' + JSON.stringify(e)); } }); ``` @@ -4493,7 +4576,7 @@ Updates credential information. This API uses a callback to return the result. | Name | Type | Mandatory| Description | | --------------- | ------------------------------------- | --- | ------------------------- | -| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | New credential information. | +| credentialInfo | [CredentialInfo](#credentialinfo8) | Yes | New credential information. | | callback | [IIdmCallback](#iidmcallback8) | Yes | Callback invoked to return the new credential information.| **Error codes** @@ -4517,8 +4600,8 @@ Updates credential information. This API uses a callback to return the result. token: null }; pinAuth.registerInputer({ - onGetData: (pinSubType, callback) => { - callback.onSetData(pinSubType, password); + onGetData: (authSubType, callback) => { + callback.onSetData(authSubType, password); } }); userIDM.openSession((err, challenge) => { @@ -4701,7 +4784,7 @@ Obtains authentication information. This API uses an asynchronous callback to re | 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.| +| callback | AsyncCallback<Array<[EnrolledCredInfo](#enrolledcredinfo8)>> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **null** and **data** is information about all registered credentials of the user. Otherwise, **err** is an error object.| **Error codes** @@ -4817,7 +4900,7 @@ Provides callbacks for PIN operations. ### onSetData8+ -onSetData: (pinSubType: AuthSubType, data: Uint8Array) => void; +onSetData: (authSubType: AuthSubType, data: Uint8Array) => void; **System API**: This is a system API. @@ -4829,7 +4912,7 @@ Called to set data in a PIN operation. | Name | Type | Mandatory| Description | | ---------- | ---------------------------------------- | ---- | ----------------------------------------------- | -| pinSubType | [AuthSubType](#authsubtype8) | Yes | Credential subtype. | +| authSubType | [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** @@ -4837,11 +4920,11 @@ Called to set data in a PIN operation. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -4849,13 +4932,13 @@ Called to set data in a PIN operation. ## IInputer8+ -Provides callbacks for the PIN input box. +Provides callbacks for credential inputers. **System API**: This is a system API. ### onGetData8+ -onGetData: (pinSubType: AuthSubType, callback: IInputData) => void; +onGetData: (authSubType: AuthSubType, callback: IInputData) => void; Called to obtain data. @@ -4874,11 +4957,11 @@ Called to obtain data. let password = new Uint8Array([0, 0, 0, 0, 0, 0]); let passwordNumber = new Uint8Array([1, 2, 3, 4]); let inputer = { - onGetData: (pinSubType, callback) => { - if (pinSubType == account_osAccount.AuthSubType.PIN_NUMBER) { - callback.onSetData(pinSubType, passwordNumber); + onGetData: (authSubType, callback) => { + if (authSubType == account_osAccount.AuthSubType.PIN_NUMBER) { + callback.onSetData(authSubType, passwordNumber); } else { - callback.onSetData(pinSubType, password); + callback.onSetData(authSubType, password); } } }; @@ -4974,7 +5057,7 @@ Called to return the result code and request result information. | Name | Type | Mandatory| Description | | --------- | --------------------------------------- | ---- | ----------------------- | | result | number | Yes | Authentication result code. | -| extraInfo | [AuthResult](#authresult8) | Yes | Specific information to be transferred.| +| extraInfo | [RequestResult](#requestresult8) | Yes | Specific information to be transferred.| **Example** ```js @@ -5124,7 +5207,7 @@ Enumerates the types of properties to obtain. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ------------- | ------ | --------- | | AUTH_SUB_TYPE | 1 | Authentication credential subtype.| | REMAIN_TIMES | 2 | Remaining time. | @@ -5138,7 +5221,7 @@ Enumerates the types of properties to set. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | -------------- | ----- | ----------- | | INIT_ALGORITHM | 1 | Initialization algorithm.| @@ -5150,10 +5233,12 @@ Enumerates the authentication credential types. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----- | ----- | ---------------- | | PIN | 1 | PIN authentication.| | FACE | 2 | Facial authentication.| +| FINGERPRINT10+ | 4 | Fingerprint authentication.| +| DOMAIN10+ | 1024 | Domain authentication.| ## AuthSubType8+ @@ -5163,13 +5248,14 @@ Enumerates the authentication credential subtypes. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ---------- | ----- | ------------------ | | PIN_SIX | 10000 | Six-digit PIN. | | PIN_NUMBER | 10001 | Custom PIN.| -| PIN_MIXED | 10002 | Custom mixed credential.| +| PIN_MIXED | 10002 | Custom mixed credentials.| | FACE_2D | 20000 | 2D face credential. | | FACE_3D | 20001 | 3D face credential. | +| DOMAIN_MIXED10+ | 10240001 | Mixed domain authentication credentials. | ## AuthTrustLevel8+ @@ -5179,7 +5265,7 @@ Enumerates the trust levels of the authentication result. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ---- | ------ | ----------- | | ATL1 | 10000 | Trust level 1.| | ATL2 | 20000 | Trust level 2.| @@ -5194,7 +5280,7 @@ Enumerates the modules from which information is obtained. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | --------- | ------ | ------------------------ | | FACE_AUTH | 1 | Facial authentication module.| @@ -5206,7 +5292,7 @@ Enumerates the authentication result codes. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------- | ----- | ---------------------------------------- | | SUCCESS | 0 | The authentication is successful or the authentication feature is supported. | | FAIL | 1 | The authentication executor failed to identify the user. | @@ -5228,7 +5314,7 @@ Enumerates the tip codes for facial authentication. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------------- | ----- | ---------------------------------------- | | FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained face image is too bright. | | FACE_AUTH_TIP_TOO_DARK | 2 | The obtained face image is too dark. | @@ -5250,7 +5336,7 @@ Enumerates the tip codes for fingerprint authentication. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------------- | ----- | ----------------------------------------------- | | FINGERPRINT_TIP_GOOD | 0 | The captured image is clear. | | FINGERPRINT_TIP_IMAGER_DIRTY | 1 | The fingerprint image has big noise due to dirt on the sensor.| @@ -5381,10 +5467,9 @@ Enumerates the constraint sources. **System capability**: SystemCapability.Account.OsAccount -| Name | Default Value| Description | +| Name | Value| Description | | ------ | ------ | ------------ | | CONSTRAINT_NOT_EXIST | 0 | The constraint does not exist.| | CONSTRAINT_TYPE_BASE | 1 | Constraint from system settings. | | CONSTRAINT_TYPE_DEVICE_OWNER | 2 | Constraint from the device owners' settings. | | CONSTRAINT_TYPE_PROFILE_OWNER | 3 | Constraint from the profile owners' settings. | - diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index be28e4b7590f1671660228d3e78f2e822451a847..ee53667d0158343624ab086abe598a8baa9608c0 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -12,25 +12,37 @@ The **pasteboard** module provides the copy and paste support for the system pas import pasteboard from '@ohos.pasteboard'; ``` -## Attributes +## Constants **System capability**: SystemCapability.MiscServices.Pasteboard -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| MAX_RECORD_NUM7+ | number | Yes| No| Maximum number of records in a **PasteData** object.| -| MIMETYPE_TEXT_HTML7+ | string | Yes| No| MIME type of the HTML content.| -| MIMETYPE_TEXT_WANT7+ | string | Yes| No| MIME type of the Want content.| -| MIMETYPE_TEXT_PLAIN7+ | string | Yes| No| MIME type of the plain text content.| -| MIMETYPE_TEXT_URI7+ | string | Yes| No| MIME type of the URI content.| -| MIMETYPE_PIXELMAP9+ | string | Yes| No| MIME type of the pixel map.| +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| MAX_RECORD_NUM7+ | number | 512 | Maximum number of records in a **PasteData** object.| +| MIMETYPE_TEXT_HTML7+ | string | 'text/html' | MIME type of the HTML content.| +| MIMETYPE_TEXT_WANT7+ | string | 'text/want' | MIME type of the Want content.| +| MIMETYPE_TEXT_PLAIN7+ | string | 'text/plain' | MIME type of the plain text content.| +| MIMETYPE_TEXT_URI7+ | string | 'text/uri' | MIME type of the URI content.| +| MIMETYPE_PIXELMAP9+ | string | 'pixelMap' | MIME type of the pixel map.| +## ValueType9+ -## pasteboard.createPlainTextData +Enumerates the value types. -createPlainTextData(text: string): PasteData +**System capability**: SystemCapability.MiscServices.Pasteboard -Creates a **PasteData** object of the plain text type. +| Type| Description| +| -------- | -------- | +| string | The value is a string.| +| image.PixelMap | The value is of the [image.PixelMap](js-apis-image.md#pixelmap7) type.| +| Want | The value is of the [Want](js-apis-app-ability-want.md) type.| +| ArrayBuffer | The value is of the **ArrayBuffer** type.| + +## pasteboard.createData9+ + +createData(mimeType: string, value: ValueType): PasteData + +Creates a **PasteData** object of a custom type. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -38,26 +50,27 @@ Creates a **PasteData** object of the plain text type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| text | string | Yes| Plain text.| +| mimeType | string | Yes| MIME type of custom data.| +| value | [ValueType](#valuetype9) | Yes| Content of custom data.| **Return value** | Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object.| +| [PasteData](#pastedata) | **PasteData** object.| **Example** -```js -var pasteData = pasteboard.createPlainTextData("content"); -``` - + ```js + let dataXml = new ArrayBuffer(256); + let pasteData = pasteboard.createData('app/xml', dataXml); + ``` -## pasteboard.createHtmlData7+ +## pasteboard.createRecord9+ -createHtmlData(htmlText: string): PasteData +createRecord(mimeType: string, value: ValueType):PasteDataRecord; -Creates a **PasteData** object of the HTML type. +Creates a **PasteDataRecord** object of the custom type. **System capability**: SystemCapability.MiscServices.Pasteboard @@ -65,58 +78,62 @@ Creates a **PasteData** object of the HTML type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| htmlText | string | Yes| HTML content.| +| mimeType | string | Yes| MIME type of custom data.| +| value | [ValueType](#valuetype9) | Yes| Content of custom data.| **Return value** | Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object.| +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the custom type.| **Example** -```js -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -var pasteData = pasteboard.createHtmlData(html); -``` - + ```js + let dataXml = new ArrayBuffer(256); + let pasteDataRecord = pasteboard.createRecord('app/xml', dataXml); + ``` -## pasteboard.createWantData7+ +## pasteboard.getSystemPasteboard -createWantData(want: Want): PasteData +getSystemPasteboard(): SystemPasteboard -Creates a **PasteData** object of the Want type. +Obtains this **SystemPasteboard** object. **System capability**: SystemCapability.MiscServices.Pasteboard -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want content.| - **Return value** | Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object.| +| [SystemPasteboard](#systempasteboard) | **SystemPasteboard** object.| **Example** ```js -var object = { - bundleName: "com.example.aafwk.test", - abilityName: "com.example.aafwk.test.TwoAbility" -}; -var pasteData = pasteboard.createWantData(object); +let systemPasteboard = pasteboard.getSystemPasteboard(); ``` +## ShareOption9+ -## pasteboard.createUriData7+ +Enumerates the paste options of data. -createUriData(uri: string): PasteData +**System capability**: SystemCapability.MiscServices.Pasteboard -Creates a **PasteData** object of the URI type. +| Name | Description | +| ----- | ----------------------- | +| InApp |Only intra-application pasting is allowed.| +| LocalDevice |Paste is allowed in any application on the local device.| +| CrossDevice |Paste is allowed in any application across devices.| + +## pasteboard.createHtmlData(deprecated) + +createHtmlData(htmlText: string): PasteData + +Creates a **PasteData** object of the HTML type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -124,7 +141,7 @@ Creates a **PasteData** object of the URI type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uri | string | Yes| URI content.| +| htmlText | string | Yes| HTML content.| **Return value** @@ -135,15 +152,18 @@ Creates a **PasteData** object of the URI type. **Example** ```js -var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); +let html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; +let pasteData = pasteboard.createHtmlData(html); ``` +## pasteboard.createWantData(deprecated) -## pasteboard.createPixelMapData9+ - -createPixelMapData(pixelMap: image.PixelMap): PasteData +createWantData(want: Want): PasteData -Creates a **PasteData** object of the pixel map type. +Creates a **PasteData** object of the Want type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -151,7 +171,7 @@ Creates a **PasteData** object of the pixel map type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pixelMap | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Pixel map.| +| want | [Want](js-apis-app-ability-want.md) | Yes| Want content.| **Return value** @@ -162,26 +182,21 @@ Creates a **PasteData** object of the pixel map type. **Example** ```js -import image from '@ohos.multimedia.image'; - -var buffer = new ArrayBuffer(128) -var opt = { - size: { height: 3, width: 5 }, - pixelFormat: 3, - editable: true, - alphaType: 1, - scaleMode: 1 -} -image.createPixelMap(buffer, opt).then((pixelMap) => { - var pasteData = pasteboard.createPixelMapData(pixelMap); -}) +let object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" +}; +let pasteData = pasteboard.createWantData(object); ``` -## pasteboard.createData9+ +## pasteboard.createPlainTextData(deprecated) -createData(mimeType: string, value: ArrayBuffer): PasteData; +createPlainTextData(text: string): PasteData -Creates a **PasteData** object of a custom type. +Creates a **PasteData** object of the plain text type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -189,28 +204,28 @@ Creates a **PasteData** object of a custom type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mimeType | string | Yes| MIME type of custom data.| -| value | ArrayBuffer | Yes| Content of custom data.| +| text | string | Yes| Plain text.| **Return value** | Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object.| +| [PasteData](#pastedata) | **PasteData** object.| **Example** - ```js - var dataXml = new ArrayBuffer(256) - var pasteData = pasteboard.createData('app/xml', dataXml) - ``` - +```js +let pasteData = pasteboard.createPlainTextData('content'); +``` -## pasteboard.createPlainTextRecord7+ +## pasteboard.createUriData(deprecated) -createPlainTextRecord(text: string): PasteDataRecord +createUriData(uri: string): PasteData -Creates a **PasteDataRecord** object of the plain text type. +Creates a **PasteData** object of the URI type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createData](#pasteboardcreatedata9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -218,26 +233,27 @@ Creates a **PasteDataRecord** object of the plain text type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| text | string | Yes| Plain text.| +| uri | string | Yes| URI content.| **Return value** | Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the plain text type.| +| [PasteData](#pastedata) | **PasteData** object.| **Example** ```js -var record = pasteboard.createPlainTextRecord("hello"); +let pasteData = pasteboard.createUriData('dataability:///com.example.myapplication1/user.txt'); ``` - - -## pasteboard.createHtmlTextRecord7+ +## pasteboard.createHtmlTextRecord(deprecated) createHtmlTextRecord(htmlText: string): PasteDataRecord Creates a **PasteDataRecord** object of the HTML text type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -256,16 +272,18 @@ Creates a **PasteDataRecord** object of the HTML text type. **Example** ```js -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

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

HEAD

\n" + "

\n" + "\n" + ""; +let record = pasteboard.createHtmlTextRecord(html); ``` - -## pasteboard.createWantRecord7+ +## pasteboard.createWantRecord(deprecated) createWantRecord(want: Want): PasteDataRecord Creates a **PasteDataRecord** object of the Want type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -273,7 +291,7 @@ Creates a **PasteDataRecord** object of the Want type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| want | [Want](js-apis-application-Want.md) | Yes| Want content.| +| want | [Want](js-apis-app-ability-want.md) | Yes| Want content.| **Return value** @@ -284,46 +302,21 @@ Creates a **PasteDataRecord** object of the Want type. **Example** ```js -var object = { +let object = { bundleName: "com.example.aafwk.test", abilityName: "com.example.aafwk.test.TwoAbility" }; -var record = pasteboard.createWantRecord(object); -``` - - -## pasteboard.createUriRecord7+ - -createUriRecord(uri: string): PasteDataRecord - -Creates a **PasteDataRecord** object of the URI type. - -**System capability**: SystemCapability.MiscServices.Pasteboard - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| uri | string | Yes| URI content.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the URI type.| - -**Example** - -```js -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); +let record = pasteboard.createWantRecord(object); ``` +## pasteboard.createPlainTextRecord(deprecated) -## pasteboard.createPixelMapRecord9+ - -createPixelMapRecord(pixelMap: image.PixelMap): PasteDataRecord +createPlainTextRecord(text: string): PasteDataRecord -Creates a **PasteDataRecord** object of the pixel map type. +Creates a **PasteDataRecord** object of the plain text type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -331,37 +324,28 @@ Creates a **PasteDataRecord** object of the pixel map type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pixelMap | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| Pixel map.| +| text | string | Yes| Plain text.| **Return value** | Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the pixel map type.| +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the plain text type.| **Example** ```js -import image from '@ohos.multimedia.image'; - -var buffer = new ArrayBuffer(128) -var opt = { - size: { height: 3, width: 5 }, - pixelFormat: 3, - editable: true, - alphaType: 1, - scaleMode: 1 -} -image.createPixelMap(buffer, opt).then((pixelMap) => { - var record = pasteboard.createPixelMapRecord(pixelMap); -}) +let record = pasteboard.createPlainTextRecord('hello'); ``` -## pasteboard.createRecord9+ +## pasteboard.createUriRecord(deprecated) -createRecord(mimeType: string, value: ArrayBuffer):PasteDataRecord; +createUriRecord(uri: string): PasteDataRecord -Creates a **PasteDataRecord** object of the custom type. +Creates a **PasteDataRecord** object of the URI type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [pasteboard.createRecord](#pasteboardcreaterecord9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -369,55 +353,20 @@ Creates a **PasteDataRecord** object of the custom type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mimeType | string | Yes| MIME type of custom data.| -| value | ArrayBuffer | Yes| Content of custom data.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the custom type.| - -**Example** - - ```js - var dataXml = new ArrayBuffer(256) - var pasteDataRecord = pasteboard.createRecord('app/xml', dataXml); - ``` - - -## pasteboard.getSystemPasteboard - -getSystemPasteboard(): SystemPasteboard - -Obtains this **SystemPasteboard** object. - -**System capability**: SystemCapability.MiscServices.Pasteboard +| uri | string | Yes| URI content.| **Return value** | Type| Description| | -------- | -------- | -| [SystemPasteboard](#systempasteboard) | **SystemPasteboard** object.| +| [PasteDataRecord](#pastedatarecord7) | New **PasteDataRecord** object of the URI type.| **Example** ```js -var systemPasteboard = pasteboard.getSystemPasteboard(); +let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); ``` -## ShareOption9+ - -Enumerates the paste options of data. - -**System capability**: SystemCapability.MiscServices.Pasteboard - -| Name | Description | -| ----- | ----------------------- | -| InApp |Only intra-application pasting is allowed. | -| LocalDevice |Paste is allowed in any application on the local device. | -| CrossDevice |Paste is allowed in any application across devices. | - ## PasteDataProperty7+ @@ -434,12 +383,10 @@ Defines the properties of all data records on the pasteboard, including the time | localOnly7+ | boolean | Yes| Yes| Whether the pasteboard content is set for local access only. The default value is **true**.
- **true**: The pasteboard content is set for local access only.
- **false**: The pasteboard content can be shared between devices.| | shareOption9+ | [ShareOption](#shareoption9) | Yes| Yes| Where the pasteboard content can be pasted. If this attribute is set incorrectly or not set, the default value **CrossDevice** is used.| - ## PasteDataRecord7+ Provides **PasteDataRecord** APIs. A **PasteDataRecord** is an abstract definition of the content on the pasteboard. The pasteboard content consists of one or more plain text, HTML, URI, or Want records. - ### Attributes **System capability**: SystemCapability.MiscServices.Pasteboard @@ -447,17 +394,43 @@ Provides **PasteDataRecord** APIs. A **PasteDataRecord** is an abstract definiti | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | | htmlText7+ | string | Yes| No| HTML content.| -| want7+ | [Want](js-apis-application-Want.md) | Yes| No| Want content.| +| want7+ | [Want](js-apis-app-ability-want.md) | Yes| No| Want content.| | mimeType7+ | string | Yes| No| Data type.| | plainText7+ | string | Yes| No| Plain text.| | uri7+ | string | Yes| No| URI content.| | pixelMap9+ | [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| No| Pixel map.| -| data9+ | {[mimeType: string]: ArrayBuffer} | Yes| No| Content of custom data.| +| data9+ | {[mimeType: string]: ArrayBuffer} | Yes| No| Content of custom data.| +### convertToTextV99+ -### convertToText7+ +convertToTextV9(callback: AsyncCallback<string>): void -convertToText(): Promise<string> +Forcibly converts the content in a **PasteData** object to text. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the text obtained from the conversion. Otherwise, **err** is error information.| + +**Example** + +```js +let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +record.convertToTextV9((err, data) => { + if (err) { + console.error(`Failed to convert to text. Cause: ${err.message}`); + return; + } + console.info(`Succeeded in converting to text. Data: ${data}`); +}); +``` + +### convertToTextV99+ + +convertToTextV9(): Promise<string> Forcibly converts the content in a **PasteData** object to text. This API uses a promise to return the result. @@ -472,20 +445,22 @@ Forcibly converts the content in a **PasteData** object to text. This API uses a **Example** ```js -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); -record.convertToText().then((data) => { - console.info('Succeeded in converting to text. Data: ' + JSON.stringify(data)); +let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +record.convertToTextV9().then((data) => { + console.info(`Succeeded in converting to text. Data: ${data}`); }).catch((err) => { - console.error('Failed to convert to text. Cause: ' + JSON.stringify(err)); + console.error(`Failed to convert to text. Cause: ${err.message}`); }); ``` - -### convertToText7+ +### convertToText(deprecated) convertToText(callback: AsyncCallback<string>): void Forcibly converts the content in a **PasteData** object to text. 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 [convertToTextV9](#converttotextv99). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -498,16 +473,43 @@ Forcibly converts the content in a **PasteData** object to text. This API uses a **Example** ```js -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); +let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); record.convertToText((err, data) => { if (err) { - console.error('Failed to convert to text. Cause: ' + JSON.stringify(err)); + console.error(`Failed to convert to text. Cause: ${err.message}`); return; } - console.info('Succeeded in converting to text. Data: ' + JSON.stringify(data)); + console.info(`Succeeded in converting to text. Data: ${data}`); }); ``` +### convertToText(deprecated) + +convertToText(): Promise<string> + +Forcibly converts the content in a **PasteData** object to text. 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 [convertToTextV9](#converttotextv99-1). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the text obtained from the conversion.| + +**Example** + +```js +let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +record.convertToText().then((data) => { + console.info(`Succeeded in converting to text. Data: ${data}`); +}).catch((err) => { + console.error(`Failed to convert to text. Cause: ${err.message}`); +}); +``` ## PasteData @@ -517,18 +519,14 @@ Before calling any **PasteData** API, you must obtain a **PasteData** object. **System capability**: SystemCapability.MiscServices.Pasteboard - ### getPrimaryText - getPrimaryText(): string - Obtains the plain text of the primary record. **System capability**: SystemCapability.MiscServices.Pasteboard - **Return value** | Type| Description| @@ -538,11 +536,10 @@ Obtains the plain text of the primary record. **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var plainText = pasteData.getPrimaryText(); +let pasteData = pasteboard.createPlainTextData('hello'); +let plainText = pasteData.getPrimaryText(); ``` - ### getPrimaryHtml7+ getPrimaryHtml(): string @@ -560,12 +557,11 @@ Obtains the HTML content of the primary record. **Example** ```js -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

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

HEAD

\n" + "

\n" + "\n" + ""; +let pasteData = pasteboard.createHtmlData(html); +let htmlText = pasteData.getPrimaryHtml(); ``` - ### getPrimaryWant7+ getPrimaryWant(): Want @@ -578,20 +574,19 @@ Obtains the Want object of the primary record. | Type| Description| | -------- | -------- | -| [Want](js-apis-application-Want.md) | Want object.| +| [Want](js-apis-app-ability-want.md) | Want object.| **Example** ```js -var object = { - bundleName: "com.example.aafwk.test", +let object = { + bundleName: "com.example.aafwk.test", abilityName: "com.example.aafwk.test.TwoAbility" }; -var pasteData = pasteboard.createWantData(object); -var want = pasteData.getPrimaryWant(); +let pasteData = pasteboard.createWantData(object); +let want = pasteData.getPrimaryWant(); ``` - ### getPrimaryUri7+ getPrimaryUri(): string @@ -609,11 +604,10 @@ Obtains the URI of the primary record. **Example** ```js -var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); -var uri = pasteData.getPrimaryUri(); +let pasteData = pasteboard.createUriData('dataability:///com.example.myapplication1/user.txt'); +let uri = pasteData.getPrimaryUri(); ``` - ### getPrimaryPixelMap9+ getPrimaryPixelMap(): image.PixelMap @@ -633,26 +627,25 @@ Obtains the pixel map of the primary record. ```js import image from '@ohos.multimedia.image'; -var buffer = new ArrayBuffer(128) -var opt = { +let buffer = new ArrayBuffer(128); +let opt = { size: { height: 3, width: 5 }, pixelFormat: 3, editable: true, alphaType: 1, scaleMode: 1 -} +}; image.createPixelMap(buffer, opt).then((pixelMap) => { - var pasteData = pasteboard.createPixelMapData(pixelMap); - var pixelMap = pasteData.getPrimaryPixelMap(); -}) + let pasteData = pasteboard.createData('app/xml',pixelMap); + let PixelMap = pasteData.getPrimaryPixelMap(); +}); ``` +### addRecord7+ -### addTextRecord7+ - -addTextRecord(text: string): void +addRecord(record: PasteDataRecord): void -Adds a plain text record to this pasteboard, and adds **MIME_TEXT_PLAIN** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. +Adds a data record to this pasteboard, and adds its type to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. The pasteboard supports a maximum number of 512 data records. @@ -662,130 +655,21 @@ The pasteboard supports a maximum number of 512 data records. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| text | string | Yes| Plain text.| +| record | [PasteDataRecord](#pastedatarecord7) | Yes| Record to add.| **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -pasteData.addTextRecord("good"); -``` - - -### addHtmlRecord7+ - -addHtmlRecord(htmlText: string): void - -Adds an HTML record to this pasteboard, and adds **MIMETYPE_TEXT_HTML** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. - -The pasteboard supports a maximum number of 512 data records. - -**System capability**: SystemCapability.MiscServices.Pasteboard - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| htmlText | string | Yes| HTML content.| - -**Example** - -```js -var pasteData = pasteboard.createPlainTextData("hello"); -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

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

HEAD

\n" + "

\n" + "\n" + ""; +let htmlRecord = pasteboard.createHtmlTextRecord(html); +pasteData.addRecord(textRecord); +pasteData.addRecord(htmlRecord); ``` - - ### addRecord9+ -addRecord(mimeType: string, value: ArrayBuffer): void +addRecord(mimeType: string, value: ValueType): void Adds a custom-type record to this pasteboard, and adds the custom type to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. @@ -798,44 +682,23 @@ The pasteboard supports a maximum number of 512 data records. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | mimeType | string | Yes| MIME type of custom data.| -| value | ArrayBuffer | Yes| Content of custom data.| +| value | [ValueType](#valuetype9) | Yes| Content of custom data.| -**Example** - - ```js - var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); - var dataXml = new ArrayBuffer(256) - pasteData.addRecord('app/xml', dataXml); - ``` - - -### addRecord7+ - -addRecord(record: PasteDataRecord): void - -Adds a data record to this pasteboard, and adds its type to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. - -The pasteboard supports a maximum number of 512 data records. - -**System capability**: SystemCapability.MiscServices.Pasteboard +**Error codes** -**Parameters** +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| record | [PasteDataRecord](#pastedatarecord7) | Yes| Record to add.| +| Error Code ID| Error Message| +| -------- | -------- | +| 12900002 | The number of record exceeds the maximum limit. | **Example** -```js -var pasteData = pasteboard.createUriData("dataability:///com.example.myapplication1/user.txt"); -var textRecord = pasteboard.createPlainTextRecord("hello"); -var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; -var htmlRecord = pasteboard.createHtmlTextRecord(html); -pasteData.addRecord(textRecord); -pasteData.addRecord(htmlRecord); -``` - + ```js + let pasteData = pasteboard.createUriData('dataability:///com.example.myapplication1/user.txt'); + let dataXml = new ArrayBuffer(256); + pasteData.addRecord('app/xml', dataXml); + ``` ### getMimeTypes7+ @@ -854,11 +717,10 @@ Obtains a list of **mimeTypes** objects in [PasteDataProperty](#pastedatapropert **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var types = pasteData.getMimeTypes(); +let pasteData = pasteboard.createPlainTextData('hello'); +let types = pasteData.getMimeTypes(); ``` - ### getPrimaryMimeType7+ getPrimaryMimeType(): string @@ -876,11 +738,10 @@ Obtains the data type of the primary record in this pasteboard. **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var type = pasteData.getPrimaryMimeType(); +let pasteData = pasteboard.createPlainTextData('hello'); +let type = pasteData.getPrimaryMimeType(); ``` - ### getProperty7+ getProperty(): PasteDataProperty @@ -898,11 +759,10 @@ Obtains the property of the pasteboard data. **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var property = pasteData.getProperty(); +let pasteData = pasteboard.createPlainTextData('hello'); +let property = pasteData.getProperty(); ``` - ### setProperty9+ setProperty(property: PasteDataProperty): void @@ -920,16 +780,15 @@ Sets the property (attributes) for the pasteboard data. Currently, only the **sh **Example** ```js -var pasteData = pasteboard.createHtmlData('application/xml'); +let pasteData = pasteboard.createHtmlData('application/xml'); let prop = pasteData.getProperty(); prop.shareOption = pasteboard.ShareOption.InApp; pasteData.setProperty(prop); ``` +### getRecord9+ -### getRecordAt7+ - -getRecordAt(index: number): PasteDataRecord +getRecord(index: number): PasteDataRecord Obtains the specified record in the pasteboard. @@ -947,14 +806,21 @@ Obtains the specified record in the pasteboard. | -------- | -------- | | [PasteDataRecord](#pastedatarecord7) | Record with the specified index.| +**Error codes** + +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 12900001 | The index is out of range. | + **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var record = pasteData.getRecordAt(0); +let pasteData = pasteboard.createPlainTextData('hello'); +let record = pasteData.getRecord(0); ``` - ### getRecordCount7+ getRecordCount(): number @@ -972,11 +838,10 @@ Obtains the number of records in the pasteboard. **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var count = pasteData.getRecordCount(); +let pasteData = pasteboard.createPlainTextData('hello'); +let count = pasteData.getRecordCount(); ``` - ### getTag7+ getTag(): string @@ -994,14 +859,13 @@ Obtains the custom tag from the pasteboard. If no custom tag is set, null is ret **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var tag = pasteData.getTag(); +let pasteData = pasteboard.createPlainTextData('hello'); +let tag = pasteData.getTag(); ``` +### hasType9+ -### hasMimeType7+ - -hasMimeType(mimeType: string): boolean +hasType(mimeType: string): boolean Checks whether the pasteboard contains data of the specified type. @@ -1022,14 +886,13 @@ Checks whether the pasteboard contains data of the specified type. **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); +let pasteData = pasteboard.createPlainTextData('hello'); +let hasType = pasteData.hasType(pasteboard.MIMETYPE_TEXT_PLAIN); ``` +### removeRecord9+ -### removeRecordAt7+ - -removeRecordAt(index: number): boolean +removeRecord(index: number): void Removes the record with the specified index from the pasteboard. @@ -1041,23 +904,24 @@ Removes the record with the specified index from the pasteboard. | -------- | -------- | -------- | -------- | | index | number | Yes| Specified index.| -**Return value** +**Error codes** -| Type| Description| +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). + +| Error Code ID| Error Message| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| 12900001 | The index is out of range. | **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var isRemove = pasteData.removeRecordAt(0); +let pasteData = pasteboard.createPlainTextData('hello'); +pasteData.removeRecord(0); ``` +### replaceRecord9+ -### replaceRecordAt7+ - -replaceRecordAt(index: number, record: PasteDataRecord): boolean +replaceRecord(index: number, record: PasteDataRecord): void Replaces the record with the specified index in the pasteboard with a new record. @@ -1070,36 +934,58 @@ Replaces the record with the specified index in the pasteboard with a new record | index | number | Yes| Specified index.| | record | [PasteDataRecord](#pastedatarecord7) | Yes| New record.| -**Return value** +**Error codes** -| Type| Description| +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). + +| Error Code ID| Error Message| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| 12900001 | The index is out of range. | **Example** ```js -var pasteData = pasteboard.createPlainTextData("hello"); -var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); -var isReplace = pasteData.replaceRecordAt(0, record); +let pasteData = pasteboard.createPlainTextData('hello'); +let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +pasteData.replaceRecord(0, record); ``` +### addHtmlRecord(deprecated) -## SystemPasteboard +addHtmlRecord(htmlText: string): void -Provides **SystemPasteboard** APIs. +Adds an HTML record to this pasteboard, and adds **MIMETYPE_TEXT_HTML** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -Before calling any **SystemPasteboard** API, you must obtain a **SystemPasteboard** object using [getSystemPasteboard](#pasteboardgetsystempasteboard). +The pasteboard supports a maximum number of 512 data records. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| htmlText | string | Yes| HTML content.| + +**Example** ```js -var systemPasteboard = pasteboard.getSystemPasteboard(); +let pasteData = pasteboard.createPlainTextData('hello'); +let html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

\n" + "\n" + ""; +pasteData.addHtmlRecord(html); ``` +### addWantRecord(deprecated) -### setPasteData +addWantRecord(want: Want): void -setPasteData(data: PasteData, callback: AsyncCallback<void>): void +Adds a Want record to this pasteboard, and adds **MIMETYPE_TEXT_WANT** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -Writes a **PasteData** object to the pasteboard. This API uses an asynchronous callback to return the result. +The pasteboard supports a maximum number of 512 data records. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1107,62 +993,55 @@ Writes a **PasteData** object to the pasteboard. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| data | [PasteData](#pastedata) | Yes| **PasteData** object.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| +| want | [Want](js-apis-app-ability-want.md) | Yes| Want object.| **Example** ```js -var pasteData = pasteboard.createPlainTextData("content"); -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.setPasteData(pasteData, (err, data) => { - if (err) { - console.error('Failed to set PasteData. Cause: ' + err.message); - return; - } - console.info('Succeeded in setting PasteData.'); -}); +let pasteData = pasteboard.createPlainTextData('hello'); +let object = { + bundleName: "com.example.aafwk.test", + abilityName: "com.example.aafwk.test.TwoAbility" +}; +pasteData.addWantRecord(object); ``` +### addTextRecord(deprecated) -### setPasteData +addTextRecord(text: string): void -setPasteData(data: PasteData): Promise<void> +Adds a plain text record to this pasteboard, and adds **MIME_TEXT_PLAIN** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -Writes a **PasteData** object to the pasteboard. This API uses a promise to return the result. +The pasteboard supports a maximum number of 512 data records. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name| Type| Description| -| -------- | -------- | -------- | -| data | [PasteData](#pastedata) | **PasteData** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<void> | Promise that returns no value.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| text | string | Yes| Plain text.| **Example** ```js -var pasteData = pasteboard.createPlainTextData("content"); -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.setPasteData(pasteData).then((data) => { - console.info('Succeeded in setting PasteData.'); -}).catch((err) => { - console.error('Failed to set PasteData. Cause: ' + err.message); -}); +let pasteData = pasteboard.createPlainTextData('hello'); +pasteData.addTextRecord('good'); ``` +### addUriRecord(deprecated) -### getPasteData +addUriRecord(uri: string): void -getPasteData( callback: AsyncCallback<PasteData>): void +Adds a URI record to this pasteboard, and adds **MIMETYPE_TEXT_URI** to **mimeTypes** in [PasteDataProperty](#pastedataproperty7). The parameters cannot be empty. Otherwise, the operation fails. -Obtains a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result. +The pasteboard supports a maximum number of 512 data records. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addRecord](#addrecord9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1170,53 +1049,52 @@ Obtains a **PasteData** object from the pasteboard. This API uses an asynchronou | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[PasteData](#pastedata)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the system pasteboard data. Otherwise, **err** is an error object.| +| uri | string | Yes| URI content.| **Example** ```js -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.getPasteData((err, pasteData) => { - if (err) { - console.error('Failed to get PasteData. Cause: ' + err.message); - return; - } - var text = pasteData.getPrimaryText(); -}); +let pasteData = pasteboard.createPlainTextData('hello'); +pasteData.addUriRecord('dataability:///com.example.myapplication1/user.txt'); ``` +### getRecordAt(deprecated) +getRecordAt(index: number): PasteDataRecord -### getPasteData +Obtains the specified record in the pasteboard. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getRecord](#getrecord9). -getPasteData(): Promise<PasteData> +**System capability**: SystemCapability.MiscServices.Pasteboard -Obtains a **PasteData** object from the pasteboard. This API uses a promise to return the result. +**Parameters** -**System capability**: SystemCapability.MiscServices.Pasteboard +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| index | number | Yes| Index of the target record.| **Return value** | Type| Description| | -------- | -------- | -| Promise<[PasteData](#pastedata)> | Promise used to return the system pasteboard data.| +| [PasteDataRecord](#pastedatarecord7) | Record with the specified index.| **Example** ```js -var systemPasteboard = pasteboard.getSystemPasteboard(); -systemPasteboard.getPasteData().then((pasteData) => { - var text = pasteData.getPrimaryText(); -}).catch((err) => { - console.error('Failed to get PasteData. Cause: ' + err.message); -}) +let pasteData = pasteboard.createPlainTextData('hello'); +let record = pasteData.getRecordAt(0); ``` +### hasMimeType(deprecated) -### on('update')7+ - -on(type: 'update', callback: () =>void ): void +hasMimeType(mimeType: string): boolean -Subscribes to the content change event of the system pasteboard. +Checks whether the pasteboard contains data of the specified type. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [hasType](#hastype9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1224,19 +1102,115 @@ Subscribes to the content change event of the system pasteboard. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value **'update'** indicates changes in the pasteboard content.| -| callback | function | Yes| Callback invoked when the pasteboard content changes.| +| mimeType | string | Yes| Type of the data to query.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the specified data type exists; returns **false** otherwise.| **Example** ```js -var systemPasteboard = pasteboard.getSystemPasteboard(); -var listener = () => { - console.info('The system pasteboard has changed.'); -}; -systemPasteboard.on('update', listener); +let pasteData = pasteboard.createPlainTextData('hello'); +let hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); ``` +### removeRecordAt(deprecated) +removeRecordAt(index: number): boolean + +Removes the record with the specified index from the pasteboard. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeRecord](#removerecord9). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| index | number | Yes| Specified index.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let pasteData = pasteboard.createPlainTextData('hello'); +let isRemove = pasteData.removeRecordAt(0); +``` +### replaceRecordAt(deprecated) + +replaceRecordAt(index: number, record: PasteDataRecord): boolean + +Replaces the record with the specified index in the pasteboard with a new record. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [replaceRecord](#replacerecord9). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| index | number | Yes| Specified index.| +| record | [PasteDataRecord](#pastedatarecord7) | Yes| New record.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + +```js +let pasteData = pasteboard.createPlainTextData('hello'); +let record = pasteboard.createUriRecord('dataability:///com.example.myapplication1/user.txt'); +let isReplace = pasteData.replaceRecordAt(0, record); +``` + +## SystemPasteboard + +Provides **SystemPasteboard** APIs. + +Before calling any **SystemPasteboard** API, you must obtain a **SystemPasteboard** object using [getSystemPasteboard](#pasteboardgetsystempasteboard). + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +``` + +### on('update')7+ + +on(type: 'update', callback: () =>void ): void + +Subscribes to the content change event of the system pasteboard. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value **'update'** indicates changes in the pasteboard content.| +| callback | function | Yes| Callback invoked when the pasteboard content changes.| + +**Example** + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +let listener = () => { + console.info('The system pasteboard has changed.'); +}; +systemPasteboard.on('update', listener); +``` ### off('update')7+ @@ -1256,16 +1230,215 @@ Unsubscribes from the system pasteboard content change event. **Example** ```js +let systemPasteboard = pasteboard.getSystemPasteboard(); let listener = () => { console.info('The system pasteboard has changed.'); -}; +}; systemPasteboard.off('update', listener); ``` +### clearData9+ -### hasPasteData7+ +clearData(callback: AsyncCallback<void>): void -hasPasteData(callback: AsyncCallback<boolean>): void +Clears the system pasteboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.clearData((err, data) => { + if (err) { + console.error(`Failed to clear the pasteboard. Cause: ${err.message}`); + return; + } + console.info('Succeeded in clearing the pasteboard.'); +}); +``` + +### clearData9+ + +clearData(): Promise<void> + +Clears the system pasteboard. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.clearData().then((data) => { + console.info('Succeeded in clearing the pasteboard.'); +}).catch((err) => { + console.error(`Failed to clear the pasteboard. Cause: ${err.message}`); +}); +``` + +### setData9+ + +setData(data: PasteData, callback: AsyncCallback<void>): void + +Writes a **PasteData** object to the pasteboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | [PasteData](#pastedata) | Yes| **PasteData** object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 12900003 | Another copy or paste is in progress. | +| 12900004 | Replication is prohibited. | + +**Example** + +```js +let pasteData = pasteboard.createPlainTextData('content'); +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setData(pasteData, (err, data) => { + if (err) { + console.error('Failed to set PasteData. Cause: ' + err.message); + return; + } + console.info('Succeeded in setting PasteData.'); +}); +``` + +### setData9+ + +setData(data: PasteData): Promise<void> + +Writes a **PasteData** object to the pasteboard. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | [PasteData](#pastedata) | Yes| **PasteData** object.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 12900003 | Another copy or paste is in progress. | +| 12900004 | Replication is prohibited. | + +**Example** + +```js +let pasteData = pasteboard.createPlainTextData('content'); +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setData(pasteData).then((data) => { + console.info('Succeeded in setting PasteData.'); +}).catch((err) => { + console.error('Failed to set PasteData. Cause: ' + err.message); +}); +``` + +### getData9+ + +getData( callback: AsyncCallback<PasteData>): void + +Obtains a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[PasteData](#pastedata)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the system pasteboard data. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 12900003 | Another copy or paste is in progress. | + +**Example** + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getData((err, pasteData) => { + if (err) { + console.error('Failed to get PasteData. Cause: ' + err.message); + return; + } + let text = pasteData.getPrimaryText(); +}); +``` + +### getData9+ + +getData(): Promise<PasteData> + +Obtains a **PasteData** object from the pasteboard. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[PasteData](#pastedata)> | Promise used to return the system pasteboard data.| + +**Error codes** + +For details about the error codes, see [Pasteboard Error Codes](../errorcodes/errorcode-pasteboard.md). + +| Error Code ID| Error Message| +| -------- | -------- | +| 12900003 | Another copy or paste is in progress. | + +**Example** + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getData().then((pasteData) => { + let text = pasteData.getPrimaryText(); +}).catch((err) => { + console.error('Failed to get PasteData. Cause: ' + err.message); +}) +``` + +### hasData9+ + +hasData(callback: AsyncCallback<boolean>): void Checks whether the system pasteboard contains data. This API uses an asynchronous callback to return the result. @@ -1280,19 +1453,19 @@ Checks whether the system pasteboard contains data. This API uses an asynchronou **Example** ```js -systemPasteboard.hasPasteData((err, data) => { +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.hasData((err, data) => { if (err) { - console.error('Failed to check the PasteData. Cause: ' + JSON.stringify(err)); + console.error(`Failed to check the PasteData. Cause: ${err.message}`); return; } - console.info('Succeeded in checking the PasteData. Data: ' + JSON.stringify(data)); + console.info(`Succeeded in checking the PasteData. Data: ${data}`); }); ``` +### hasData9+ -### hasPasteData7+ - -hasPasteData(): Promise<boolean> +hasData(): Promise<boolean> Checks whether the system pasteboard contains data. This API uses a promise to return the result. @@ -1307,19 +1480,22 @@ Checks whether the system pasteboard contains data. This API uses a promise to r **Example** ```js -systemPasteboard.hasPasteData().then((data) => { - console.info('Succeeded in checking the PasteData. Data: ' + JSON.stringify(data)); +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.hasData().then((data) => { + console.info(`Succeeded in checking the PasteData. Data: ${data}`); }).catch((err) => { - console.error('Failed to check the PasteData. Cause: ' + JSON.stringify(err)); + console.error(`Failed to check the PasteData. Cause: ${err.message}`); }); ``` - -### clear7+ +### clear(deprecated) clear(callback: AsyncCallback<void>): void Clears the system pasteboard. 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 [pasteboard.clearData](#cleardata9). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1334,19 +1510,21 @@ Clears the system pasteboard. This API uses an asynchronous callback to return t ```js systemPasteboard.clear((err, data) => { if (err) { - console.error('Failed to clear the PasteData. Cause: ' + JSON.stringify(err)); - return; + console.error(`Failed to clear the PasteData. Cause: ${err.message}`); + return; } console.info('Succeeded in clearing the PasteData.'); }); ``` - -### clear7+ +### clear(deprecated) clear(): Promise<void> Clears the system pasteboard. 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 [pasteboard.clearData](#cleardata9-1). **System capability**: SystemCapability.MiscServices.Pasteboard @@ -1362,6 +1540,186 @@ Clears the system pasteboard. This API uses a promise to return the result. systemPasteboard.clear().then((data) => { console.info('Succeeded in clearing the PasteData.'); }).catch((err) => { - console.error('Failed to clear the PasteData. Cause: ' + JSON.stringify(err)); + console.error(`Failed to clear the PasteData. Cause: ${err.message}`); +}); +``` + +### getPasteData(deprecated) + +getPasteData( callback: AsyncCallback<PasteData>): void + +Obtains a **PasteData** object from the pasteboard. 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 [getData](#getdata9). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[PasteData](#pastedata)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the system pasteboard data. Otherwise, **err** is an error object.| + +**Example** + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getPasteData((err, pasteData) => { + if (err) { + console.error('Failed to get PasteData. Cause: ' + err.message); + return; + } + let text = pasteData.getPrimaryText(); +}); +``` + +### getPasteData(deprecated) + +getPasteData(): Promise<PasteData> + +Obtains a **PasteData** object from the pasteboard. 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 [getData](#getdata9-1). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<[PasteData](#pastedata)> | Promise used to return the system pasteboard data.| + +**Example** + +```js +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getPasteData().then((pasteData) => { + let text = pasteData.getPrimaryText(); +}).catch((err) => { + console.error('Failed to get PasteData. Cause: ' + err.message); +}) +``` + +### hasPasteData(deprecated) + +hasPasteData(callback: AsyncCallback<boolean>): void + +Checks whether the system pasteboard contains data. 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 [hasData](#hasdata9). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if the system pasteboard contains data; returns **false** otherwise.| + +**Example** + +```js +systemPasteboard.hasPasteData((err, data) => { + if (err) { + console.error(`Failed to check the PasteData. Cause: ${err.message}`); + return; + } + console.info(`Succeeded in checking the PasteData. Data: ${data}`); +}); +``` + +### hasPasteData(deprecated) + +hasPasteData(): Promise<boolean> + +Checks whether the system pasteboard contains data. 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 [hasData](#hasdata9-1). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. Returns **true** if the system pasteboard contains data; returns **false** otherwise.| + +**Example** + +```js +systemPasteboard.hasPasteData().then((data) => { + console.info(`Succeeded in checking the PasteData. Data: ${data}`); +}).catch((err) => { + console.error(`Failed to check the PasteData. Cause: ${err.message}`); +}); +``` + +### setPasteData(deprecated) + +setPasteData(data: PasteData, callback: AsyncCallback<void>): void + +Writes a **PasteData** object to the pasteboard. 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 [setData](#setdata9). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | [PasteData](#pastedata) | Yes| **PasteData** object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| + +**Example** + +```js +let pasteData = pasteboard.createPlainTextData('content'); +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setPasteData(pasteData, (err, data) => { + if (err) { + console.error('Failed to set PasteData. Cause: ' + err.message); + return; + } + console.info('Succeeded in setting PasteData.'); +}); +``` +### setPasteData(deprecated) + +setPasteData(data: PasteData): Promise<void> + +Writes a **PasteData** object to the pasteboard. 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 [setData](#setdata9-1). + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| data | [PasteData](#pastedata) | Yes| **PasteData** object.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let pasteData = pasteboard.createPlainTextData('content'); +let systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setPasteData(pasteData).then((data) => { + console.info('Succeeded in setting PasteData.'); +}).catch((err) => { + console.error('Failed to set PasteData. Cause: ' + err.message); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md index b397ba221d3d570e3b5eca2f551ecee228bdfc35..03e049e9a1bb1076f770bd2d89dc25455c453ee6 100644 --- a/en/application-dev/reference/apis/js-apis-permissionrequestresult.md +++ b/en/application-dev/reference/apis/js-apis-permissionrequestresult.md @@ -1,40 +1,40 @@ # PermissionRequestResult -The **PermissionRequestResult** module provides the result of a permission request. +The **PermissionRequestResult** module defines the result of a permission request. The result is returned when [requestPermissionsFromUser](js-apis-abilityAccessCtrl.md#requestpermissionsfromuser9) is called to request permissions. > **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. -## Usage +## Attributes -The permission request result is obtained through an **AbilityStage** instance. - -```js -import Ability from '@ohos.application.Ability' -export default class MainAbility extends Ability { - onWindowStageCreate(windowStage) { - var permissions=['com.example.permission'] - 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)); - } - }); - } -} -``` +**System capability**: SystemCapability.Security.AccessToken +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| permissions | Array<string> | Yes| No| Permissions requested.| +| authResults | Array<number> | Yes| No| Whether the requested permissions are granted. The value **0** means that the requests permissions are granted, and a non-zero value means the opposite.| -## Attributes +## Usage -**System capability**: SystemCapability.Ability.AbilityRuntime.Core +The permission request result is obtained through an **atManager** instance. + +**Example** +```ts +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; +let atManager = abilityAccessCtrl.createAtManager(); +try { + atManager.requestPermissionsFromUser(this.context, ["ohos.permission.CAMERA"]).then((data) => { + console.info("data:" + JSON.stringify(data)); + console.info("data permissions:" + data.permissions); + console.info("data authResults:" + data.authResults); + }).catch((err) => { + console.info("data:" + JSON.stringify(err)); + }) +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` - | 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 a non-zero value means the opposite. | + \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-plainarray.md b/en/application-dev/reference/apis/js-apis-plainarray.md index 79ede0ce7a1aac37d64fe0a848e4bb5948cd877b..8ccc7d7fb4bc1a5f876b8da75c181f8547e32f51 100644 --- a/en/application-dev/reference/apis/js-apis-plainarray.md +++ b/en/application-dev/reference/apis/js-apis-plainarray.md @@ -1,7 +1,6 @@ -# Nonlinear Container PlainArray +# @ohos.util.PlainArray (Nonlinear Container PlainArray) > **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. **PlainArray** stores key-value (KV) pairs. Each key must be unique, be of the number type, and have only one value. @@ -44,7 +43,7 @@ A constructor used to create a **PlainArray** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -54,11 +53,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let plainArray = new PlainArray(); -try { - let plainArray2 = PlainArray(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -78,7 +72,7 @@ Checks whether this container is empty. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -89,11 +83,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const plainArray = new PlainArray(); let result = plainArray.isEmpty(); -try { - plainArray.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -119,7 +108,7 @@ Checks whether this container contains the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -132,11 +121,6 @@ let plainArray = new PlainArray(); plainArray.has(1); plainArray.add(1, "squirrel"); let result1 = plainArray.has(1); -try { - plainArray.has.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -162,7 +146,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -175,11 +159,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.get(1); -try { - plainArray.get.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -205,7 +184,7 @@ Obtains the index of the first occurrence of an element with the specified key i **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -218,11 +197,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfKey(2); -try { - plainArray.getIndexOfKey.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -248,7 +222,7 @@ Obtains the index of the first occurrence of an element with the specified value **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -261,11 +235,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getIndexOfValue("squirrel"); -try { - plainArray.getIndexOfValue.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -291,7 +260,7 @@ Obtains the key of the element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -304,11 +273,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getKeyAt(1); -try { - plainArray.getKeyAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getValueAt @@ -321,24 +285,24 @@ Obtains the value of an element at the specified position in this container. **Parameters** -| Name| Type | Mandatory| Description| -| -------- | -------- | -------- | -------- | -| index | number | Yes| Position index of the target element.| + | Name| Type | Mandatory| Description| + | -------- | -------- | -------- | -------- | + | index | number | Yes| Position index of the target element.| **Return value** -| Type| Description| -| -------- | -------- | -| T | Returns the value of the element if obtained; returns **undefined** otherwise.| + | Type| Description| + | -------- | -------- | + | T | Returns the value of the element if obtained; returns **undefined** otherwise.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The getValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -347,16 +311,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.getValueAt(1); -try { - plainArray.getValueAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.getValueAt(10); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### clone @@ -375,7 +329,7 @@ Clones this container and returns a copy. The modification to the copy does not **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -388,11 +342,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let newPlainArray = plainArray.clone(); -try { - plainArray.clone.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -413,7 +362,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -424,11 +373,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); -try { - plainArray.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -454,7 +398,7 @@ Removes an element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -467,11 +411,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.remove(2); -try { - plainArray.remove.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -497,7 +436,7 @@ Removes an element at the specified position from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -510,11 +449,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeAt(1); -try { - plainArray.removeAt.bind({}, 1)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -541,12 +475,12 @@ Removes elements in a specified range from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The removeRangeFrom method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -555,16 +489,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.removeRangeFrom(1, 3); -try { - plainArray.removeRangeFrom.bind({}, 1, 3)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.removeRangeFrom(10, 3); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -585,12 +509,12 @@ Sets a value for an element at the specified position in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | | 10200011 | The setValueAt method cannot be bound. | -| 10200001 | The value of parameters are out of range. | +| 10200001 | The value of index is out of range. | **Example** @@ -599,16 +523,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.setValueAt(1, 3546); -try { - plainArray.setValueAt.bind({}, 1, 3546)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} -try { - plainArray.setValueAt(10, 3); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -628,7 +542,7 @@ Obtains a string that contains all elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -641,11 +555,6 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); let result = plainArray.toString(); -try { - plainArray.toString.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -659,7 +568,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -672,17 +581,12 @@ let plainArray = new PlainArray(); plainArray.add(1, "squirrel"); plainArray.add(2, "sparrow"); plainArray.clear(); -try { - plainArray.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value: T, index?: number, PlainArray?: PlainArray<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -692,7 +596,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type | Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -704,7 +608,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -719,13 +623,6 @@ plainArray.add(2, "sparrow"); plainArray.forEach((value, index) => { console.log("value:" + value, index); }); -try { - plainArray.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -745,7 +642,7 @@ Obtains an iterator object that contains key-value pairs, where the key is of th **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -772,9 +669,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - plainArray[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md index ea2d452000bb542e55232a29456d3811fd24526c..fc74447111636244fb54e604dba5c458a6e6e061 100644 --- a/en/application-dev/reference/apis/js-apis-pointer.md +++ b/en/application-dev/reference/apis/js-apis-pointer.md @@ -1,9 +1,8 @@ -# Mouse Pointer +# @ohos.multimodalInput.pointer (Mouse Pointer) -The mouse pointer module provides APIs related to pointer attribute management. +The **pointer** module provides APIs related to pointer attribute management. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -122,9 +121,13 @@ Checks the visible status of the mouse pointer. This API uses a promise to retur **Example** ```js -pointer.isPointerVisible().then((visible) => { - console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); -}); +try { + pointer.isPointerVisible().then((visible) => { + console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`); + }); +} catch (error) { + console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`); +} ``` ## pointer.setPointerSpeed9+ @@ -135,12 +138,14 @@ Sets the mouse movement speed. This API uses an asynchronous callback to return **System capability**: SystemCapability.MultimodalInput.Input.Pointer +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ------------------------------------- | | speed | number | Yes | Mouse movement speed. The value ranges from **1** to **11**. The default value is **5**. | -| callback | AysncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -166,6 +171,8 @@ Sets the mouse movement speed. This API uses a promise to return the result. **System capability**: SystemCapability.MultimodalInput.Input.Pointer +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -198,6 +205,8 @@ Obtains the mouse movement speed. This API uses an asynchronous callback to retu **System capability**: SystemCapability.MultimodalInput.Input.Pointer +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -254,6 +263,8 @@ Obtains the mouse pointer style. This API uses an asynchronous callback to retur **System capability**: SystemCapability.MultimodalInput.Input.Pointer +**System API**: This is a system API. + **Parameters** | Name | Type | Mandatory | Description | @@ -268,7 +279,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -311,7 +322,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -341,7 +352,7 @@ Sets the mouse pointer style. This API uses an asynchronous callback to return t | ------------ | ------------------------------ | ---- | ----------------------------------- | | windowId | number | Yes | Window ID. | | pointerStyle | [PointerStyle](#pointerstyle9) | Yes | Mouse pointer style ID. | -| callback | AysncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -350,7 +361,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; @@ -388,7 +399,7 @@ import window from '@ohos.window'; window.getTopWindow((error, win) => { win.getProperties((error, properties) => { - var windowId = properties.id; + let windowId = properties.id; if (windowId < 0) { console.log(`Invalid windowId`); return; diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md index ad6e437f09767e362b2787f5ee78dd58d1a65165..4dc07d44197a78f01cb3e9018293cc1da88bea38 100644 --- a/en/application-dev/reference/apis/js-apis-power.md +++ b/en/application-dev/reference/apis/js-apis-power.md @@ -1,10 +1,9 @@ -# Power Manager +# @ohos.power (System Power Management) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -The Power Manager module provides APIs for rebooting and shutting down the system, as well as querying the screen status. +The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status. +> **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -12,42 +11,294 @@ The Power Manager module provides APIs for rebooting and shutting down the syste import power from '@ohos.power'; ``` -## System Capability - -SystemCapability.PowerManager.PowerManager.Core - +## power.shutdown -## power.shutdownDevice - -shutdownDevice(reason: string): void +shutdown(reason: string): void Shuts down the system. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Required permission**: ohos.permission.REBOOT +**System capability:** SystemCapability.PowerManager.PowerManager.Core + **Parameters** | Name | Type | Mandatory | Description | | ------ | ------ | ---- | ----- | | reason | string | Yes | Reason for system shutdown.| +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + **Example** ```js -power.shutdownDevice("shutdown_test"); -console.info('power_shutdown_device_test success') +try { + power.shutdown('shutdown_test'); +} catch(err) { + console.error('shutdown failed, err: ' + err); +} ``` +## power.reboot9+ + +reboot(reason: string): void + +Reboots the system. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.REBOOT + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| reason | string | Yes | Reason for system reboot.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.reboot('reboot_test'); +} catch(err) { + console.error('reboot failed, err: ' + err); +} +``` + +## power.isActive9+ + +isActive(): boolean + +Checks whether the current device is active. In the active state, the screen is on if the device has a screen and the device is not in sleep state if the device does not have a screen. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var isActive = power.isActive(); + console.info('power is active: ' + isActive); +} catch(err) { + console.error('check active status failed, err: ' + err); +} +``` + +## power.wakeup9+ + +wakeup(detail: string): void + +Wakes up a device. + +**System API**: This is a system API. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------- | +| detail | string | Yes | Reason for wakeup.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.wakeup('wakeup_test'); +} catch(err) { + console.error('wakeup failed, err: ' + err); +} +``` + +## power.suspend9+ + +suspend(): void + +Hibernates a device. + +**System API**: This is a system API. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + power.suspend(); +} catch(err) { + console.error('suspend failed, err: ' + err); +} +``` -## power.rebootDevice +## power.getPowerMode9+ + +getPowerMode(): DevicePowerMode + +Obtains the power mode of this device. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Return value** + +| Type | Description | +| ------------------------------------ | ---------- | +| [DevicePowerMode](#devicepowermode9) | Power mode.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var mode = power.getPowerMode(); + console.info('power mode: ' + mode); +} catch(err) { + console.error('get power mode failed, err: ' + err); +} +``` + +## power.setPowerMode9+ + +setPowerMode(mode: DevicePowerMode, callback: AsyncCallback<void>): void + +Sets the power mode of this device. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.POWER_OPTIMIZATION + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the power mode is successfully set, **err** is **undefined**; otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE, err => { + if (typeof err === 'undefined') { + console.info('set power mode to MODE_PERFORMANCE'); + } else { + console.error('set power mode failed, err: ' + err); + } +}); +``` + +## power.setPowerMode9+ + +setPowerMode(mode: DevicePowerMode): Promise<void> + +Sets the power mode of this device. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permission**: ohos.permission.POWER_OPTIMIZATION + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------ | ---- | ---------- | +| mode | [DevicePowerMode](#devicepowermode9) | Yes | Power mode.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Error codes** + +For details about the error codes, see [Power Manager Error Codes](../errorcodes/errorcode-power.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +power.setPowerMode(power.DevicePowerMode.MODE_PERFORMANCE) +.then(() => { + console.info('set power mode to MODE_PERFORMANCE'); +}) +.catch(err => { + console.error('set power mode failed, err: ' + err); +}); +``` + +## power.rebootDevice(deprecated) rebootDevice(reason: string): void +> This API is deprecated since API version 9. You are advised to use [power.reboot](#powerreboot9) instead. + Reboots the system. -**Required permission**: ohos.permission.REBOOT (to reboot) or ohos.permission.REBOOT_RECOVERY (to reboot and enter the recovery or updater mode) +**Required permission**: ohos.permission.REBOOT + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** @@ -58,55 +309,73 @@ Reboots the system. **Example** ```js -power.rebootDevice("reboot_test"); -console.info('power_reboot_device_test success') +power.rebootDevice('reboot_test'); ``` - -## power.isScreenOn +## power.isScreenOn(deprecated) isScreenOn(callback: AsyncCallback<boolean>): void -Checks the screen status of the current device. +> This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead. + +Checks the screen status of the current device. This API uses an asynchronous callback to return the result. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the screen status obtained, where the value **true** indicates on and the value **false** indicates the opposite. Otherwise, **err** is an error object.| **Example** ```js -power.isScreenOn((error, screenOn) => { - if (typeof error === "undefined") { - console.info('screenOn status is ' + screenOn); +power.isScreenOn((err, data) => { + if (typeof err === 'undefined') { + console.info('screen on status is ' + data); } else { - console.log('error: ' + error); + console.error('check screen status failed, err: ' + err); } }) ``` - -## power.isScreenOn +## power.isScreenOn(deprecated) isScreenOn(): Promise<boolean> -Checks the screen status of the current device. +> This API is deprecated since API version 9. You are advised to use [power.isActive](#powerisactive9) instead. + +Checks the screen status of the current device. This API uses a promise to return the result. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core **Return value** -| Type | Description | -| ---------------------- | --------------------------------------- | -| Promise<boolean> | Promise used to obtain the return value.
Return value: The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| +| Type | Description | +| ---------------------- | -------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the screen is on, and the value **false** indicates the opposite.| **Example** ```js power.isScreenOn() -.then(screenOn => { - console.info('screenOn status is ' + screenOn); +.then(data => { + console.info('screen on status is ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.error('check screen status failed, err: ' + err); }) ``` + +## DevicePowerMode9+ + +Enumerates power modes. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +| Name | Value | Description | +| ----------------------- | ---- | ---------------------- | +| MODE_NORMAL | 600 | Standard mode. It is the default value.| +| MODE_POWER_SAVE | 601 | Power saving mode. | +| MODE_PERFORMANCE | 602 | Performance mode. | +| MODE_EXTREME_POWER_SAVE | 603 | Ultra power saving mode. | diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index cf518ed93a2aea668985ae96031b12d48e284811..c7da8609952d245b53e82aead09f57f97eeeedf1 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -1,4 +1,4 @@ -# Privacy Management +# @ohos.privacyManager (Privacy Management) The **privacyManager** module provides APIs for privacy management, such as management of permission usage records. @@ -42,11 +42,14 @@ The permission usage record includes the application identity (token ID) of the **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -89,11 +92,14 @@ The permission usage record includes the application identity (token ID) of the **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -139,11 +145,14 @@ Obtains historical permission usage records. This API uses a promise to return t **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. the value of flag in request is invalid. | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -191,11 +200,14 @@ Obtains historical permission usage records. This API uses an asynchronous callb **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | +| 12100001 | The parameter is invalid. the value of flag in request is invalid. | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -251,12 +263,15 @@ Starts to use a permission and flushes the permission usage record. This API is **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -296,12 +311,15 @@ Starts to use a permission and flushes the permission usage record. This API is **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is called repeatedly with the same input. It means the application specified by the tokenID has been using the specified permission. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -324,7 +342,7 @@ try { ## privacyManager.stopUsingPermission -stopUsingPermission(tokenID: number, permissionName: string): Promise<void> +stopUsingPermission(tokenID: number, permissionName: Permissions): Promise<void> Stops using a permission. This API is called by a system application and uses a promise to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. This API uses a promise to return the result. @@ -348,12 +366,15 @@ Stops using a permission. This API is called by a system application and uses a **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -393,12 +414,15 @@ Stops using a permission. This API is called by a system application and uses a **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100002 | TokenId does not exist. | -| 12100003 | Permission does not exist. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100002 | The specified tokenID does not exist or it does not refer to an application process. | +| 12100003 | The specified permission does not exist or it is not an user_grant permission. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** @@ -434,26 +458,29 @@ Subscribes to the permission usage status changes of the specified permissions. | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | No | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | +| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback invoked to return a change in the permission usage.| **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100004 | The interface is not used together. | -| 12100005 | The number of listeners exceeds the limit. | +| 12100001 | The parameter is invalid. The tokenID is 0 | +| 12100004 | The interface is called repeatedly with the same input. | +| 12100005 | The registration time has exceeded the limitation. | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList = []; try { - atManager.on('activeStateChange', permissionNameList, (data) => { + privacyManager.on('activeStateChange', permissionNameList, (data) => { console.debug("receive permission state change, data:" + JSON.stringify(data)); }); } catch(err) { @@ -476,23 +503,26 @@ Unsubscribes from the permission usage status changes of the specified permissio | Name | Type | Mandatory| Description | | ------------------ | --------------------- | ---- | ------------------------------------------------------------ | | type | string | Yes | Event type to subscribe to. The value is **'activeStateChange'**, which indicates the permission usage change event. | -| permissionNameList | Array<Permissions> | No | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| +| permissionNameList | Array<Permissions> | Yes | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback for the permission usage change event.| **Error codes** For details about the error codes, see [Ability Access Control Error Codes](../errorcodes/errorcode-access-token.md). + | ID| Error Message| | -------- | -------- | -| 12100001 | Parameter invalid. | -| 12100004 | The interface is not used together. | +| 12100001 | The parameter is invalid. The permissionName in list is all invalid or the list size is larger than 1024. | +| 12100004 | The interface is not used with | +| 12100007 | Service is abnormal. | +| 12100008 | Out of memory. | **Example** ```js import privacyManager from '@ohos.privacyManager'; -let permissionNameList: Array = []; +let permissionNameList = []; try { privacyManager.off('activeStateChange', permissionNameList); }catch(err) { @@ -589,7 +619,7 @@ Enumerates the permission usage statuses. **System capability**: SystemCapability.Security.AccessToken -| Name | Default Value| Description | +| Name | Value | Description | | ------------------------- | ------ | ---------------- | | PERM_INACTIVE | 0 | The permission is not used. | | PERM_ACTIVE_IN_FOREGROUND | 1 | The permission is being used by an application running in the foreground.| diff --git a/en/application-dev/reference/apis/js-apis-process.md b/en/application-dev/reference/apis/js-apis-process.md index 59727e8c039dd23adc71b3a0b314e5664e8c9b34..318ba307995a44950461ae3b9a43e92743c37364 100755 --- a/en/application-dev/reference/apis/js-apis-process.md +++ b/en/application-dev/reference/apis/js-apis-process.md @@ -1,4 +1,4 @@ -# Obtaining Process Information +# @ohos.process (Obtaining Process Information) > **NOTE** > @@ -18,13 +18,13 @@ import process from '@ohos.process'; | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| egid | number | Yes| No| Effective group identifier (EGID) of a process. This is a system API and cannot be called by third-party applications.| -| euid | number | Yes| No| Effective user identifier (EUID) of a process. This is a system API and cannot be called by third-party applications.| -| gid | number | Yes| No| Group identifier (GID) of a process. This is a system API and cannot be called by third-party applications.| +| egid | number | Yes| No| Effective group identifier (EGID) of a process.
**System API**: This is a system API.
It is used only to test applications.| +| euid | number | Yes| No| Effective user identifier (EUID) of a process.
**System API**: This is a system API.
It is used only to test applications.| +| gid | number | Yes| No| Group identifier (GID) of a process.
**System API**: This is a system API.
It is used only to test applications.| | uid | number | Yes| No| User identifier (UID) of a process.| -| groups | number[] | Yes| No| Array with supplementary group IDs. This is a system API and cannot be called by third-party applications.| +| groups | number[] | Yes| No| Array with supplementary group IDs.
**System API**: This is a system API.
It is used only to test applications.| | pid | number | Yes| No| Process ID (PID) of a process.| -| ppid | number | Yes| No| Parent process ID (PPID) of a process. This is a system API and cannot be called by third-party applications.| +| ppid | number | Yes| No| Parent process ID (PPID) of a process.
**System API**: This is a system API.
It is used only to test applications.| | tid8+ | number | Yes| No| Thread ID (TID) of a process.| @@ -32,7 +32,7 @@ import process from '@ohos.process'; Provides APIs for throwing exceptions during the addition of a process. -### process.isAppUid9+ +### isAppUid9+ isAppUid(v: number): boolean @@ -60,7 +60,7 @@ let result = pro.isAppUid(688); ``` -### process.getUidForName9+ +### getUidForName9+ getUidForName(v: string): number @@ -88,7 +88,7 @@ let pres = pro .getUidForName("tool"); ``` -### process.getThreadPriority9+ +### getThreadPriority9+ getThreadPriority(v: number): number @@ -117,7 +117,7 @@ let pres = pro.getThreadPriority(tid); ``` -### process.getSystemConfig9+ +### getSystemConfig9+ getSystemConfig(name: number): number @@ -146,7 +146,7 @@ let pres = pro.getSystemConfig(_SC_ARG_MAX); ``` -### process.getEnvironmentVar9+ +### getEnvironmentVar9+ getEnvironmentVar(name: string): string @@ -174,7 +174,7 @@ let pres = pro.getEnvironmentVar("PATH"); ``` -### process.exit9+ +### exit9+ exit(code: number): void @@ -198,7 +198,7 @@ pro.exit(0); ``` -### process.kill9+ +### kill9+ kill(signal: number, pid: number): boolean @@ -238,10 +238,10 @@ Allows a process to obtain the standard input and output of its child processes, | Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| PID of the child process. This is a system API and cannot be called by third-party applications.| -| ppid | number | Yes| No| PPID of the child process. This is a system API and cannot be called by third-party applications.| -| exitCode | number | Yes| No| Exit code of the child process. This is a system API and cannot be called by third-party applications.| -| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it. This is a system API and cannot be called by third-party applications.| +| pid | number | Yes| No| PID of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| ppid | number | Yes| No| PPID of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| exitCode | number | Yes| No| Exit code of the child process.
**System API**: This is a system API.
It is used only to test applications.| +| killed | boolean | Yes| No| Whether the parent process successfully sends a signal to the child process to terminate it.
**System API**: This is a system API.
It is used only to test applications.| ### wait @@ -250,7 +250,9 @@ wait(): Promise<number> Waits until the child process ends. This method uses a promise to return the exit code of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -277,7 +279,9 @@ getOutput(): Promise<Uint8Array> Obtains the standard output of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -304,7 +308,9 @@ getErrorOutput(): Promise<Uint8Array> Obtains the standard error output of the child process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -331,7 +337,9 @@ close(): void Closes the child process in running. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -349,7 +357,9 @@ kill(signal: number | string): void Sends a signal to the specified child process to terminate it. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -593,7 +603,9 @@ runCmd(command: string, options?: { timeout?: number, killSignal?: number | stri Forks a new process to run a shell command and returns the **ChildProcess** object. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -609,7 +621,7 @@ This is a system API and cannot be called by third-party applications. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | timeout | number | No| Maximum running time (in ms) of the child process. When the running time of the child process exceeds the value of this parameter, the parent process sends a **killSignal** to the child process to terminate it. The default value is **0**.| -| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| +| killSignal | number \| string | No| Signal sent to the child process when the running time of a child process exceeds the timeout period. The default value is **SIGTERM**.| | maxBuffer | number | No| Maximum buffer size for the standard input and output of the child process. When the size is exceeded, the child process will be terminated. The default value is **1024 \* 1024**.| **Return value** @@ -650,7 +662,9 @@ on(type: string, listener: EventListener): void Stores the events triggered by the user. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -682,7 +696,9 @@ off(type: string): boolean Deletes the event stored by the user. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -737,7 +753,9 @@ cwd(): string Obtains the working directory of this process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang @@ -754,7 +772,9 @@ chdir(dir: string): void Changes the working directory of this process. -This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. + +It is used only to test applications. **System capability**: SystemCapability.Utils.Lang diff --git a/en/application-dev/reference/apis/js-apis-processrunninginformation.md b/en/application-dev/reference/apis/js-apis-processrunninginformation.md deleted file mode 100644 index a5add77380e1a9173f9d1d1b1e44b2dfee5be38c..0000000000000000000000000000000000000000 --- a/en/application-dev/reference/apis/js-apis-processrunninginformation.md +++ /dev/null @@ -1,29 +0,0 @@ -# ProcessRunningInformation9+ - -The **ProcessRunningInformation** module provides process running information. - -> **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. - -## Usage Guidelines - -The process running information is obtained through [appManager](js-apis-appmanager.md#appmanagergetprocessrunninginformation9). - -```js -import appManager from '@ohos.application.appManager'; -appManager.getProcessRunningInformation((error,data) => { - console.log("getProcessRunningInformation error: " + error.code + " data: " + JSON.stringify(data)); -}); -``` - -## Attributes - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| pid | number | Yes| No| Process ID.| -| uid | number | Yes| No| User ID.| -| processName | string | Yes| No| Process name.| -| bundleNames | Array<string> | Yes| No| Names of all running bundles in the process.| diff --git a/en/application-dev/reference/apis/js-apis-prompt.md b/en/application-dev/reference/apis/js-apis-prompt.md index 1fd0357783d6cf3ead6913cfc07a0e4b4e1c3c82..27a450de58306f1b018468d6f2590778a9f0d484 100644 --- a/en/application-dev/reference/apis/js-apis-prompt.md +++ b/en/application-dev/reference/apis/js-apis-prompt.md @@ -1,4 +1,4 @@ -# Prompt +# @ohos.prompt The **Prompt** module provides APIs for creating and showing toasts, dialog boxes, and action menus. @@ -146,11 +146,11 @@ 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.| +| 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 | [[Button](#button),[Button](#button)?,[Button](#button)?] | 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 @@ -158,9 +158,9 @@ 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.| +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | ------------------------------- | +| index | number | No | Index of the selected button in the **buttons** array.| ## prompt.showActionMenu @@ -255,10 +255,10 @@ 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 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.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+ | No | Title of the text to display. | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[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 diff --git a/en/application-dev/reference/apis/js-apis-promptAction.md b/en/application-dev/reference/apis/js-apis-promptAction.md index 268673b046bbb5f775dfffe3986105718319d009..0faa9cf211bbd0a673287c34b8d9ad45d34374e6 100644 --- a/en/application-dev/reference/apis/js-apis-promptAction.md +++ b/en/application-dev/reference/apis/js-apis-promptAction.md @@ -1,4 +1,4 @@ -# Prompt +# @ohos.promptAction The **PromptAction** module provides APIs for creating and showing toasts, dialog boxes, and action menus. @@ -32,7 +32,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -88,7 +88,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -142,7 +142,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -181,11 +181,11 @@ 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.| +| 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 | [[Button](#button),[Button](#button)?,[Button](#button)?] | 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 @@ -193,9 +193,9 @@ 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.| +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | ------------------------------- | +| index | number | No | Index of the selected button in the **buttons** array.| ## promptAction.showActionMenu @@ -218,7 +218,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -276,7 +276,7 @@ For details about the error codes, see [promptAction Error Codes](../errorcodes/ | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -314,10 +314,10 @@ 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.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| title | string\| [Resource](../arkui-ts/ts-types.md#resource)9+| No | Title of the dialog box. | +| buttons | [[Button](#button),[Button](#button)?,[Button](#button)?,[Button](#button)?,[Button](#button)?,[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 diff --git a/en/application-dev/reference/apis/js-apis-queue.md b/en/application-dev/reference/apis/js-apis-queue.md index 11ca91994e98310961e657db1a4c5e2554798c99..e4adf559e862ddc954b7e75c3253fb8aa95b6b2a 100644 --- a/en/application-dev/reference/apis/js-apis-queue.md +++ b/en/application-dev/reference/apis/js-apis-queue.md @@ -1,7 +1,6 @@ -# Linear Container Queue +# @ohos.util.Queue (Linear Container Queue) > **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. **Queue** follows the principle of First In First Out (FIFO). It supports insertion of elements at the end and removal from the front of the queue. **Queue** is implemented based on the queue data structure. @@ -41,7 +40,7 @@ A constructor used to create a **Queue** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -51,11 +50,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let queue = new Queue(); -try { - let queue2 = Queue(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -81,7 +75,7 @@ Adds an element at the end of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -97,11 +91,6 @@ let b = [1, 2, 3]; let result2 = queue.add(b); let c = {name : "Dylon", age : "13"}; let result3 = queue.add(c); -try { - queue.add.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### pop @@ -120,7 +109,7 @@ Removes the first element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -136,11 +125,6 @@ queue.add(5); queue.add(2); queue.add(4); let result = queue.pop(); -try { - queue.pop.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### getFirst @@ -151,7 +135,7 @@ Obtains the first element of this container. **System capability**: SystemCapability.Utils.Lang -**Parameters** +**Return value** | Type| Description| | -------- | -------- | @@ -159,7 +143,7 @@ Obtains the first element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -174,16 +158,11 @@ queue.add(4); queue.add(5); queue.add(2); let result = queue.getFirst(); -try { - queue.getFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, Queue?: Queue<T>) => void, +forEach(callbackFn: (value: T, index?: number, Queue?: Queue<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -194,7 +173,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -207,7 +186,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -224,13 +203,6 @@ queue.add(4); queue.forEach((value, index) => { console.log("value:" + value, index); }); -try { - queue.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -249,7 +221,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -275,9 +247,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - queue[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 5e7b448ff0a5452d40ef6037cf1b037bf0f95614..dfb1dd75061b1bb272170b5dbd7c202d320ce304 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -1,6 +1,6 @@ -# Radio +# @ohos.telephony.radio (Network Search) -The radio module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. +The **radio** module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card. >**NOTE** > @@ -928,7 +928,8 @@ Sends a cell location update request. This API uses an asynchronous callback to **System API**: This is a system API. -**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION +**Required permissions**: ohos.permission.LOCATION + **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -953,7 +954,8 @@ Sends a cell location update request for the SIM card in the specified slot. Thi **System API**: This is a system API. -**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION +**Required permissions**: ohos.permission.LOCATION + **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -980,7 +982,8 @@ Sends a cell location update request for the SIM card in the specified slot.This **System API**: This is a system API. -**Required permissions**: ohos.permission.LOCATION and ohos.permission.APPROXIMATELY_LOCATION +**Required permissions**: ohos.permission.LOCATION + **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -1731,8 +1734,8 @@ Enables listening for **imsRegStateChange** events for the SIM card in the speci **Example** ```js -radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +radio.on('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1760,8 +1763,8 @@ Disables listening for **imsRegStateChange** events for the SIM card in the spec **Example** ```js -radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, (err, data) => { - console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +radio.off('imsRegStateChange', 0, radio.ImsServiceType.TYPE_VIDEO, data => { + console.log(`callback: data->${JSON.stringify(data)}`); }); ``` @@ -1794,10 +1797,10 @@ Defines the signal strength. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------- | --------------------------- | ------------------ | -| signalType | [NetworkType](#networktype) | Signal strength type.| -| signalLevel | number | Signal strength level.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| signalType | [NetworkType](#networktype) | Yes| Signal strength type.| +| signalLevel | number | Yes| Signal strength level.| ## NetworkType @@ -1822,17 +1825,17 @@ Defines the network status. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------------- | --------------------- | ------------------------------------------------------------ | -| longOperatorName | string | Long carrier name of the registered network.| -| shortOperatorName | string | Short carrier name of the registered network.| -| plmnNumeric | string | PLMN code of the registered network.| -| isRoaming | boolean | Whether the user is roaming.| -| regState | [RegState](#regstate) | Network registration status of the device.| -| cfgTech8+ | [RadioTechnology](#radiotechnology) | RAT of the device.| -| nsaState | [NsaState](#nsastate) | NSA network registration status of the device.| -| isCaActive | boolean | CA status.| -| isEmergency | boolean | Whether only emergency calls are allowed.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| longOperatorName | string | Yes | Long carrier name of the registered network.| +| shortOperatorName | string | Yes | Short carrier name of the registered network.| +| plmnNumeric | string | Yes | PLMN code of the registered network.| +| isRoaming | boolean | Yes | Whether the user is roaming.| +| regState | [RegState](#regstate) | Yes | Network registration status of the device.| +| cfgTech8+ | [RadioTechnology](#radiotechnology) | Yes | RAT of the device.| +| nsaState | [NsaState](#nsastate) | Yes | NSA network registration status of the device.| +| isCaActive | boolean | Yes | CA status.| +| isEmergency | boolean | Yes | Whether only emergency calls are allowed.| ## RegState @@ -1930,13 +1933,13 @@ Defines the cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| networkType | [NetworkType](#networktype) | Network type of the cell. | -| isCamped | boolean | Status of the cell. | -| timeStamp | number | Timestamp when cell information is obtained. | -| signalInformation | [SignalInformation](#signalinformation) | Signal information. | -| data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | CDMA cell information \|GSM cell information \|LTE cell information \|NR cell information \|TD-SCDMA cell information| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| networkType | [NetworkType](#networktype) | Yes | Network type of the cell. | +| isCamped | boolean | Yes | Status of the cell. | +| timeStamp | number | Yes | Timestamp when cell information is obtained. | +| signalInformation | [SignalInformation](#signalinformation) | Yes | Signal information. | +| data | [CdmaCellInformation](#cdmacellinformation8) \| [GsmCellInformation](#gsmcellinformation8) \| [LteCellInformation](#ltecellinformation8) \| [NrCellInformation](#nrcellinformation8) \| [TdscdmaCellInformation](#tdscdmacellinformation8) | Yes | CDMA cell information \|GSM cell information \|LTE cell information \|NR cell information \|TD-SCDMA cell information| ## CdmaCellInformation8+ @@ -1946,13 +1949,13 @@ Defines the CDMA cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------- | ------ | ------------ | -| baseId | number | Base station ID. | -| latitude | number | Longitude. | -| longitude | number | Latitude. | -| nid | number | Network ID.| -| sid | number | System ID.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| baseId | number | Yes | Base station ID. | +| latitude | number | Yes | Longitude. | +| longitude | number | Yes | Latitude. | +| nid | number | Yes | Network ID.| +| sid | number | Yes | System ID.| ## GsmCellInformation8+ @@ -1962,14 +1965,14 @@ Defines the GSM cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------ | ------ | -------------------- | -| lac | number | Location area code. | -| cellId | number | Cell ID. | -| arfcn | number | Absolute radio frequency channel number.| -| bsic | number | Base station ID. | -| mcc | string | Mobile country code. | -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lac | number | Yes | Location area code. | +| cellId | number | Yes | Cell ID. | +| arfcn | number | Yes | Absolute radio frequency channel number.| +| bsic | number | Yes | Base station ID. | +| mcc | string | Yes | Mobile country code. | +| mnc | string | Yes | Mobile network code. | ## LteCellInformation8+ @@ -1979,16 +1982,16 @@ Defines the LTE cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------------- | ------- | ----------------------- | -| cgi | number | Cell global identification. | -| pci | number | Physical cell ID. | -| tac | number | Tracking area code. | -| earfcn | number | Absolute radio frequency channel number. | -| bandwidth | number | Bandwidth. | -| mcc | string | Mobile country code. | -| mnc | string | Mobile network code. | -| isSupportEndc | boolean | Support New Radio_Dual Connectivity| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| cgi | number | Yes | Cell global identification. | +| pci | number | Yes | Physical cell ID. | +| tac | number | Yes | Tracking area code. | +| earfcn | number | Yes | Absolute radio frequency channel number. | +| bandwidth | number | Yes | Bandwidth. | +| mcc | string | Yes | Mobile country code. | +| mnc | string | Yes | Mobile network code. | +| isSupportEndc | boolean | Yes | Support for New Radio_Dual Connectivity. | ## NrCellInformation8+ @@ -1998,14 +2001,14 @@ Defines the NR cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------- | ------ | ---------------- | -| nrArfcn | number | 5G frequency number. | -| pci | number | Physical cell ID. | -| tac | number | Tracking area code. | -| nci | number | 5G network cell ID.| -| mcc | string | Mobile country code. | -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| nrArfcn | number | Yes | 5G frequency number. | +| pci | number | Yes | Physical cell ID. | +| tac | number | Yes | Tracking area code. | +| nci | number | Yes | 5G network cell ID.| +| mcc | string | Yes | Mobile country code. | +| mnc | string | Yes | Mobile network code. | ## TdscdmaCellInformation8+ @@ -2015,14 +2018,14 @@ Defines the TD-SCDMA cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------ | ------ | ------------ | -| lac | number | Location area code.| -| cellId | number | Cell ID. | -| cpid | number | Cell parameter ID.| -| uarfcn | number | Absolute radio frequency number.| -| mcc | string | Mobile country code.| -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lac | number | Yes | Location area code.| +| cellId | number | Yes | Cell ID. | +| cpid | number | Yes | Cell parameter ID.| +| uarfcn | number | Yes | Absolute radio frequency number.| +| mcc | string | Yes | Mobile country code.| +| mnc | string | Yes | Mobile network code. | ## WcdmaCellInformation8+ @@ -2032,14 +2035,14 @@ Defines the WCDMA cell information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------ | ------ | ------------ | -| lac | number | Location area code.| -| cellId | number | Cell ID. | -| psc | number | Primary scrambling code. | -| uarfcn | number | Absolute radio frequency number.| -| mcc | string | Mobile country code.| -| mnc | string | Mobile network code. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lac | number | Yes | Location area code.| +| cellId | number | Yes | Cell ID. | +| psc | number | Yes | Primary scrambling code. | +| uarfcn | number | Yes | Absolute radio frequency number.| +| mcc | string | Yes | Mobile country code.| +| mnc | string | Yes | Mobile network code. | ## NrOptionMode8+ @@ -2064,10 +2067,10 @@ Defines the network search result. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ---------------------- | ------------------------------------------------- | -------------- | -| isNetworkSearchSuccess | boolean | Successful network search.| -| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Network search result.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| isNetworkSearchSuccess | boolean | Yes | Successful network search.| +| networkSearchResult | Array<[NetworkInformation](#networkinformation)\> | Yes | Network search result.| ## NetworkInformation @@ -2077,12 +2080,12 @@ Defines the network information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------------- | ----------------------------------------- | -------------- | -| operatorName | string | Carrier name.| -| operatorNumeric | string | Carrier number. | -| state | [NetworkInformation](#networkinformationstate) | Network information status.| -| radioTech | string | Radio technology. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| operatorName | string | Yes | Carrier name.| +| operatorNumeric | string | Yes | Carrier number. | +| state | [NetworkInformation](#networkinformationstate) | Yes | Network information status.| +| radioTech | string | Yes | Radio technology. | ## NetworkInformationState @@ -2107,12 +2110,12 @@ Defines the network selection mode. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------------------ | --------------------------------------------- | -------------------------------------- | -| slotId | number | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| -| selectMode | [NetworkSelectionMode](#networkselectionmode) | Network selection mode. | -| networkInformation | [NetworkInformation](#networkinformation) | Network information. | -| resumeSelection | boolean | Whether to resume selection. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| +| selectMode | [NetworkSelectionMode](#networkselectionmode) | Yes | Network selection mode. | +| networkInformation | [NetworkInformation](#networkinformation) | Yes | Network information. | +| resumeSelection | boolean | Yes | Whether to resume selection. | ## ImsRegState9+ @@ -2150,10 +2153,10 @@ Defines the IMS registration information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ----------- | ---------------------------- | ------------- | -| imsRegState | [ImsRegState](#imsregstate9) | IMS registration state.| -| imsRegTech | [ImsRegTech](#imsregtech9) | IMS registration technology.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| imsRegState | [ImsRegState](#imsregstate9) | Yes | IMS registration state.| +| imsRegTech | [ImsRegTech](#imsregtech9) | Yes | IMS registration technology.| ## ImsServiceType9+ diff --git a/en/application-dev/reference/apis/js-apis-reminderAgent.md b/en/application-dev/reference/apis/js-apis-reminderAgent.md index 81717b6ebd1ed56470b9992e1f2fc69b546c035a..29b20c42950323df2346d817922f178d71d11a80 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgent.md @@ -1,8 +1,8 @@ -# reminderAgent +# @ohos.reminderAgent (reminderAgent) The **reminderAgent** module provides APIs for publishing scheduled reminders through the reminder agent. -You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. > **NOTE** > @@ -13,14 +13,16 @@ You can set your application to use the reminder agent APIs to create scheduled ## Modules to Import -```js +```ts import reminderAgent from'@ohos.reminderAgent'; ``` ## reminderAgent.publishReminder -publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void +```ts +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void +``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -33,14 +35,15 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Example** -```js +```ts let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + reminderAgent.publishReminder(timer, (err, reminderId) => { console.log("callback, reminderId = " + reminderId); }); @@ -49,7 +52,9 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c ## reminderAgent.publishReminder -publishReminder(reminderReq: ReminderRequest): Promise<number> +```ts +publishReminder(reminderReq: ReminderRequest): Promise +``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -65,14 +70,15 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Example** -```js +```ts let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + reminderAgent.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); }); @@ -81,7 +87,9 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu ## reminderAgent.cancelReminder -cancelReminder(reminderId: number, callback: AsyncCallback<void>): void +```ts +cancelReminder(reminderId: number, callback: AsyncCallback): void +``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -92,11 +100,11 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel. The value is obtained by calling [publishReminder](#reminderagentpublishreminder).| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts reminderAgent.cancelReminder(1, (err, data) => { console.log("cancelReminder callback"); }); @@ -105,7 +113,9 @@ reminderAgent.cancelReminder(1, (err, data) => { ## reminderAgent.cancelReminder -cancelReminder(reminderId: number): Promise<void> +```ts +cancelReminder(reminderId: number): Promise +``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -121,20 +131,21 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts reminderAgent.cancelReminder(1).then(() => { console.log("cancelReminder promise"); }); ``` - ## reminderAgent.getValidReminders -getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void +```ts +getValidReminders(callback: AsyncCallback>): void +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. @@ -144,11 +155,11 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| **Example** -```js +```ts reminderAgent.getValidReminders((err, reminders) => { console.log("callback, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -178,7 +189,9 @@ reminderAgent.getValidReminders((err, reminders) => { ## reminderAgent.getValidReminders -getValidReminders(): Promise<Array<ReminderRequest>> +```ts +getValidReminders(): Promise> +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -188,11 +201,11 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| **Example** -```js +```ts reminderAgent.getValidReminders().then((reminders) => { console.log("promise, getValidReminders length = " + reminders.length); for (let i = 0; i < reminders.length; i++) { @@ -222,7 +235,9 @@ reminderAgent.getValidReminders().then((reminders) => { ## reminderAgent.cancelAllReminders -cancelAllReminders(callback: AsyncCallback<void>): void +```ts +cancelAllReminders(callback: AsyncCallback): void +``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -232,11 +247,11 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts reminderAgent.cancelAllReminders((err, data) =>{ console.log("cancelAllReminders callback") }) @@ -245,7 +260,9 @@ reminderAgent.cancelAllReminders((err, data) =>{ ## reminderAgent.cancelAllReminders -cancelAllReminders(): Promise<void> +```ts +cancelAllReminders(): Promise +``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -255,20 +272,21 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts reminderAgent.cancelAllReminders().then(() => { console.log("cancelAllReminders promise") }) ``` - ## reminderAgent.addNotificationSlot -addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void +```ts +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void +``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -279,11 +297,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -297,7 +315,9 @@ reminderAgent.addNotificationSlot(mySlot, (err, data) => { ## reminderAgent.addNotificationSlot -addNotificationSlot(slot: NotificationSlot): Promise<void> +```ts +addNotificationSlot(slot: NotificationSlot): Promise +``` Adds a notification slot. This API uses a promise to return the result. @@ -313,11 +333,11 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -331,7 +351,9 @@ reminderAgent.addNotificationSlot(mySlot).then(() => { ## reminderAgent.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void +```ts +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void +``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -341,12 +363,12 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, (err, data) => { @@ -357,7 +379,9 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION, ## reminderAgent.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType): Promise<void> +```ts +removeNotificationSlot(slotType: notification.SlotType): Promise +``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -367,17 +391,17 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| +| slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the reminder notification slot to remove.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION).then(() => { @@ -392,7 +416,7 @@ Enumerates button types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | ACTION_BUTTON_TYPE_CLOSE | 0 | Button for closing the reminder.| | ACTION_BUTTON_TYPE_SNOOZE | 1 | Button for snoozing the reminder.| @@ -404,7 +428,7 @@ Enumerates reminder types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | REMINDER_TYPE_TIMER | 0 | Countdown reminder.| | REMINDER_TYPE_CALENDAR | 1 | Calendar reminder.| @@ -431,7 +455,7 @@ Sets the package and ability that are redirected to when the reminder notificati | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| +| pkgName | string | Yes| Name of the HAP that is redirected to when the reminder notification is clicked.| | abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.| @@ -443,7 +467,7 @@ Provides the information about the target package and ability to start automatic | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the HAP that is automatically started when the reminder arrives and the device is not in use.| | abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| @@ -459,9 +483,9 @@ Defines the reminder to publish. | actionButton | [ActionButton](#actionbutton) | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the notification is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| -| ringDuration | number | No| Ringing duration.| -| snoozeTimes | number | No| Number of reminder snooze times.| -| timeInterval | number | No| Reminder snooze interval.| +| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| +| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| +| timeInterval | number | No| Reminder snooze interval, in seconds. The default value is **0**.| | title | string | No| Reminder title.| | content | string | No| Reminder content.| | expiredContent | string | No| Content to be displayed after the reminder expires.| @@ -481,8 +505,8 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array<number> | No| Month in which the reminder repeats.| -| repeatDays | Array<number> | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm @@ -497,7 +521,7 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats.| +| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| ## ReminderRequestTimer diff --git a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md index 3ec850db6ec46eb5e2343f6aa7918efec37a4a48..ab3d0f116871392e6cdbf0c004b9c418c5660e16 100644 --- a/en/application-dev/reference/apis/js-apis-reminderAgentManager.md +++ b/en/application-dev/reference/apis/js-apis-reminderAgentManager.md @@ -1,8 +1,8 @@ -# reminderAgentManager +# @ohos.reminderAgentManager (reminderAgentManager) The **reminderAgentManager** module provides APIs for publishing scheduled reminders through the reminder agent. -You can set your application to use the reminder agent APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. +You can use the APIs to create scheduled reminders for countdown timers, calendar events, and alarm clocks. When the created reminders are published, the timing and pop-up notification functions of your application will be taken over by the reminder agent in the background when your application is frozen or exits. > **NOTE** > @@ -11,14 +11,16 @@ You can set your application to use the reminder agent APIs to create scheduled ## Modules to Import -``` +```ts import reminderAgentManager from'@ohos.reminderAgentManager'; ``` ## reminderAgentManager.publishReminder -publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback<number>): void +```ts +publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void +``` Publishes a reminder through the reminder agent. This API uses an asynchronous callback to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -31,7 +33,7 @@ Publishes a reminder through the reminder agent. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderReq | [ReminderRequest](#reminderrequest) | Yes| Reminder to be published.| - | callback | AsyncCallback<number> | Yes| Asynchronous callback used to return the published reminder's ID.| + | callback | AsyncCallback\ | Yes| Callback used to return the published reminder's ID.| **Error codes** @@ -39,15 +41,16 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | -| 1700001 | Notification does not enable. | +| 1700001 | Notification is not enabled. | | 1700002 | The number of reminders exceeds the limit. | **Example** -```js +```ts let timer = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + try { reminderAgentManager.publishReminder(timer, (err, reminderId) => { if (err) { @@ -64,7 +67,9 @@ try { ## reminderAgentManager.publishReminder -publishReminder(reminderReq: ReminderRequest): Promise<number> +```ts +publishReminder(reminderReq: ReminderRequest): Promise +``` Publishes a reminder through the reminder agent. This API uses a promise to return the result. It can be called only when notification is enabled for the application through [Notification.requestEnableNotification](js-apis-notification.md#notificationrequestenablenotification8). @@ -80,7 +85,7 @@ Publishes a reminder through the reminder agent. This API uses a promise to retu **Return value** | Type| Description| | -------- | -------- | - | Promise<number> | Promise used to return the published reminder's ID.| + | Promise\ | Promise used to return the published reminder's ID.| **Error codes** @@ -88,15 +93,16 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | -| 1700001 | Notification does not enable. | +| 1700001 | Notification is not enabled. | | 1700002 | The number of reminders exceeds the limit. | **Example** -```js +```ts let timer = { reminderType: reminderAgentManager.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10 } + try { reminderAgentManager.publishReminder(timer).then((reminderId) => { console.log("promise, reminderId = " + reminderId); @@ -111,7 +117,9 @@ try { ## reminderAgentManager.cancelReminder -cancelReminder(reminderId: number, callback: AsyncCallback<void>): void +```ts +cancelReminder(reminderId: number, callback: AsyncCallback): void +``` Cancels the reminder with the specified ID. This API uses an asynchronous callback to return the cancellation result. @@ -122,7 +130,7 @@ Cancels the reminder with the specified ID. This API uses an asynchronous callba | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | reminderId | number | Yes| ID of the reminder to cancel.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Error codes** @@ -131,11 +139,11 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | | 1700003 | The reminder does not exist. | -| 1700004 | The package name does not exist. | +| 1700004 | The bundle name does not exist. | **Example** -```js +```ts try { reminderAgentManager.cancelReminder(1, (err, data) => { if (err) { @@ -152,7 +160,9 @@ try { ## reminderAgentManager.cancelReminder -cancelReminder(reminderId: number): Promise<void> +```ts +cancelReminder(reminderId: number): Promise +``` Cancels the reminder with the specified ID. This API uses a promise to return the cancellation result. @@ -168,7 +178,7 @@ Cancels the reminder with the specified ID. This API uses a promise to return th | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Error codes** @@ -177,11 +187,11 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | | 1700003 | The reminder does not exist. | -| 1700004 | The package name does not exist. | +| 1700004 | The bundle name does not exist. | **Example** -```js +```ts try { reminderAgentManager.cancelReminder(1).then(() => { console.log("cancelReminder promise"); @@ -193,10 +203,12 @@ try { }; ``` - ## reminderAgentManager.getValidReminders -getValidReminders(callback: AsyncCallback<Array<ReminderRequest>>): void +```ts +getValidReminders(callback: AsyncCallback>): void + +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses an asynchronous callback to return the reminders. @@ -206,7 +218,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Array<[ReminderRequest](#reminderrequest)>> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| +| callback | AsyncCallback\\> | Yes| Asynchronous callback used to return an array of all valid reminders set by the current application.| **Error codes** @@ -214,11 +226,11 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | -| 1700004 | The package name does not exist. | +| 1700004 | The bundle name does not exist. | **Example** -```js +```ts try { reminderAgentManager.getValidReminders((err, reminders) => { if (err) { @@ -253,10 +265,11 @@ try { }; ``` - ## reminderAgentManager.getValidReminders -getValidReminders(): Promise<Array<ReminderRequest>> +```ts +getValidReminders(): Promise> +``` Obtains all valid (not yet expired) reminders set by the current application. This API uses a promise to return the reminders. @@ -266,7 +279,7 @@ Obtains all valid (not yet expired) reminders set by the current application. Th | Type| Description| | -------- | -------- | -| Promise<Array<[ReminderRequest](#reminderrequest)>> | Promise used to return an array of all valid reminders set by the current application.| +| Promise\\> | Promise used to return an array of all valid reminders set by the current application.| **Error codes** @@ -274,11 +287,11 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | -| 1700004 | The package name does not exist. | +| 1700004 | The bundle name does not exist. | **Example** -```js +```ts try { reminderAgentManager.getValidReminders().then((reminders) => { console.log("promise, getValidReminders length = " + reminders.length); @@ -314,7 +327,9 @@ try { ## reminderAgentManager.cancelAllReminders -cancelAllReminders(callback: AsyncCallback<void>): void +```ts +cancelAllReminders(callback: AsyncCallback): void +``` Cancels all reminders set by the current application. This API uses an asynchronous callback to return the cancellation result. @@ -324,7 +339,7 @@ Cancels all reminders set by the current application. This API uses an asynchron | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Error codes** @@ -332,11 +347,11 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | -| 1700004 | The package name does not exist. | +| 1700004 | The bundle name does not exist. | **Example** -```js +```ts try { reminderAgentManager.cancelAllReminders((err, data) =>{ if (err) { @@ -353,7 +368,9 @@ try { ## reminderAgentManager.cancelAllReminders -cancelAllReminders(): Promise<void> +```ts +cancelAllReminders(): Promise +``` Cancels all reminders set by the current application. This API uses a promise to return the cancellation result. @@ -363,7 +380,7 @@ Cancels all reminders set by the current application. This API uses a promise to | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Error codes** @@ -371,11 +388,11 @@ For details about the error codes, see [reminderAgentManager Error Codes](../err | ID | Error Message| | --------- | ------- | -| 1700004 | The package name does not exist. | +| 1700004 | The bundle name does not exist. | **Example** -```js +```ts try { reminderAgentManager.cancelAllReminders().then(() => { console.log("cancelAllReminders promise") @@ -390,7 +407,9 @@ try { ## reminderAgentManager.addNotificationSlot -addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback<void>): void +```ts +addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void +``` Adds a notification slot. This API uses an asynchronous callback to return the result. @@ -401,11 +420,11 @@ Adds a notification slot. This API uses an asynchronous callback to return the r | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slot | [NotificationSlot](js-apis-notification.md#notificationslot) | Yes| Notification slot, whose type can be set.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -427,7 +446,9 @@ try { ## reminderAgentManager.addNotificationSlot -addNotificationSlot(slot: NotificationSlot): Promise<void> +```ts +addNotificationSlot(slot: NotificationSlot): Promise +``` Adds a notification slot. This API uses a promise to return the result. @@ -443,11 +464,11 @@ Adds a notification slot. This API uses a promise to return the result. | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' let mySlot = { @@ -467,7 +488,9 @@ try { ## reminderAgentManager.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback<void>): void +```ts +removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void +``` Removes a notification slot of a specified type. This API uses an asynchronous callback to return the result. @@ -478,11 +501,11 @@ Removes a notification slot of a specified type. This API uses an asynchronous c | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | slotType | [notification.SlotType](js-apis-notification.md#slottype) | Yes| Type of the notification slot to remove.| -| callback | AsyncCallback<void> | Yes| Asynchronous callback used to return the result.| +| callback | AsyncCallback\ | Yes| Asynchronous callback used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' try { @@ -501,7 +524,9 @@ try { ## reminderAgentManager.removeNotificationSlot -removeNotificationSlot(slotType: notification.SlotType): Promise<void> +```ts +removeNotificationSlot(slotType: notification.SlotType): Promise +``` Removes a notification slot of a specified type. This API uses a promise to return the result. @@ -517,11 +542,11 @@ Removes a notification slot of a specified type. This API uses a promise to retu | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result.| +| Promise\ | Promise used to return the result.| **Example** -```js +```ts import notification from '@ohos.notification' try { @@ -541,7 +566,7 @@ Enumerates button types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | ACTION_BUTTON_TYPE_CLOSE | 0 | Button for closing the reminder.| | ACTION_BUTTON_TYPE_SNOOZE | 1 | Button for snoozing the reminder.| @@ -553,7 +578,7 @@ Enumerates reminder types. **System capability**: SystemCapability.Notification.ReminderAgent -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | REMINDER_TYPE_TIMER | 0 | Countdown reminder.| | REMINDER_TYPE_CALENDAR | 1 | Calendar reminder.| @@ -580,7 +605,7 @@ Sets the package and ability that are redirected to when the reminder notificati | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is redirected to when the reminder notification is clicked.| +| pkgName | string | Yes| Name of the HAP that is redirected to when the reminder notification is clicked.| | abilityName | string | Yes| Name of the ability that is redirected to when the reminder notification is clicked.| @@ -592,7 +617,7 @@ Provides the information about the target package and ability to start automatic | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| pkgName | string | Yes| Name of the package that is automatically started when the reminder arrives and the device is not in use.| +| pkgName | string | Yes| Name of the HAP that is automatically started when the reminder arrives and the device is not in use.| | abilityName | string | Yes| Name of the ability that is automatically started when the reminder arrives and the device is not in use.| @@ -608,9 +633,9 @@ Defines the reminder to publish. | actionButton | [ActionButton](#actionbutton) | No| Button displayed in the reminder notification. (The parameter is optional. Up to two buttons are supported.)| | wantAgent | [WantAgent](#wantagent) | No| Information about the ability that is redirected to when the notification is clicked.| | maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | No| Information about the ability that is automatically started when the reminder arrives. If the device is in use, a notification will be displayed.| -| ringDuration | number | No| Ringing duration, in seconds.| -| snoozeTimes | number | No| Number of reminder snooze times.| -| timeInterval | number | No| Reminder snooze interval, in seconds.| +| ringDuration | number | No| Ringing duration, in seconds. The default value is **1**.| +| snoozeTimes | number | No| Number of reminder snooze times. The default value is **0**.| +| timeInterval | number | No| Reminder snooze interval, in seconds. The default value is **0**.| | title | string | No| Reminder title.| | content | string | No| Reminder content.| | expiredContent | string | No| Content to be displayed after the reminder expires.| @@ -630,8 +655,8 @@ Defines a reminder for a calendar event. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | dateTime | [LocalDateTime](#localdatetime) | Yes| Reminder time.| -| repeatMonths | Array<number> | No| Month in which the reminder repeats.| -| repeatDays | Array<number> | No| Date on which the reminder repeats.| +| repeatMonths | Array\ | No| Month in which the reminder repeats.| +| repeatDays | Array\ | No| Date on which the reminder repeats.| ## ReminderRequestAlarm @@ -646,7 +671,7 @@ Defines a reminder for an alarm. | -------- | -------- | -------- | -------- | | hour | number | Yes| Hour portion of the reminder time.| | minute | number | Yes| Minute portion of the reminder time.| -| daysOfWeek | Array<number> | No| Days of a week when the reminder repeats.| +| daysOfWeek | Array\ | No| Days of a week when the reminder repeats. The value ranges from 1 to 7, corresponding to the data from Monday to Sunday.| ## ReminderRequestTimer diff --git a/en/application-dev/reference/apis/js-apis-request.md b/en/application-dev/reference/apis/js-apis-request.md index 65e8c2708c98748ba55a734e8095228233d90b9a..d3a0eeb30ea75a3109b6917d50b7b1d24cdd2fb4 100644 --- a/en/application-dev/reference/apis/js-apis-request.md +++ b/en/application-dev/reference/apis/js-apis-request.md @@ -1,9 +1,8 @@ -# Upload and Download +# @ohos.request (Upload and Download) The **request** module provides applications with basic upload, download, and background transmission agent capabilities. -> **NOTE** -> +> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -34,8 +33,9 @@ var config = { The **cleartextTraffic** attribute is not involved during application development in the stage model. -The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')7+)](#onfail7). +The download server must support the HTTP HEAD method so that the size of the data to download can be obtained through **Content-length**. Otherwise, the download task fails. If this is the case, you can check the failure cause through [on('fail')7+](#onfail7). +Only HTTP requests are supported. HTTPS requests are not supported. ## Constants @@ -43,41 +43,60 @@ The download server must support the HTTP HEAD method so that the size of the da **System capability**: SystemCapability.MiscServices.Download -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| NETWORK_MOBILE | number | Yes| No| Whether download is allowed on a mobile network.| -| NETWORK_WIFI | number | Yes| No| Whether download is allowed on a WLAN.| -| ERROR_CANNOT_RESUME7+ | number | Yes| No| Failure to resume the download due to an error.| -| ERROR_DEVICE_NOT_FOUND7+ | number | Yes| No| Failure to find a storage device such as a memory card.| -| ERROR_FILE_ALREADY_EXISTS7+ | number | Yes| No| Failure to download the file because it already exists.| -| ERROR_FILE_ERROR7+ | number | Yes| No| File operation failure.| -| ERROR_HTTP_DATA_ERROR7+ | number | Yes| No| HTTP transmission failure.| -| ERROR_INSUFFICIENT_SPACE7+ | number | Yes| No| Insufficient storage space.| -| ERROR_TOO_MANY_REDIRECTS7+ | number | Yes| No| Error caused by too many network redirections.| -| ERROR_UNHANDLED_HTTP_CODE7+ | number | Yes| No| Unidentified HTTP code.| -| ERROR_OFFLINE9+ | number | Yes| No| No network connection.| -| ERROR_UNSUPPORTED_NETWORK_TYPE9+ | number | Yes| No| Network type mismatch.| -| ERROR_UNKNOWN7+ | number | Yes| No| Unknown error.| -| PAUSED_QUEUED_FOR_WIFI7+ | number | Yes| No| Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| -| PAUSED_UNKNOWN7+ | number | Yes| No| Download paused due to unknown reasons.| -| PAUSED_WAITING_FOR_NETWORK7+ | number | Yes| No| Download paused due to a network connection problem, for example, network disconnection.| -| PAUSED_WAITING_TO_RETRY7+ | number | Yes| No| Download paused and then retried.| -| SESSION_FAILED7+ | number | Yes| No| Download failure without retry.| -| SESSION_PAUSED7+ | number | Yes| No| Download paused.| -| SESSION_PENDING7+ | number | Yes| No| Download pending.| -| SESSION_RUNNING7+ | number | Yes| No| Download in progress.| -| SESSION_SUCCESSFUL7+ | number | Yes| No| Successful download.| - - -## request.upload +### Network Types +You can set **networkType** in [DownloadConfig](#downloadconfig) to specify the network type for the download service. -upload(config: UploadConfig): Promise<UploadTask> +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| NETWORK_MOBILE | number | 0x00000001 | Whether download is allowed on a mobile network.| +| NETWORK_WIFI | number | 0x00010000 | Whether download is allowed on a WLAN.| -Uploads files. This API uses a promise to return the result. +### Download Error Codes +The table below lists the error codes that may be returned by [on('fail')7+](#onfail7)/[off('fail')7+](#offfail7)/[getTaskInfo9+](#gettaskinfo9). -This API can be used only in the FA model. +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| ERROR_CANNOT_RESUME7+ | number | 0 | Failure to resume the download due to network errors.| +| ERROR_DEVICE_NOT_FOUND7+ | number | 1 | Failure to find a storage device such as a memory card.| +| ERROR_FILE_ALREADY_EXISTS7+ | number | 2 | Failure to download the file because it already exists.| +| ERROR_FILE_ERROR7+ | number | 3 | File operation failure.| +| ERROR_HTTP_DATA_ERROR7+ | number | 4 | HTTP transmission failure.| +| ERROR_INSUFFICIENT_SPACE7+ | number | 5 | Insufficient storage space.| +| ERROR_TOO_MANY_REDIRECTS7+ | number | 6 | Error caused by too many network redirections.| +| ERROR_UNHANDLED_HTTP_CODE7+ | number | 7 | Unidentified HTTP code.| +| ERROR_UNKNOWN7+ | number | 8 | Unknown error.| +| ERROR_OFFLINE9+ | number | 9 | No network connection.| +| ERROR_UNSUPPORTED_NETWORK_TYPE9+ | number | 10 | Network type mismatch.| + + +### Causes of Download Pause +The table below lists the causes of download pause that may be returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| PAUSED_QUEUED_FOR_WIFI7+ | number | 0 | Download paused and queuing for a WLAN connection, because the file size exceeds the maximum value allowed by a mobile network session.| +| PAUSED_WAITING_FOR_NETWORK7+ | number | 1 | Download paused due to a network connection problem, for example, network disconnection.| +| PAUSED_WAITING_TO_RETRY7+ | number | 2 | Download paused and then retried.| +| PAUSED_BY_USER9+ | number | 3 | The user paused the session. | +| PAUSED_UNKNOWN7+ | number | 4 | Download paused due to unknown reasons.| -> **NOTE**
This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). +### Download Task Status Codes +The table below lists the download task status codes that may be returned by [getTaskInfo9+](#gettaskinfo9). + +| Name| Type| Value| Description| +| -------- | -------- | -------- | -------- | +| SESSION_SUCCESSFUL7+ | number | 0 | Successful download.| +| SESSION_RUNNING7+ | number | 1 | Download in progress.| +| SESSION_PENDING7+ | number | 2 | Download pending.| +| SESSION_PAUSED7+ | number | 3 | Download paused.| +| SESSION_FAILED7+ | number | 4 | Download failure without retry.| + + +## request.uploadFile9+ + +uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> + +Uploads files. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -85,86 +104,108 @@ This API can be used only in the FA model. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| + **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | Bad file path. | **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(uploadConfig).then((data) => { + try { + request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; - }).catch((err) => { - console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - }) + }).catch((err) => { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } ``` -## request.upload +## request.uploadFile9+ -upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void +uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -This API can be used only in the FA model. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400002 | Bad file path. | **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(uploadConfig, (err, data) => { + try { + request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; } uploadTask = data; - }); + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } ``` -## request.upload9+ -upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> +## request.upload(deprecated) + +upload(config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). +**Model restriction**: This API can be used only in the FA model. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). **Required permissions**: ohos.permission.INTERNET @@ -172,46 +213,46 @@ Uploads files. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| +| Type| Description| +| -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(globalThis.abilityContext, uploadConfig).then((data) => { + request.upload(uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); - }); + }) ``` -## request.upload9+ +## request.upload(deprecated) -upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void +upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). +**Model restriction**: This API can be used only in the FA model. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). **Required permissions**: ohos.permission.INTERNET @@ -219,24 +260,23 @@ Uploads files. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| - | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| +| callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| **Example** - + ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { + request.upload(uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -245,13 +285,16 @@ Uploads files. This API uses an asynchronous callback to return the result. }); ``` +## request.upload(deprecated) -## request.uploadFile9+ - -uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> +upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> Uploads files. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -259,36 +302,29 @@ Uploads files. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| **Return value** | Type| Description| - | -------- | -------- | -| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| - -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| | -------- | -------- | -| 13400002 | Bad file path. | +| Promise<[UploadTask](#uploadtask)> | Promise used to return the **UploadTask** object.| **Example** ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.uploadFile(globalThis.abilityContext, uploadConfig).then((data) => { + request.upload(globalThis.abilityContext, uploadConfig).then((data) => { uploadTask = data; }).catch((err) => { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); @@ -296,12 +332,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ``` -## request.uploadFile9+ +## request.upload(deprecated) -uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void +upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void Uploads files. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.uploadFile9+](#requestuploadfile9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Upload @@ -309,30 +349,23 @@ Uploads files. This API uses an asynchronous callback to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [UploadConfig](#uploadconfig) | Yes| Upload configurations.| | callback | AsyncCallback<[UploadTask](#uploadtask)> | Yes| Callback used to return the **UploadTask** object.| -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| -| -------- | -------- | -| 13400002 | Bad file path. | - **Example** ```js let uploadTask; let uploadConfig = { - url: 'https://patch', + url: 'http://patch', header: { key1: "value1", key2: "value2" }, method: "POST", files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], data: [{ name: "name123", value: "123" }], }; - request.uploadFile(globalThis.abilityContext, uploadConfig, (err, data) => { + request.upload(globalThis.abilityContext, uploadConfig, (err, data) => { if (err) { console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); return; @@ -341,11 +374,9 @@ For details about the error codes, see [Upload and Download Error Codes](../erro }); ``` - ## UploadTask -Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object. - +Implements file uploads. Before using any APIs of this class, you must obtain an **UploadTask** object through [request.uploadFile9+](#requestuploadfile9) in promise mode or [request.uploadFile9+](#requestuploadfile9-1) in callback mode. ### on('progress') @@ -359,22 +390,21 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| - | callback | function | Yes| Callback for the upload progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (upload progress).| +| callback | function | Yes| Callback for the upload progress event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes| Size of the uploaded files, in KB.| -| totalSize | number | Yes| Total size of the files to upload, in KB.| +| uploadedSize | number | Yes| Size of the uploaded files, in bytes. | +| totalSize | number | Yes| Total size of the files to upload, in bytes. | **Example** - + ```js - let uploadTask; uploadTask.on('progress', function callback(uploadedSize, totalSize) { console.info("upload totalSize:" + totalSize + " uploadedSize:" + uploadedSize); } @@ -394,21 +424,20 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| - | callback | function | Yes| Callback for the HTTP Response Header event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'headerReceive'** (response header).| +| callback | function | Yes| Callback for the HTTP Response Header event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | header | object | Yes| HTTP Response Header.| **Example** - + ```js - let uploadTask; uploadTask.on('headerReceive', function callback(headers){ console.info("upOnHeader headers:" + JSON.stringify(headers)); } @@ -428,21 +457,20 @@ Subscribes to an upload event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| - | callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | Yes| Callback used to return the result.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| **Example** - + ```js - let uploadTask; uploadTask.on('complete', function callback(taskStates) { for (let i = 0; i < taskStates.length; i++ ) { console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); @@ -471,22 +499,21 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| - | callback | function | No| Callback for the upload progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (upload progress).| +| callback | function | No| Callback for the upload progress event.| - Parameters of the callback function + Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| uploadedSize | number | Yes| Size of the uploaded files, in KB.| -| totalSize | number | Yes| Total size of the files to upload, in KB.| +| uploadedSize | number | Yes| Size of the uploaded files, in bytes. | +| totalSize | number | Yes| Total size of the files to upload, in bytes. | **Example** - + ```js - let uploadTask; uploadTask.off('progress', function callback(uploadedSize, totalSize) { console.info('uploadedSize: ' + uploadedSize, 'totalSize: ' + totalSize); } @@ -506,21 +533,20 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| - | callback | function | No| Callback for the HTTP Response Header event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'headerReceive'** (response header).| +| callback | function | No| Callback for the HTTP Response Header event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | header | object | Yes| HTTP Response Header.| **Example** - + ```js - let uploadTask; uploadTask.off('headerReceive', function callback(headers) { console.info("upOnHeader headers:" + JSON.stringify(headers)); } @@ -539,21 +565,20 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| - | callback | Callback<Array<TaskState>> | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'complete'** means the upload completion event, and **'fail'** means the upload failure event.| +| callback | Callback<Array<TaskState>> | No| Callback used to return the result.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | taskstates | Array<[TaskState](#taskstate9)> | Yes| Upload result.| **Example** - + ```js - let uploadTask; uploadTask.off('complete', function callback(taskStates) { for (let i = 0; i < taskStates.length; i++ ) { console.info("upOnComplete taskState:" + JSON.stringify(taskStates[i])); @@ -569,16 +594,10 @@ Unsubscribes from an upload event. This API uses an asynchronous callback to ret ); ``` +### delete9+ +delete(): Promise<boolean> -### remove - -remove(): Promise<boolean> - -Removes this upload task. This API uses a promise to return the result. - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9). +Deletes this upload task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -586,15 +605,14 @@ Removes this upload task. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. It returns **true** if the operation is successful and returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| **Example** - + ```js - let uploadTask; - uploadTask.remove().then((result) => { + uploadTask.delete().then((result) => { if (result) { console.info('Upload task removed successfully. '); } else { @@ -606,15 +624,11 @@ Removes this upload task. This API uses a promise to return the result. ``` -### remove - -remove(callback: AsyncCallback<boolean>): void +### delete9+ -Removes this upload task. This API uses an asynchronous callback to return the result. +delete(callback: AsyncCallback<boolean>): void -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-1). +Deletes this upload task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -622,15 +636,14 @@ Removes this upload task. This API uses an asynchronous callback to return the r **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let uploadTask; - uploadTask.remove((err, result) => { + uploadTask.delete((err, result) => { if (err) { console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); return; @@ -644,11 +657,15 @@ Removes this upload task. This API uses an asynchronous callback to return the r ``` -### delete9+ +### remove(deprecated) -delete(): Promise<boolean> +remove(): Promise<boolean> -Deletes this upload task. This API uses a promise to return the result. +Removes this upload task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9). **Required permissions**: ohos.permission.INTERNET @@ -657,14 +674,13 @@ Deletes this upload task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the task deletion result. It returns **true** if the operation is successful and returns **false** otherwise.| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result. It returns **true** if the operation is successful and returns **false** otherwise.| **Example** ```js - let uploadTask; - uploadTask.delete().then((result) => { + uploadTask.remove().then((result) => { if (result) { console.info('Upload task removed successfully. '); } else { @@ -676,11 +692,15 @@ Deletes this upload task. This API uses a promise to return the result. ``` -### delete9+ +### remove(deprecated) -delete(callback: AsyncCallback<boolean>): void +remove(callback: AsyncCallback<boolean>): void -Deletes this upload task. This API uses an asynchronous callback to return the result. +Removes this upload task. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-1). **Required permissions**: ohos.permission.INTERNET @@ -689,14 +709,13 @@ Deletes this upload task. This API uses an asynchronous callback to return the r **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** ```js - let uploadTask; - uploadTask.delete((err, result) => { + uploadTask.remove((err, result) => { if (err) { console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); return; @@ -709,7 +728,6 @@ Deletes this upload task. This API uses an asynchronous callback to return the r }); ``` - ## UploadConfig **Required permissions**: ohos.permission.INTERNET @@ -746,7 +764,7 @@ Deletes this upload task. This API uses an asynchronous callback to return the r | -------- | -------- | -------- | -------- | | filename | string | Yes| File name in the header when **multipart** is used.| | name | string | Yes| Name of a form item when **multipart** is used. The default value is **file**.| -| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | +| uri | string | Yes| Local path for storing files.
The **dataability** and **internal** protocol types are supported. However, the **internal** protocol type supports only temporary directories. Below are examples:
dataability:///com.domainname.dataability.persondata/person/10/file.txt

internal://cache/path/to/file.txt | | type | string | Yes| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| @@ -761,93 +779,110 @@ Deletes this upload task. This API uses an asynchronous callback to return the r | name | string | Yes| Name of a form element.| | value | string | Yes| Value of a form element.| +## request.downloadFile9+ -## request.download - -download(config: DownloadConfig): Promise<DownloadTask> +downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). - -This API can be used only in the FA model. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | **Example** - + ```js let downloadTask; - request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { - downloadTask = data; - }).catch((err) => { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); - }) + try { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + downloadTask = data; + }).catch((err) => { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + }) + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } ``` -## request.download +## request.downloadFile9+ -download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void +downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; Downloads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). - -This API can be used only in the FA model. - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| - | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| + +**Error codes** +For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). + +| ID| Error Message| +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | **Example** - + ```js let downloadTask; - request.download({ url: 'https://xxxx/xxxxx.hap', - filePath: 'xxx/xxxxx.hap'}, (err, data) => { - if (err) { - console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); - return; - } - downloadTask = data; - }); + try { + request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + filePath: 'xxx/xxxxx.hap'}, (err, data) => { + if (err) { + console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); + return; + } + downloadTask = data; + }); + } catch (err) { + console.error('err.code : ' + err.code + ', err.message : ' + err.message); + } ``` -## request.download9+ +## request.download(deprecated) -download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> +download(config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). + +**Model restriction**: This API can be used only in the FA model. **Required permissions**: ohos.permission.INTERNET @@ -855,22 +890,21 @@ Downloads files. This API uses a promise to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** - + ```js let downloadTask; - request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.download({ url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -878,15 +912,17 @@ Downloads files. This API uses a promise to return the result. ``` -## request.download9+ +## request.download(deprecated) -download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; +download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void Downloads files. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). + +**Model restriction**: This API can be used only in the FA model. **Required permissions**: ohos.permission.INTERNET @@ -894,17 +930,16 @@ Downloads files. This API uses an asynchronous callback to return the result. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | BaseContext | Yes| Application-based context.| - | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| - | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| **Example** - + ```js let downloadTask; - request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + request.download({ url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -914,13 +949,16 @@ Downloads files. This API uses an asynchronous callback to return the result. }); ``` +## request.download(deprecated) -## request.downloadFile9+ - -downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> +download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> Downloads files. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 9 and is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -928,30 +966,21 @@ Downloads files. This API uses a promise to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| **Return value** | Type| Description| - | -------- | -------- | -| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| - -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| | -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | +| Promise<[DownloadTask](#downloadtask)> | Promise used to return the result.| **Example** ```js let downloadTask; - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxx.hap' }).then((data) => { downloadTask = data; }).catch((err) => { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -959,12 +988,16 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ``` -## request.downloadFile9+ +## request.download(deprecated) -downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; +download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; Downloads files. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [request.downloadFile9+](#requestdownloadfile9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -972,25 +1005,16 @@ Downloads files. This API uses an asynchronous callback to return the result. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| context | BaseContext | Yes| Application-based context.| +| -------- | -------- | -------- | -------- | +| context | [BaseContext](js-apis-inner-application-baseContext.md) | Yes| Application-based context.| | config | [DownloadConfig](#downloadconfig) | Yes| Download configurations.| | callback | AsyncCallback<[DownloadTask](#downloadtask)> | Yes| Callback used to return the result.| -**Error codes** -For details about the error codes, see [Upload and Download Error Codes](../errorcodes/errorcode-request.md). - -| ID| Error Message| -| -------- | -------- | -| 13400001 | File operation error. | -| 13400002 | Bad file path. | -| 13400003 | Task manager service error. | - **Example** ```js let downloadTask; - request.downloadFile(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', + request.download(globalThis.abilityContext, { url: 'https://xxxx/xxxxx.hap', filePath: 'xxx/xxxxx.hap'}, (err, data) => { if (err) { console.error('Failed to request the download. Cause: ' + JSON.stringify(err)); @@ -1003,7 +1027,7 @@ For details about the error codes, see [Upload and Download Error Codes](../erro ## DownloadTask -Implements file downloads. +Implements file downloads. Before using any APIs of this class, you must obtain a **DownloadTask** object through [request.downloadFile9+](#requestdownloadfile9) in promise mode or [request.downloadFile9+](#requestdownloadfile9-1) in callback mode. ### on('progress') @@ -1018,22 +1042,21 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| - | callback | function | Yes| Callback for the download progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'progress'** (download progress).| +| callback | function | Yes| Callback for the download progress event.| Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes| Size of the downloaded files, in KB.| -| totalSize | number | Yes| Total size of the files to download, in KB.| +| receivedSize | number | Yes| Size of the downloaded files, in bytes. | +| totalSize | number | Yes| Total size of the files to download, in bytes. | **Example** - + ```js - let downloadTask; downloadTask.on('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); } @@ -1053,20 +1076,20 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| - | callback | function | No| Callback for the download progress event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'progress'** (download progress).| +| callback | function | No| Callback for the download progress event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| receivedSize | number | Yes| Size of the downloaded files.| -| totalSize | number | Yes| Total size of the files to download.| +| receivedSize | number | Yes| Size of the downloaded files, in bytes. | +| totalSize | number | Yes| Total size of the files to download, in bytes. | **Example** - + ```js downloadTask .off('progress', function download_callback(receivedSize, totalSize) { console.info("download receivedSize:" + receivedSize + " totalSize:" + totalSize); @@ -1087,15 +1110,14 @@ Subscribes to a download event. This API uses an asynchronous callback to return **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| - | callback | function | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; downloadTask.on('complete', function callback() { console.info('Download task completed.'); } @@ -1115,15 +1137,14 @@ Unsubscribes from a download event. This API uses an asynchronous callback to re **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| - | callback | function | No| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from.
- **'complete'**: download task completion event.
- **'pause'**: download task pause event.
- **'remove'**: download task removal event.| +| callback | function | No| Callback used to return the result.| **Example** - + ```js - let downloadTask; downloadTask.off('complete', function callback() { console.info('Download task completed.'); } @@ -1143,21 +1164,20 @@ Subscribes to the download task failure event. This API uses an asynchronous cal **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| - | callback | function | Yes| Callback for the download task failure event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value is **'fail'** (download failure).| +| callback | function | Yes| Callback for the download task failure event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| +| err | number | Yes| Error code of the download failure. For details about the error codes, see [Download Error Codes](#download-error-codes).| **Example** - + ```js - let downloadTask; downloadTask.on('fail', function callBack(err) { console.info('Download task failed. Cause:' + err); } @@ -1177,53 +1197,46 @@ Unsubscribes from the download task failure event. This API uses an asynchronous **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| - | callback | function | No| Callback for the download task failure event.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to unsubscribe from. The value is **'fail'** (download failure).| +| callback | function | No| Callback for the download task failure event.| - Parameters of the callback function +Parameters of the callback function | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| err | number | Yes| Error code of the download failure. For details about the error codes, see [ERROR_*](#constants).| +| err | number | Yes| Error code of the download failure. For details about the error codes, see [Download Error Codes](#download-error-codes).| **Example** - + ```js - let downloadTask; downloadTask.off('fail', function callBack(err) { console.info('Download task failed. Cause:' + err); } ); ``` +### delete9+ -### remove - -remove(): Promise<boolean> +delete(): Promise<boolean> Removes this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-2). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the task removal result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| **Example** - + ```js - let downloadTask; - downloadTask.remove().then((result) => { + downloadTask.delete().then((result) => { if (result) { console.info('Download task removed.'); } else { @@ -1235,31 +1248,26 @@ Removes this download task. This API uses a promise to return the result. ``` -### remove +### delete9+ -remove(callback: AsyncCallback<boolean>): void +delete(callback: AsyncCallback<boolean>): void Removes this download task. This API uses an asynchronous callback to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-3). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** - + ```js - let downloadTask; - downloadTask.remove((err, result)=>{ + downloadTask.delete((err, result)=>{ if(err) { console.error('Failed to remove the download task.'); return; @@ -1273,15 +1281,11 @@ Removes this download task. This API uses an asynchronous callback to return the ``` -### query7+ - -query(): Promise<DownloadInfo> +### getTaskInfo9+ -Queries this download task. This API uses a promise to return the result. +getTaskInfo(): Promise<DownloadInfo> -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9). +Obtains the information about this download task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1289,15 +1293,14 @@ Queries this download task. This API uses a promise to return the result. **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| +| Type| Description| +| -------- | -------- | +| Promise<[DownloadInfo](#downloadinfo7)> | Promise used to return the download task information.| **Example** - + ```js - let downloadTask; - downloadTask.query().then((downloadInfo) => { + downloadTask.getTaskInfo().then((downloadInfo) => { console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) }) .catch((err) => { console.error('Failed to query the download task. Cause:' + err) @@ -1305,15 +1308,11 @@ Queries this download task. This API uses a promise to return the result. ``` -### query7+ - -query(callback: AsyncCallback<DownloadInfo>): void +### getTaskInfo9+ -Queries this download task. This API uses an asynchronous callback to return the result. +getTaskInfo(callback: AsyncCallback<DownloadInfo>): void -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9-1). +Obtains the information about this download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1321,15 +1320,14 @@ Queries this download task. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** - + ```js - let downloadTask; - downloadTask.query((err, downloadInfo)=>{ + downloadTask.getTaskInfo((err, downloadInfo)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1339,15 +1337,11 @@ Queries this download task. This API uses an asynchronous callback to return the ``` -### queryMimeType7+ - -queryMimeType(): Promise<string> +### getTaskMimeType9+ -Queries the **MimeType** of this download task. This API uses a promise to return the result. +getTaskMimeType(): Promise<string> -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9). +Obtains the **MimeType** of this download task. This API uses a promise to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1355,15 +1349,14 @@ Queries the **MimeType** of this download task. This API uses a promise to retur **Return value** - | Type| Description| - | -------- | -------- | - | Promise<string> | Promise used to return the **MimeType** of the download task.| +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** - + ```js - let downloadTask; - downloadTask.queryMimeType().then((data) => { + downloadTask.getTaskMimeType().then((data) => { console.info('Download task queried. Data:' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) @@ -1371,15 +1364,11 @@ Queries the **MimeType** of this download task. This API uses a promise to retur ``` -### queryMimeType7+ - -queryMimeType(callback: AsyncCallback<string>): void; +### getTaskMimeType9+ -Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. +getTaskMimeType(callback: AsyncCallback<string>): void; -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9-1). +Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.INTERNET @@ -1387,15 +1376,14 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** - + ```js - let downloadTask; - downloadTask.queryMimeType((err, data)=>{ + downloadTask.getTaskMimeType((err, data)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1405,31 +1393,26 @@ Queries the **MimeType** of this download task. This API uses an asynchronous ca ``` -### pause7+ +### suspend9+ -pause(): Promise<void> +suspend(): Promise<boolean> Pauses this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [suspend9+](#suspend9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the download task pause result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the download task pause result.| **Example** - + ```js - let downloadTask; - downloadTask.pause().then((result) => { + downloadTask.suspend().then((result) => { if (result) { console.info('Download task paused. '); } else { @@ -1441,13 +1424,9 @@ Pauses this download task. This API uses a promise to return the result. ``` -### pause7+ - -pause(callback: AsyncCallback<void>): void +### suspend9+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [suspend9+](#suspend9-1). +suspend(callback: AsyncCallback<boolean>): void Pauses this download task. This API uses an asynchronous callback to return the result. @@ -1457,15 +1436,14 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.pause((err, result)=>{ + downloadTask.suspend((err, result)=>{ if(err) { console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); return; @@ -1479,31 +1457,26 @@ Pauses this download task. This API uses an asynchronous callback to return the ``` -### resume7+ +### restore9+ -resume(): Promise<void> +restore(): Promise<boolean> Resumes this download task. This API uses a promise to return the result. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [restore9+](#restore9). - **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.resume().then((result) => { + downloadTask.restore().then((result) => { if (result) { console.info('Download task resumed.') } else { @@ -1516,13 +1489,9 @@ Resumes this download task. This API uses a promise to return the result. ``` -### resume7+ - -resume(callback: AsyncCallback<void>): void +### restore9+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [restore9+](#restore9-1). +restore(callback: AsyncCallback<boolean>): void Resumes this download task. This API uses an asynchronous callback to return the result. @@ -1532,15 +1501,14 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback used to return the result.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| **Example** - + ```js - let downloadTask; - downloadTask.resume((err, result)=>{ + downloadTask.restore((err, result)=>{ if (err) { console.error('Failed to resume the download task. Cause:' + err); return; @@ -1554,11 +1522,16 @@ Resumes this download task. This API uses an asynchronous callback to return the ``` -### delete9+ -delete(): Promise<boolean> +### remove(deprecated) -Deletes this download task. This API uses a promise to return the result. +remove(): Promise<boolean> + +Removes this download task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-2). **Required permissions**: ohos.permission.INTERNET @@ -1567,14 +1540,13 @@ Deletes this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the result.| +| -------- | -------- | +| Promise<boolean> | Promise used to return the task removal result.| **Example** ```js - let downloadTask; - downloadTask.delete().then((result) => { + downloadTask.remove().then((result) => { if (result) { console.info('Download task removed.'); } else { @@ -1586,11 +1558,15 @@ Deletes this download task. This API uses a promise to return the result. ``` -### delete9+ +### remove(deprecated) -delete(callback: AsyncCallback<boolean>): void +remove(callback: AsyncCallback<boolean>): void -Deletes this download task. This API uses an asynchronous callback to return the result. +Removes this download task. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [delete9+](#delete9-3). **Required permissions**: ohos.permission.INTERNET @@ -1599,14 +1575,13 @@ Deletes this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the task removal result.| **Example** ```js - let downloadTask; - downloadTask.delete((err, result)=>{ + downloadTask.remove((err, result)=>{ if(err) { console.error('Failed to remove the download task.'); return; @@ -1620,12 +1595,16 @@ Deletes this download task. This API uses an asynchronous callback to return the ``` -### getTaskInfo9+ +### query(deprecated) -getTaskInfo(): Promise<DownloadInfo> +query(): Promise<DownloadInfo> Queries this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1639,8 +1618,7 @@ Queries this download task. This API uses a promise to return the result. **Example** ```js - let downloadTask; - downloadTask.getTaskInfo().then((downloadInfo) => { + downloadTask.query().then((downloadInfo) => { console.info('Download task queried. Data:' + JSON.stringify(downloadInfo)) }) .catch((err) => { console.error('Failed to query the download task. Cause:' + err) @@ -1648,12 +1626,16 @@ Queries this download task. This API uses a promise to return the result. ``` -### getTaskInfo9+ +### query(deprecated) query(callback: AsyncCallback<DownloadInfo>): void Queries this download task. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskInfo9+](#gettaskinfo9-1). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1661,14 +1643,13 @@ Queries this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | Yes| Callback used to return the download task information.| **Example** ```js - let downloadTask; - downloadTask.getTaskInfo((err, downloadInfo)=>{ + downloadTask.query((err, downloadInfo)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1678,11 +1659,15 @@ Queries this download task. This API uses an asynchronous callback to return the ``` -### getTaskMimeType9+ +### queryMimeType(deprecated) -getTaskMimeType(): Promise<string> +queryMimeType(): Promise<string> -Obtains the **MimeType** of this download task. This API uses a promise to return the result. +Queries the **MimeType** of this download task. This API uses a promise to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9). **Required permissions**: ohos.permission.INTERNET @@ -1691,14 +1676,13 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur **Return value** | Type| Description| - | -------- | -------- | +| -------- | -------- | | Promise<string> | Promise used to return the **MimeType** of the download task.| **Example** ```js - let downloadTask; - downloadTask.getTaskMimeType().then((data) => { + downloadTask.queryMimeType().then((data) => { console.info('Download task queried. Data:' + JSON.stringify(data)); }).catch((err) => { console.error('Failed to query the download MimeType. Cause:' + JSON.stringify(err)) @@ -1706,11 +1690,15 @@ Obtains the **MimeType** of this download task. This API uses a promise to retur ``` -### getTaskMimeType9+ +### queryMimeType(deprecated) -getTaskMimeType(callback: AsyncCallback<string>): void; +queryMimeType(callback: AsyncCallback<string>): void; -Obtains the **MimeType** of this download task. This API uses an asynchronous callback to return the result. +Queries the **MimeType** of this download task. This API uses an asynchronous callback to return the result. + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [getTaskMimeType9+](#gettaskmimetype9-1). **Required permissions**: ohos.permission.INTERNET @@ -1719,14 +1707,13 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | +| -------- | -------- | -------- | -------- | | callback | AsyncCallback<string> | Yes| Callback used to return the **MimeType** of the download task.| **Example** ```js - let downloadTask; - downloadTask.getTaskMimeType((err, data)=>{ + downloadTask.queryMimeType((err, data)=>{ if(err) { console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); } else { @@ -1736,12 +1723,16 @@ Obtains the **MimeType** of this download task. This API uses an asynchronous ca ``` -### suspend9+ +### pause(deprecated) -suspend(): Promise<boolean> +pause(): Promise<void> Pauses this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend9+](#suspend9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1749,14 +1740,13 @@ Pauses this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the download task pause result.| +| -------- | -------- | +| Promise<void> | Promise used to return the download task pause result.| **Example** ```js - let downloadTask; - downloadTask.suspend().then((result) => { + downloadTask.pause().then((result) => { if (result) { console.info('Download task paused. '); } else { @@ -1768,9 +1758,13 @@ Pauses this download task. This API uses a promise to return the result. ``` -### suspend9+ +### pause(deprecated) -suspend(callback: AsyncCallback<boolean>): void +pause(callback: AsyncCallback<void>): void + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [suspend9+](#suspend9-1). Pauses this download task. This API uses an asynchronous callback to return the result. @@ -1781,14 +1775,13 @@ Pauses this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js - let downloadTask; - downloadTask.suspend((err, result)=>{ + downloadTask.pause((err, result)=>{ if(err) { console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); return; @@ -1802,12 +1795,16 @@ Pauses this download task. This API uses an asynchronous callback to return the ``` -### restore9+ +### resume(deprecated) -restore(): Promise<boolean> +resume(): Promise<void> Resumes this download task. This API uses a promise to return the result. +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore9+](#restore9). + **Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.MiscServices.Download @@ -1815,14 +1812,13 @@ Resumes this download task. This API uses a promise to return the result. **Return value** | Type| Description| - | -------- | -------- | -| Promise<boolean> | Promise used to return the result.| +| -------- | -------- | +| Promise<void> | Promise used to return the result.| **Example** ```js - let downloadTask; - downloadTask.restore().then((result) => { + downloadTask.resume().then((result) => { if (result) { console.info('Download task resumed.') } else { @@ -1835,9 +1831,13 @@ Resumes this download task. This API uses a promise to return the result. ``` -### restore9+ +### resume(deprecated) -restore(callback: AsyncCallback<boolean>): void +resume(callback: AsyncCallback<void>): void + +> **NOTE** +> +> This API is supported since API version 7 and is deprecated since API version 9. You are advised to use [restore9+](#restore9-1). Resumes this download task. This API uses an asynchronous callback to return the result. @@ -1848,14 +1848,13 @@ Resumes this download task. This API uses an asynchronous callback to return the **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return the result.| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js - let downloadTask; - downloadTask.restore((err, result)=>{ + downloadTask.resume((err, result)=>{ if (err) { console.error('Failed to resume the download task. Cause:' + err); return; @@ -1879,12 +1878,12 @@ Resumes this download task. This API uses an asynchronous callback to return the | -------- | -------- | -------- | -------- | | url | string | Yes| Resource URL.| | header | Object | No| HTTPS flag header to be included in the download request.
The **X-TLS-Version** parameter in **header** specifies the TLS version to be used. If this parameter is not set, the CURL_SSLVERSION_TLSv1_2 version is used. Available options are as follows:
CURL_SSLVERSION_TLSv1_0
CURL_SSLVERSION_TLSv1_1
CURL_SSLVERSION_TLSv1_2
CURL_SSLVERSION_TLSv1_3
The **X-Cipher-List** parameter in **header** specifies the cipher suite list to be used. If this parameter is not specified, the secure cipher suite list is used. Available options are as follows:
- The TLS 1.2 cipher suite list includes the following ciphers:
TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,TLS_DSS_RSA_WITH_AES_256_GCM_SHA384,
TLS_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_AES_128_GCM_SHA256,
TLS_DHE_PSK_WITH_AES_256_GCM_SHA384,TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256,TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_ECDHE_PSK_WITH_AES_256_GCM_SHA384,
TLS_ECDHE_PSK_WITH_AES_128_GCM_SHA256,TLS_DHE_RSA_WITH_AES_128_CCM,
TLS_DHE_RSA_WITH_AES_256_CCM,TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256,
TLS_PSK_WITH_AES_256_CCM,TLS_DHE_PSK_WITH_AES_128_CCM,
TLS_DHE_PSK_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_AES_128_CCM,
TLS_ECDHE_ECDSA_WITH_AES_256_CCM,TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256
- The TLS 1.3 cipher suite list includes the following ciphers:
TLS_AES_128_GCM_SHA256,TLS_AES_256_GCM_SHA384,TLS_CHACHA20_POLY1305_SHA256,TLS_AES_128_CCM_SHA256
- The TLS 1.3 cipher suite list adds the Chinese national cryptographic algorithm:
TLS_SM4_GCM_SM3,TLS_SM4_CCM_SM3 | -| enableMetered | boolean | No| Whether download is allowed on a metered connection.
- **true**: yes
- **false**: no| -| enableRoaming | boolean | No| Whether download is allowed on a roaming network.
- **true**: yes
- **false**: no| +| enableMetered | boolean | No| Whether download is allowed on a metered connection.
- **true**: allowed
- **false**: not allowed | +| enableRoaming | boolean | No| Whether download is allowed on a roaming network.
- **true**: allowed
- **false**: not allowed | | description | string | No| Description of the download session.| -| filePath7+ | string | No| Download path. (The default path is **'internal://cache/'**.)
- filePath:'workspace/test.txt': The **workspace** directory is created in the default path to store files.
- filePath:'test.txt': Files are stored in the default path.
- filePath:'workspace/': The **workspace** directory is created in the default path to store files.| +| filePath7+ | string | No| Path where the downloaded file is stored.
- filePath:'/data/storage/el2/base/haps/entry/files/test.txt': Save the file to an absolute path.
- In the FA model, use [context](js-apis-inner-app-context.md#contextgetcachedir) to obtain the cache directory of the application, for example, **'${featureAbility.getContext().getFilesDir()}/test.txt'**, and store the file in this directory.
- In the stage model, use [AbilityContext](js-apis-inner-application-context.md) to obtain the fie path, for example, **'${globalThis.abilityContext.tempDir}/test.txt'**, and store the file in this path.| | networkType | number | No| Network type allowed for download.
- NETWORK_MOBILE: 0x00000001
- NETWORK_WIFI: 0x00010000| -| title | string | No| Title of the download session.| +| title | string | No| Download task name.| | background9+ | boolean | No| Whether to enable the background task notification. When this parameter is enabled, the download status is displayed in the notification panel.| @@ -1897,13 +1896,13 @@ Resumes this download task. This API uses an asynchronous callback to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | downloadId | number | Yes| ID of the downloaded file.| -| failedReason | number | No| Download failure cause, which can be any constant of [ERROR_*](#constants).| +| failedReason | number | No| Cause of the download failure. The value can be any constant in [Download Error Codes](#download-error-codes).| | fileName | string | Yes| Name of the downloaded file.| | filePath | string | Yes| URI of the saved file.| -| pausedReason | number | No| Reason for session pause, which can be any constant of [PAUSED_*](#constants).| -| status | number | Yes| Download status code, which can be any constant of [SESSION_*](#constants).| +| pausedReason | number | No| Cause of download pause. The value can be any constant in [Causes of Download Pause](#causes-of-download-pause).| +| status | number | Yes| Download task status code. The value can be any constant in [Download Task Status Codes](#download-task-status-codes).| | targetURI | string | Yes| URI of the downloaded file.| -| downloadTitle | string | Yes| Title of the downloaded file.| -| downloadTotalBytes | number | Yes| Total size of the files to download (int bytes).| +| downloadTitle | string | Yes| Download task name.| +| downloadTotalBytes | number | Yes| Total size of the files to download, in bytes.| | description | string | Yes| Description of the file to download.| -| downloadedBytes | number | Yes| Size of the files downloaded (int bytes).| +| downloadedBytes | number | Yes| Size of the files downloaded, in bytes.| diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md index ba93ca3c5a6352d03ec65cfa4c468d2769239f4f..7dc343709c19421175b4f99e6308c1c0ad90e5dd 100644 --- a/en/application-dev/reference/apis/js-apis-resource-manager.md +++ b/en/application-dev/reference/apis/js-apis-resource-manager.md @@ -1,4 +1,4 @@ -# Resource Manager +# @ohos.resourceManager (Resource Manager) The Resource Manager module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density. @@ -16,7 +16,7 @@ import resourceManager from '@ohos.resourceManager'; ## Instruction Since API version 9, the stage model allows an application to obtain a **ResourceManager** object based on **context** and call its resource management APIs without first importing the required bundle. This approach, however, is not applicable to the FA model. -For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../ability/context-userguide.md). +For details about how to reference **context** in the stage model, see [Context in the Stage Model](../../application-models/application-context-stage.md). ```ts import Ability from '@ohos.application.Ability'; @@ -97,6 +97,7 @@ Obtains the **ResourceManager** object of this application. This API uses a prom **System capability**: SystemCapability.Global.ResourceManager **Return value** + | Type | Description | | ---------------------------------------- | ----------------- | | Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| @@ -134,6 +135,7 @@ Obtains the **ResourceManager** object of an application based on the specified | bundleName | string | Yes | Bundle name of the application.| **Return value** + | Type | Description | | ---------------------------------------- | ------------------ | | Promise<[ResourceManager](#resourcemanager)> | Promise used to return the result.| @@ -305,7 +307,7 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco **Example (stage)** ```ts try { - this.context.getStringValue($r('app.string.test').id, (error, value) => { + this.context.resourceManager.getStringValue($r('app.string.test').id, (error, value) => { if (error != null) { console.log("error is " + error); } else { @@ -333,6 +335,7 @@ Obtains the string corresponding to the specified resource ID. This API uses a p | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | ----------- | | Promise<string> | Promise used to return the result.| @@ -423,6 +426,7 @@ Obtains the string corresponding to the specified resource object. This API uses | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | --------------------- | ---------------- | | Promise<string> | Promise used to return the result.| @@ -512,6 +516,7 @@ Obtains the string array corresponding to the specified resource ID. This API us | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ---------------------------------- | ------------- | | Promise<Array<string>> | Promise used to return the result.| @@ -599,6 +604,7 @@ Obtains the string array corresponding to the specified resource object. This AP | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ---------------------------------- | ------------------ | | Promise<Array<string>> | Promise used to return the result.| @@ -687,6 +693,7 @@ Obtains the content of the media file corresponding to the specified resource ID | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------------------------- | -------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -772,6 +779,7 @@ Obtains the content of the media file corresponding to the specified resource ob | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------------------------- | ------------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -859,6 +867,7 @@ Obtains the Base64 code of the image corresponding to the specified resource ID. | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | -------------------- | | Promise<string> | Promise used to return the result.| @@ -944,6 +953,7 @@ Obtains the Base64 code of the image corresponding to the specified resource obj | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| @@ -1014,6 +1024,7 @@ Obtains the device configuration. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Return value** + | Type | Description | | ---------------------------------------- | ---------------- | | Promise<[Configuration](#configuration)> | Promise used to return the result.| @@ -1069,6 +1080,7 @@ Obtains the device capability. This API uses a promise to return the result. **System capability**: SystemCapability.Global.ResourceManager **Return value** + | Type | Description | | ---------------------------------------- | ------------------- | | Promise<[DeviceCapability](#devicecapability)> | Promise used to return the result.| @@ -1144,6 +1156,7 @@ Obtains the singular-plural string corresponding to the specified resource ID ba | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| @@ -1234,6 +1247,7 @@ Obtains the singular-plural string corresponding to the specified resource objec | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ------------------------------ | | Promise<string> | Promise used to return the result.| @@ -1321,6 +1335,7 @@ Obtains the content of the raw file in the **resources/rawfile** directory. This | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------------- | ----------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -1375,15 +1390,16 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco try { this.context.resourceManager.getRawFd("test.xml", (error, value) => { if (error != null) { - console.log("error is " + error); + console.log(`callback getRawFd failed error code: ${error.code}, message: ${error.message}.`); } else { let fd = value.fd; let offset = value.offset; let length = value.length; } - }).catch(error => { - console.log("getRawFd callback error is " + error); - }); + }); + } catch (error) { + console.error(`callback getRawFd failed, error code: ${error.code}, message: ${error.message}.`) + }; ``` ### getRawFd9+ @@ -1401,6 +1417,7 @@ Obtains the descriptor of the raw file in the **resources/rawfile** directory. T | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ---------------------------------------- | ------------------- | | Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| @@ -1421,10 +1438,10 @@ For details about the error codes, see [Resource Manager Error Codes](../errorco let offset = value.offset; let length = value.length; }).catch(error => { - console.log("getRawFd promise error is " + error); + console.log(`promise getRawFd error error code: ${error.code}, message: ${error.message}.`); }); } catch (error) { - console.log("getRawFd promise error is " + error); + console.error(`promise getRawFd failed, error code: ${error.code}, message: ${error.message}.`); }; ``` @@ -1469,6 +1486,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------- | ---- | | Promise<void> | Promise that returns no value.| @@ -1537,6 +1555,7 @@ Closes the descriptor of the raw file in the **resources/rawfile** directory. Th | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------- | ---- | | Promise<void> | Promise that returns no value.| @@ -1633,6 +1652,7 @@ Obtains the string corresponding to the specified resource name. This API uses a | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | --------------------- | ---------- | | Promise<string> | String corresponding to the resource name.| @@ -1715,6 +1735,7 @@ Obtains the string array corresponding to the specified resource name. This API | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ---------------------------------- | ------------ | | Promise<Array<string>> | Promise used to return the result.| @@ -1797,6 +1818,7 @@ Obtains the content of the media file corresponding to the specified resource na | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------------------------- | ------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -1879,6 +1901,7 @@ Obtains the Base64 code of the image corresponding to the specified resource nam | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | --------------------- | ------------------- | | Promise<string> | Promise used to return the result.| @@ -1964,6 +1987,7 @@ Obtains the plural string corresponding to the specified resource name based on | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ---------------------- | | Promise<string> | Promise used to return the result.| @@ -2006,6 +2030,7 @@ Obtains the string corresponding to the specified resource ID. This API returns | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------ | ----------- | | string | Promise used to return the result.| @@ -2044,6 +2069,7 @@ Obtains the string corresponding to the specified resource object. This API retu | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------ | ---------------- | | string | Promise used to return the result.| @@ -2087,6 +2113,7 @@ Obtains the string corresponding to the specified resource name. This API return | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------ | ---------- | | string | String corresponding to the specified resource name.| @@ -2125,6 +2152,7 @@ Obtains the Boolean result corresponding to the specified resource ID. This API | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------- | ------------ | | boolean | Boolean result corresponding to the specified resource ID.| @@ -2162,6 +2190,7 @@ Obtains the Boolean result corresponding to the specified resource object. This | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------- | ----------------- | | boolean | Boolean result corresponding to the specified resource object.| @@ -2205,6 +2234,7 @@ Obtains the Boolean result corresponding to the specified resource name. This AP | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------- | ----------- | | boolean | Boolean result corresponding to the specified resource name.| @@ -2243,6 +2273,7 @@ Obtains the integer or float value corresponding to the specified resource ID. T | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------ | ---------- | | number | Integer or float value corresponding to the specified resource ID.| @@ -2287,6 +2318,7 @@ Obtains the integer or float value corresponding to the specified resource objec | resource | [Resource](#resource9) | Yes | Resource object.| **Return value** + | Type | Description | | ------ | --------------- | | number | Integer or float value corresponding to the specified resource object.| @@ -2330,6 +2362,7 @@ Obtains the integer or float value corresponding to the specified resource name. | resName | string | Yes | Resource name.| **Return value** + | Type | Description | | ------ | --------- | | number | Integer or float value corresponding to the specified resource name.| @@ -2408,6 +2441,7 @@ This API is deprecated since API version 9. You are advised to use [getStringVal | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | ----------- | | Promise<string> | Promise used to return the result.| @@ -2472,6 +2506,7 @@ This API is deprecated since API version 9. You are advised to use [getStringArr | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ---------------------------------- | ------------- | | Promise<Array<string>> | Promise used to return the result.| @@ -2494,7 +2529,7 @@ getMedia(resId: number, callback: AsyncCallback<Uint8Array>): void Obtains the content of the media file corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2525,7 +2560,7 @@ getMedia(resId: number): Promise<Uint8Array> Obtains the content of the media file corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent-1) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContent](#getmediacontent9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2536,6 +2571,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | ------------------------- | -------------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -2558,7 +2594,7 @@ getMediaBase64(resId: number, callback: AsyncCallback<string>): void Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase64) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2589,7 +2625,7 @@ getMediaBase64(resId: number): Promise<string> Obtains the Base64 code of the image corresponding to the specified resource ID. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase64-1) instead. +This API is deprecated since API version 9. You are advised to use [getMediaContentBase64](#getmediacontentbase649-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2600,6 +2636,7 @@ This API is deprecated since API version 9. You are advised to use [getMediaCont | resId | number | Yes | Resource ID.| **Return value** + | Type | Description | | --------------------- | -------------------- | | Promise<string> | Promise used to return the result.| @@ -2622,7 +2659,7 @@ getPluralString(resId: number, num: number): Promise<string> Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses a promise to return the result. -This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue) instead. +This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2634,6 +2671,7 @@ This API is deprecated since API version 9. You are advised to use [getPluralStr | num | number | Yes | Number. | **Return value** + | Type | Description | | --------------------- | ------------------------- | | Promise<string> | Promise used to return the result.| @@ -2656,7 +2694,7 @@ getPluralString(resId: number, num: number, callback: AsyncCallback<string> Obtains the singular-plural string corresponding to the specified resource ID based on the specified number. This API uses an asynchronous callback to return the result. -This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue-1) instead. +This API is deprecated since API version 9. You are advised to use [getPluralStringValue](#getpluralstringvalue9-1) instead. **System capability**: SystemCapability.Global.ResourceManager @@ -2730,6 +2768,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFileCo | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ------------------------- | ----------- | | Promise<Uint8Array> | Promise used to return the result.| @@ -2795,6 +2834,7 @@ This API is deprecated since API version 9. You are advised to use [getRawFd](#g | path | string | Yes | Path of the raw file.| **Return value** + | Type | Description | | ---------------------------------------- | ------------------- | | Promise<[RawFileDescriptor](#rawfiledescriptor8)> | Promise used to return the result.| diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md index 8944052b4fed8899733d3cf924479ddc4359fc7e..d5daa5d41e299d368b7d38af4428856bf343c516 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-backgroundTaskManager.md @@ -1,4 +1,4 @@ -# Background Task Management +# @ohos.resourceschedule.backgroundTaskManager (Background Task Management) The **BackgroundTaskManager** module provides APIs to manage background tasks. @@ -234,9 +234,9 @@ Requests a continuous task from the system. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -256,7 +256,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; @@ -268,13 +268,13 @@ function callback(error, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -308,9 +308,9 @@ Requests a continuous task from the system. This API uses a promise to return th | Name | Type | Mandatory | Description | | --------- | ---------------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | bgMode | [BackgroundMode](#backgroundmode) | Yes | Background mode requested. | -| wantAgent | [WantAgent](js-apis-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | Yes | Notification parameter, which is used to specify the target page that is redirected to when a continuous task notification is clicked. | **Return value** @@ -335,17 +335,17 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; import wantAgent from '@ohos.wantAgent'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { let wantAgentInfo = { wants: [ { bundleName: "com.example.myapplication", - abilityName: "MainAbility" + abilityName: "EntryAbility" } ], operationType: wantAgent.OperationType.START_ABILITY, @@ -381,7 +381,7 @@ Requests to cancel a continuous task. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| | callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Error codes** @@ -401,7 +401,7 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; function callback(error, data) { @@ -412,7 +412,7 @@ function callback(error, data) { } } -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context, callback); @@ -437,7 +437,7 @@ Requests to cancel a continuous task. This API uses a promise to return the resu | Name | Type | Mandatory | Description | | ------- | ------- | ---- | ---------------------------------------- | -| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md).| +| context | Context | Yes | Application context.
For details about the application context of the FA model, see [Context](js-apis-inner-app-context.md).
For details about the application context of the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -462,10 +462,10 @@ For details about the error codes, see [backgroundTaskManager Error Codes](../er **Example** ```js -import Ability from '@ohos.application.Ability' +import UIAbility from '@ohos.app.ability.UIAbility'; import backgroundTaskManager from '@ohos.resourceschedule.backgroundTaskManager'; -export default class MainAbility extends Ability { +export default class EntryAbility extends UIAbility { onCreate(want, launchParam) { try { backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { @@ -618,12 +618,12 @@ Enumerates the efficiency resource types. **System API**: This is a system API. -| Name | Description | -| ----------------------- | --------------------- | -| CPU | CPU resources, which prevent the application from being suspended. | -| COMMON_EVENT | A type of software resources, which prevent common events from being proxied when the application is suspended. | -| TIMER | A type of software resources, which prevent timers from being proxied when the application is suspended. | -| WORK_SCHEDULER | WORK_SCHEDULER resources, which ensure that the application has more time to execute the task. | -| BLUETOOTH | A type of hardware resources, which prevent Bluetooth resources from being proxied when the application is suspended. | -| GPS | A type of hardware resources, which prevent GPS resources from being proxied when the application is suspended. | -| AUDIO | A type of hardware resources, which prevent audio resources from being proxied when the application is suspended.| +| 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-resourceschedule-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md index f22d412603c1cb7d1db873f3877be537c73fb9a1..1e243a9881594c4acf692110cfe2a2e7a363b945 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-deviceUsageStatistics.md @@ -1,4 +1,4 @@ -# Device Usage Statistics +# @ohos.resourceschedule.usageStatistics (Device Usage Statistics) This module provides APIs for collecting statistics on device usage. @@ -219,8 +219,8 @@ Queries the application usage duration statistics based on the specified start t | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<[BundleStatsMap](#bundlestatsmap)> | Yes | Callback used to return the application usage duration statistics.| **Error codes** @@ -274,8 +274,8 @@ Queries the application usage duration statistics based on the specified start t | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -333,8 +333,8 @@ Queries the application usage duration statistics in the specified time frame at | Name | Type | Mandatory | Description | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | | byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried. | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleStatsInfo](#bundlestatsinfo)>> | Yes | Callback used to return the application usage duration statistics.| **Error codes** @@ -387,8 +387,8 @@ Queries the application usage duration statistics in the specified time frame at | Name | Type | Mandatory | Description | | ---------- | ----------------------------- | ---- | ----- | | byInterval | [IntervalType](#intervaltype) | Yes | Type of information to be queried.| -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -443,8 +443,8 @@ Queries events of all applications based on the specified start time and end tim | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleEvents](#bundleevents)>> | Yes | Callback used to return the events obtained.| **Error codes** @@ -496,8 +496,8 @@ Queries events of all applications based on the specified start time and end tim | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -548,8 +548,8 @@ Queries events of this application based on the specified start time and end tim | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[BundleEvents](#bundleevents)>> | Yes | Callback used to return the events obtained.| **Error codes** @@ -597,8 +597,8 @@ Queries events of this application based on the specified start time and end tim | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -703,7 +703,7 @@ Queries FA usage records. This API uses an asynchronous callback to return a max | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback<Array<[HapModuleInfo](#hapmoduleinfo)>> | Yes | Callback used to return a maximum of 1000 FA usage records.| +| callback | AsyncCallback<Array<[HapModuleInfo](#hapmoduleinfo)>> | Yes | Callback used to return a maximum of **maxNum** FA usage records.| **Error codes** @@ -1182,8 +1182,6 @@ Deregisters the callback for application group changes. This API uses a promise **System API**: This is a system API. -**Parameters**: none - **Return value** | Type | Description | @@ -1278,8 +1276,8 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1297,7 +1295,7 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | | 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed | +| 10000006 | Get application info failed. | | 10000007 | Get system or actual time failed. | **Example** @@ -1331,8 +1329,8 @@ queryDeviceEventStats(begin: number, end: number, callback: AsyncCallback<Arr | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[DeviceEventStats](#deviceeventstats)>> | Yes | Callback used to return the result. | **Error codes** @@ -1345,7 +1343,7 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | | 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed | +| 10000006 | Get application info failed. | | 10000007 | Get system or actual time failed. | **Example** @@ -1381,8 +1379,8 @@ Queries the number of notifications from all applications based on the specified | Name | Type | Mandatory | Description | | ----- | ------ | ---- | ----- | -| begin | number | Yes | Start time.| -| end | number | Yes | End time.| +| begin | number | Yes | Start time, in milliseconds.| +| end | number | Yes | End time, in milliseconds.| **Return value** @@ -1400,7 +1398,7 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | | 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed | +| 10000006 | Get application info failed. | | 10000007 | Get system or actual time failed. | **Example** @@ -1434,8 +1432,8 @@ Queries the number of notifications from all applications based on the specified | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | Yes | Start time. | -| end | number | Yes | End time. | +| begin | number | Yes | Start time, in milliseconds. | +| end | number | Yes | End time, in milliseconds. | | callback | AsyncCallback<Array<[DeviceEventStats](#deviceeventstats)>> | Yes | Callback used to return the result. | **Error codes** @@ -1448,7 +1446,7 @@ For details about the error codes, see [DeviceUsageStatistics Error Codes](../er | 10000002 | Parcel operation failed. | | 10000003 | System service operation failed. | | 10000004 | IPC Communication failed. | -| 10000006 | Get application info failed | +| 10000006 | Get application info failed. | | 10000007 | Get system or actual time failed. | **Example** @@ -1478,7 +1476,7 @@ Provides the information about the FA usage. | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ----------------------------- | | deviceId | string | No | ID of the device to which the FA belongs. | -| bundleName | string | Yes | Name of the application bundle to which the FA belongs. | +| bundleName | string | Yes | Name of the bundle to which the FA belongs. | | moduleName | string | Yes | Name of the module to which the FA belongs. | | abilityName | string | No | **MainAbility** name of the FA. | | appLabelId | number | No | Application label ID of the FA. | @@ -1566,6 +1564,8 @@ Provides the usage duration information of an application. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API. + | Name | Type | Mandatory | Description | | ------------------------------ | ---------------------------------------- | ---- | -------------- | | [key: string]: BundleStatsInfo | [key: string]: [BundleStatsInfo](#bundlestatsinfo) | Yes | Usage duration information by application.| @@ -1590,7 +1590,9 @@ Enumerates the interval types for querying the application usage duration. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App -| Name | Default Value | Description | +**System API**: This is a system API. + +| Name | Value | Description | | ------------ | ---- | ---------------------------------------- | | BY_OPTIMIZED | 0 | The system queries the application usage duration statistics in the specified time frame at the interval the system deems appropriate.| | BY_DAILY | 1 | The system queries the application usage duration statistics in the specified time frame on a daily basis. | @@ -1606,7 +1608,7 @@ Enumerates the application group types. **System API**: This is a system API. -| Name | Default Value | Description | +| Name | Value | Description | | ------------------ | ---- | ----------------- | | ALIVE_GROUP | 10 | Group of active applications. | | DAILY_GROUP | 20 | Group of frequently used applications that are not in the active state. | diff --git a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md index e62f6ca72f897772a8c98f21d14aaf18e398f575..70f20b743d5ee09f2c79877ab626d76fdaeb0d95 100644 --- a/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md +++ b/en/application-dev/reference/apis/js-apis-resourceschedule-workScheduler.md @@ -1,4 +1,4 @@ -# Work Scheduler +# @ohos.resourceschedule.workScheduler (workScheduler) The **workScheduler** module provides the APIs for registering, canceling, and querying Work Scheduler tasks, which do not have real-time constraints. @@ -437,45 +437,45 @@ Enumerates the network types that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ---------------------- | ----------------------- | -| NETWORK_TYPE_ANY | Any network type. | -| NETWORK_TYPE_MOBILE | Mobile network. | -| NETWORK_TYPE_WIFI | Wi-Fi network. | -| NETWORK_TYPE_BLUETOOTH | Bluetooth network.| -| NETWORK_TYPE_WIFI_P2P | Wi-Fi P2P network. | -| NETWORK_TYPE_ETHERNET | Ethernet. | +| Name | Value | Description | +| ---------------------- | ---- | ----------------------- | +| NETWORK_TYPE_ANY | 0 | Any network type. | +| NETWORK_TYPE_MOBILE | 1 | Mobile network. | +| NETWORK_TYPE_WIFI | 2 | Wi-Fi network. | +| NETWORK_TYPE_BLUETOOTH | 3 | Bluetooth network.| +| NETWORK_TYPE_WIFI_P2P | 4 | Wi-Fi P2P network. | +| NETWORK_TYPE_ETHERNET | 5 | Ethernet. | ## ChargingType Enumerates the charging types that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ------------------------- | -------------------- | -| CHARGING_PLUGGED_ANY | Any charging type.| -| CHARGING_PLUGGED_AC | DC charging. | -| CHARGING_PLUGGED_USB | USB charging. | -| CHARGING_PLUGGED_WIRELESS | Wireless charging. | +| Name | Value | Description | +| ------------------------- | ---- | -------------------- | +| CHARGING_PLUGGED_ANY | 0 | Any charging type.| +| CHARGING_PLUGGED_AC | 1 | DC charging. | +| CHARGING_PLUGGED_USB | 2 | USB charging. | +| CHARGING_PLUGGED_WIRELESS | 3 | Wireless charging. | ## BatteryStatus Enumerates the battery states that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| -------------------------- | -------------------------- | -| BATTERY_STATUS_LOW | A low battery alert is displayed. | -| BATTERY_STATUS_OKAY | The battery level is restored from low to normal. | -| BATTERY_STATUS_LOW_OR_OKAY | The battery level is restored from low to normal, or a low battery alert is displayed.| +| Name | Value | Description | +| -------------------------- | ---- | -------------------------- | +| BATTERY_STATUS_LOW | 0 | A low battery alert is displayed. | +| BATTERY_STATUS_OKAY | 1 | The battery level is restored from low to normal. | +| BATTERY_STATUS_LOW_OR_OKAY | 2 | The battery level is restored from low to normal, or a low battery alert is displayed.| ## StorageRequest Enumerates the storage states that can trigger the task. **System capability**: SystemCapability.ResourceSchedule.WorkScheduler -| Name | Description | -| ------------------------- | ------------------------------ | -| STORAGE_LEVEL_LOW | The storage space is insufficient. | -| STORAGE_LEVEL_OKAY | The storage space is restored from insufficient to normal. | -| STORAGE_LEVEL_LOW_OR_OKAY | The storage space is restored from insufficient to normal, or the storage space is insufficient.| +| Name | Value | Description | +| ------------------------- | ---- | ------------------------------ | +| STORAGE_LEVEL_LOW | 0 | The storage space is insufficient. | +| STORAGE_LEVEL_OKAY | 1 | The storage space is restored from insufficient to normal. | +| STORAGE_LEVEL_LOW_OR_OKAY | 2 | The storage space is restored from insufficient to normal, or the storage space is insufficient.| diff --git a/en/application-dev/reference/apis/js-apis-router.md b/en/application-dev/reference/apis/js-apis-router.md index 5e85658f698d0ca85ea2d422d648b020f5d02e4b..11bb575b307023f70b92935d98f94cab013998ad 100644 --- a/en/application-dev/reference/apis/js-apis-router.md +++ b/en/application-dev/reference/apis/js-apis-router.md @@ -1,4 +1,4 @@ -# Page Routing +# @ohos.router The **Router** module provides APIs to access pages through URLs. You can use the APIs to navigate to a specified page in an application, replace the current page with another one in an application, and return to the previous page or a specified page. @@ -40,9 +40,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | 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. | +| 100001 | If UI execution context not found. | +| 100002 | If the uri is not exist. | +| 100003 | If the pages are pushed too much. | **Example** @@ -54,8 +54,8 @@ try { data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } }) .then(() => { // success @@ -89,9 +89,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | 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. | +| 100001 | If UI execution context not found. | +| 100002 | If the uri is not exist. | +| 100003 | If the pages are pushed too much. | **Example** @@ -103,8 +103,8 @@ try { data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } }, (err) => { if (err) { console.error(`pushUrl failed, code is ${err.code}, message is ${err.message}`); @@ -143,9 +143,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | 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. | +| 100001 | If UI execution context not found. | +| 100002 | If the uri is not exist. | +| 100003 | If the pages are pushed too much. | **Example** @@ -157,8 +157,8 @@ try { data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } }, router.RouterMode.Standard) .then(() => { // success @@ -193,9 +193,9 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | 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. | +| 100001 | If UI execution context not found. | +| 100002 | If the uri is not exist. | +| 100003 | If the pages are pushed too much. | **Example** @@ -207,8 +207,8 @@ try { 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}`); @@ -247,8 +247,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | -| 200002 | Uri error. The uri of router is not exist. | +| 100001 | If UI execution context not found, only throw in standard system. | +| 200002 | If the uri is not exist. | **Example** @@ -257,8 +257,8 @@ try { router.replaceUrl({ url: 'pages/detail', params: { - data1: 'message', - }, + data1: 'message' + } }) .then(() => { // success @@ -292,8 +292,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | -| 200002 | Uri error. The uri of router is not exist. | +| 100001 | If UI execution context not found, only throw in standard system. | +| 200002 | If the uri is not exist. | **Example** @@ -302,8 +302,8 @@ try { router.replaceUrl({ url: 'pages/detail', params: { - data1: 'message', - }, + data1: 'message' + } }, (err) => { if (err) { console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); @@ -344,8 +344,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | -| 200002 | Uri error. The uri of router is not exist. | +| 100001 | If UI execution context not found, only throw in standard system. | +| 200002 | If the uri is not exist. | **Example** @@ -354,8 +354,8 @@ try { router.replaceUrl({ url: 'pages/detail', params: { - data1: 'message', - }, + data1: 'message' + } }, router.RouterMode.Standard) .then(() => { // success @@ -390,8 +390,8 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | -| 200002 | Uri error. The uri of router is not exist. | +| 100001 | If UI execution context not found, only throw in standard system. | +| 200002 | If the uri is not exist. | **Example** @@ -400,8 +400,8 @@ try { router.replaceUrl({ url: 'pages/detail', params: { - data1: 'message', - }, + data1: 'message' + } }, router.RouterMode.Standard, (err) => { if (err) { console.error(`replaceUrl failed, code is ${err.code}, message is ${err.message}`); @@ -465,7 +465,7 @@ Obtains the number of pages in the current stack. **Example** ```js -var size = router.getLength(); +let size = router.getLength(); console.log('pages stack size = ' + size); ``` @@ -486,7 +486,7 @@ Obtains state information about the current page. **Example** ```js -var page = router.getState(); +let page = router.getState(); console.log('current index = ' + page.index); console.log('current name = ' + page.name); console.log('current path = ' + page.path); @@ -498,11 +498,11 @@ Describes the page routing state. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Type | Description | -| ----- | ------ | ---------------------------------- | -| index | number | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.| -| name | string | Name of the current page, that is, the file name. | -| path | string | Path of the current page. | +| Name | Type | Mandatory| Description | +| ----- | ------ | ---- | ------------------------------------------------------------ | +| index | number | Yes | Index of the current page in the stack. The index starts from 1 from the bottom to the top of the stack.| +| name | string | No | Name of the current page, that is, the file name. | +| path | string | Yes | Path of the current page. | ## router.enableBackPageAlert9+ @@ -524,7 +524,7 @@ For details about the error codes, see [Router Error Codes](../errorcodes/errorc | ID | Error Message| | --------- | ------- | -| 100001 | Internal error. | +| 100001 | If UI execution context not found. | **Example** @@ -590,7 +590,7 @@ Describes the page routing options. | 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 the value of 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.| +| 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 the value of 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** @@ -602,9 +602,9 @@ Enumerates the routing modes. **System capability**: SystemCapability.ArkUI.ArkUI.Full -| Name | Description | -| -------- | ---------------------------------------- | -| 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. | +| Name | Description | +| -------- | ------------------------------------------------------------ | +| 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 @@ -618,8 +618,8 @@ export default { router.push({ url: 'pages/detail/detail', params: { - data1: 'message', - }, + data1: 'message' + } }); } } @@ -642,18 +642,18 @@ import router from '@ohos.router' @Entry @Component struct Index { - async routePage() { + async routePage() { let options = { url: 'pages/second', params: { text: 'This is the value on the first page.', data: { array: [12, 45, 78] - }, + } } } try { - await router.push(options) + await router.pushUrl(options) } catch (err) { console.info(` fail callback, code: ${err.code}, msg: ${err.msg}`) } @@ -661,18 +661,18 @@ struct Index { build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Text('This is the first page.') - .fontSize(50) - .fontWeight(FontWeight.Bold) + Text('This is the first page.') + .fontSize(50) + .fontWeight(FontWeight.Bold) Button() { Text('next page') .fontSize(25) .fontWeight(FontWeight.Bold) }.type(ButtonType.Capsule) - .margin({ top: 20 }) - .backgroundColor('#ccc') - .onClick(() => { - this.routePage() + .margin({ top: 20 }) + .backgroundColor('#ccc') + .onClick(() => { + this.routePage() }) } .width('100%') @@ -704,7 +704,7 @@ struct Second { this.secondData = (this.data.array[1]).toString() }) .margin({top:20}) - Text('Value from the first page '+'' + this.secondData) + Text(`This is the data passed from the first page: ${this.secondData}`) .fontSize(20) .margin({top:20}) .backgroundColor('red') @@ -741,8 +741,8 @@ router.push({ data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } }); ``` ## router.push(deprecated) @@ -772,8 +772,8 @@ router.push({ data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } },router.RouterMode.Standard); ``` @@ -799,12 +799,12 @@ This API is deprecated since API version 9. You are advised to use [replaceUrl(deprecated)
+## router.replace(deprecated) replace(options: RouterOptions, mode: RouterMode): void @@ -812,7 +812,7 @@ Replaces the current page with another one in the application and destroys the c This API is deprecated since API version 9. You are advised to use [replaceUrl9+](#routerreplaceurl9) instead. -**System capability**: SystemCapability.ArkUI.ArkUI.Full +**System capability**: SystemCapability.ArkUI.ArkUI.Lite **Parameters** @@ -827,8 +827,8 @@ This API is deprecated since API version 9. You are advised to use [replaceUrl **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> This module supports return of error codes since API version 9. ## Modules to Import - ``` import rpc from '@ohos.rpc'; ``` -## MessageParcel +## ErrorCode9+ + +The APIs of this module return exceptions since API version 9. The following table lists the error codes. + +**System capability**: SystemCapability.Communication.IPC.Core + + | Name | Value | Description | + | ------------------------------------- | ------- | --------------------------------------------- | + | CHECK_PARAM_ERROR | 401 | Parameter check failed. | + | OS_MMAP_ERROR | 1900001 | Failed to call mmap. | + | OS_IOCTL_ERROR | 1900002 | Failed to call **ioctl** with the shared memory file descriptor.| + | WRITE_TO_ASHMEM_ERROR | 1900003 | Failed to write data to the shared memory. | + | READ_FROM_ASHMEM_ERROR | 1900004 | Failed to read data from the shared memory. | + | ONLY_PROXY_OBJECT_PERMITTED_ERROR | 1900005 | This operation is allowed only on the proxy object. | + | ONLY_REMOTE_OBJECT_PERMITTED_ERROR | 1900006 | This operation is allowed only on the remote object. | + | COMMUNICATION_ERROR | 1900007 | Failed to communicate with the remote object over IPC. | + | PROXY_OR_REMOTE_OBJECT_INVALID_ERROR | 1900008 | Invalid proxy or remote object. | + | WRITE_DATA_TO_MESSAGE_SEQUENCE_ERROR | 1900009 | Failed to write data to MessageSequence. | + | READ_DATA_FROM_MESSAGE_SEQUENCE_ERROR | 1900010 | Failed to read data from MessageSequence. | + | PARCEL_MEMORY_ALLOC_ERROR | 1900011 | Failed to allocate memory during serialization. | + | CALL_JS_METHOD_ERROR | 1900012 | Failed to invoke the JS callback. | + | OS_DUP_ERROR | 1900013 | Failed to call dup. | + -Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided **MessageParcel** to write data to a **MessageParcel** object in specific format. The receiver can use the **read()** method provided by **MessageParcel** to read data in specific format from a **MessageParcel** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. +## MessageSequence9+ + Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided by **MessageSequence** to write data in specific format to a **MessageSequence** object. The receiver can use the **read()** method provided by **MessageSequence** to read data in specific format from a **MessageSequence** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. ### create -create(): MessageParcel + create(): MessageSequence -Creates a **MessageParcel** object. This method is a static method. + Creates a **MessageSequence** object. This API is a static method. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | MessageParcel | **MessageParcel** object created.| + | Type | Description | + | --------------- | ------------------------------- | + | MessageSequence | **MessageSequence** object created.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); console.log("RpcClient: data is " + data); ``` - ### reclaim reclaim(): void -Reclaims the **MessageParcel** object that is no longer used. +Reclaims the **MessageSequence** object that is no longer used. **System capability**: SystemCapability.Communication.IPC.Core **Example** ``` - let reply = rpc.MessageParcel.create(); + let reply = rpc.MessageSequence.create(); reply.reclaim(); ``` - ### writeRemoteObject -writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean +writeRemoteObject(object: [IRemoteObject](#iremoteobject)): void - Serializes a remote object and writes it to this **MessageParcel** object. +Serializes a remote object and writes it to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | object | [IRemoteObject](#iremoteobject) | Yes| Remote object to serialize and write to the **MessageParcel** object.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ----------------------------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageSequence** object.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900008 | proxy or remote object is invalid | + | 1900009 | write data to message sequence failed | **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } } - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let testRemoteObject = new TestRemoteObject("testObject"); - data.writeRemoteObject(testRemoteObject); + try { + data.writeRemoteObject(testRemoteObject); + } catch(error) { + console.info("Rpc write remote object fail, errorCode " + error.code); + console.info("Rpc write remote object fail, errorMessage " + error.message); + } ``` - ### readRemoteObject readRemoteObject(): IRemoteObject -Reads the remote object from this **MessageParcel** object. You can use this method to deserialize the **MessageParcel** object to generate an **IRemoteObject**. The remote objects are read in the order in which they are written to this **MessageParcel** object. +Reads the remote object from **MessageSequence**. You can use this API to deserialize the **MessageSequence** object to generate an **IRemoteObject**. The remote object is read in the order in which it is written to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------------------- | ------------------ | | [IRemoteObject](#iremoteobject) | Remote object obtained.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | + | 1900010 | read data from message sequence failed | + **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } } - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let testRemoteObject = new TestRemoteObject("testObject"); - data.writeRemoteObject(testRemoteObject); - let proxy = data.readRemoteObject(); + try { + data.writeRemoteObject(testRemoteObject); + let proxy = data.readRemoteObject(); + } catch(error) { + console.info("Rpc write remote object fail, errorCode " + error.code); + console.info("Rpc write remote object fail, errorMessage " + error.message); + } ``` - ### writeInterfaceToken -writeInterfaceToken(token: string): boolean +writeInterfaceToken(token: string): void -Writes an interface token to this **MessageParcel** object. The remote object can use this interface token to verify the communication. +Writes an interface token to this **MessageSequence** object. The remote object can use this interface token to verify the communication. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | token | string | Yes| Interface token to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | token | string | Yes | Interface token to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeInterfaceToken("aaa"); - console.log("RpcServer: writeInterfaceToken is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeInterfaceToken("aaa"); + } catch(error) { + console.info("rpc write interface fail, errorCode " + error.code); + console.info("rpc write interface fail, errorMessage " + error.message); + } ``` - ### readInterfaceToken readInterfaceToken(): string -Reads the interface token from this **MessageParcel** object. The interface token is read in the sequence in which it is written to the **MessageParcel** object. The local object can use it to verify the communication. +Reads the interface token from this **MessageSequence** object. The interface token is read in the sequence in which it is written to the **MessageSequence** object. The local object can use it to verify the communication. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------------ | | string | Interface token obtained.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ----- | + | 1900010 | read data from message sequence failed | + + **Example** ``` class Stub extends rpc.RemoteObject { onRemoteRequest(code, data, reply, option) { - let interfaceToken = data.readInterfaceToken(); - console.log("RpcServer: interfaceToken is " + interfaceToken); + try { + let interfaceToken = data.readInterfaceToken(); + console.log("RpcServer: interfaceToken is " + interfaceToken); + } catch(error) { + console.info("RpcServer: read interfaceToken failed, errorCode " + error.code); + console.info("RpcServer: read interfaceToken failed, errorMessage " + error.message); + } return true; } } ``` - ### getSize getSize(): number -Obtains the data size of this **MessageParcel** object. +Obtains the data size of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Size of the **MessageParcel** object obtained, in bytes.| + | Type | Description | + | ------ | ----------------------------------------------- | + | number | Size of the **MessageSequence** object obtained, in bytes.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let size = data.getSize(); console.log("RpcClient: size is " + size); ``` - ### getCapacity getCapacity(): number -Obtains the capacity of this **MessageParcel** object. +Obtains the capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | **MessageParcel** capacity obtained, in bytes.| + | Type | Description| + | ------ | ----- | + | number | **MessageSequence** capacity obtained, in bytes.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let result = data.getCapacity(); console.log("RpcClient: capacity is " + result); ``` - ### setSize -setSize(size: number): boolean +setSize(size: number): void -Sets the size of data contained in this **MessageParcel** object. +Sets the size of data contained in this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | + | Name| Type | Mandatory| Description| + | ------ | ------ | ---- | ------ | | size | number | Yes| Data size to set, in bytes.| -**Return value** - - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ``` - let data = rpc.MessageParcel.create(); - let setSize = data.setSize(16); - console.log("RpcClient: setSize is " + setSize); + let data = rpc.MessageSequence.create(); + try { + data.setSize(16); + console.log("RpcClient: setSize is " + data.getSize()); + } catch(error) { + console.info("rpc set size of MessageSequence fail, errorCode " + error.code); + console.info("rpc set size of MessageSequence fail, errorMessage " + error.message); + } ``` - ### setCapacity -setCapacity(size: number): boolean +setCapacity(size: number): void -Sets the storage capacity of this **MessageParcel** object. +Sets the storage capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | size | number | Yes| Storage capacity to set, in bytes.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | --------------------------------------------- | + | size | number | Yes | Storage capacity of the **MessageSequence** object to set, in bytes.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------ | + | 1900011 | parcel memory alloc failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.setCapacity(100); - console.log("RpcClient: setCapacity is " + result); + let data = rpc.MessageSequence.create(); + try { + data.setCapacity(100); + console.log("RpcClient: setCapacity is " + data.getCapacity()); + } catch(error) { + console.info("rpc memory alloc fail, errorCode " + error.code); + console.info("rpc memory alloc fail, errorMessage " + error.message); + } ``` - ### getWritableBytes getWritableBytes(): number -Obtains the writable capacity of this **MessageParcel** object. +Obtains the writable capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | **MessageParcel** writable capacity obtained, in bytes.| + | ------ | ------ | + | number | **MessageSequence** writable capacity obtained, in bytes.| **Example** @@ -334,20 +369,19 @@ Obtains the writable capacity of this **MessageParcel** object. } ``` - ### getReadableBytes getReadableBytes(): number -Obtains the readable capacity of this **MessageParcel** object. +Obtains the readable capacity of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | **MessageParcel** object readable capacity, in bytes.| + | ------ | ------- | + | number | **MessageSequence** readable capacity obtained, in bytes.| **Example** @@ -361,57 +395,54 @@ Obtains the readable capacity of this **MessageParcel** object. } ``` - ### getReadPosition getReadPosition(): number -Obtains the read position of this **MessageParcel** object. +Obtains the read position of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | Current read position of the **MessageParcel** object.| + | ------ | ------ | + | number | Read position obtained.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let readPos = data.getReadPosition(); console.log("RpcClient: readPos is " + readPos); ``` - ### getWritePosition getWritePosition(): number -Obtains the write position of this **MessageParcel** object. +Obtains the write position of this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** | Type| Description| - | -------- | -------- | - | number | Current write position of the **MessageParcel** object.| + | ------ | ----- | + | number | Write position obtained.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); data.writeInt(10); let bwPos = data.getWritePosition(); console.log("RpcClient: bwPos is " + bwPos); ``` - ### rewindRead -rewindRead(pos: number): boolean +rewindRead(pos: number): void Moves the read pointer to the specified position. @@ -420,32 +451,30 @@ Moves the read pointer to the specified position. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | pos | number | Yes| Position from which data is to read.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the read position changes; returns **false** otherwise.| + | ------ | ------ | ---- | ------- | + | pos | number | Yes | Position from which data is to read.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); data.writeInt(12); - data.writeString("parcel"); + data.writeString("sequence"); let number = data.readInt(); console.log("RpcClient: number is " + number); - data.rewindRead(0); + try { + data.rewindRead(0); + } catch(error) { + console.info("rpc rewind read data fail, errorCode " + error.code); + console.info("rpc rewind read data fail, errorMessage " + error.message); + } let number2 = data.readInt(); console.log("RpcClient: rewindRead is " + number2); ``` - ### rewindWrite -rewindWrite(pos: number): boolean +rewindWrite(pos: number): void Moves the write pointer to the specified position. @@ -454,532 +483,721 @@ Moves the write pointer to the specified position. **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | pos | number | Yes| Position from which data is to write.| - -**Return value** - - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the write position changes; returns **false** otherwise.| + | ------ | ------ | ---- | ----- | + | pos | number | Yes | Position from which data is to write.| **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); data.writeInt(4); - data.rewindWrite(0); + try { + data.rewindWrite(0); + } catch(error) { + console.info("rpc rewind read data fail, errorCode " + error.code); + console.info("rpc rewind read data fail, errorMessage " + error.message); + } data.writeInt(5); let number = data.readInt(); console.log("RpcClient: rewindWrite is: " + number); ``` - ### writeByte -writeByte(val: number): boolean +writeByte(val: number): void -Writes a Byte value to this **MessageParcel** object. +Writes a byte value to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | + | Name| Type | Mandatory| Description| + | ----- | ------ | ---- | ----- | | val | number | Yes| Byte value to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeByte(2); - console.log("RpcClient: writeByte is: " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeByte(2); + } catch(error) { + console.info("rpc write byte fail, errorCode " + error.code); + console.info("rpc write byte fail, errorMessage" + error.message); + } ``` - ### readByte readByte(): number -Reads the Byte value from this **MessageParcel** object. +Reads the byte value from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description| + | ------ | ----- | | number | Byte value read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeByte(2); - console.log("RpcClient: writeByte is: " + result); - let ret = data.readByte(); - console.log("RpcClient: readByte is: " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeByte(2); + } catch(error) { + console.info("rpc write byte fail, errorCode " + error.code); + console.info("rpc write byte fail, errorMessage" + error.message); + } + try { + let ret = data.readByte(); + console.log("RpcClient: readByte is: " + ret); + } catch(error) { + console.info("rpc write byte fail, errorCode " + error.code); + console.info("rpc write byte fail, errorMessage" + error.message); + } ``` - ### writeShort -writeShort(val: number): boolean +writeShort(val: number): void -Writes a Short int value to this **MessageParcel** object. +Writes a short integer to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Short int value to write.| + | Name| Type | Mandatory| Description| + | ------ | ------ | --- | --- | + | val | number | Yes| Short integer to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShort(8); - console.log("RpcClient: writeShort is: " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeShort(8); + } catch(error) { + console.info("rpc write short fail, errorCode " + error.code); + console.info("rpc write short fail, errorMessage" + error.message); + } ``` - ### readShort readShort(): number -Reads the Short int value from this **MessageParcel** object. +Reads the short integer from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Short int value read.| + | Type | Description | + | ------ | -------------- | + | number | Short integer read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShort(8); - console.log("RpcClient: writeShort is: " + result); - let ret = data.readShort(); - console.log("RpcClient: readShort is: " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeShort(8); + } catch(error) { + console.info("rpc write short fail, errorCode " + error.code); + console.info("rpc write short fail, errorMessage" + error.message); + } + try { + let ret = data.readShort(8); + } catch(error) { + console.info("rpc read short fail, errorCode " + error.code); + console.info("rpc read short fail, errorMessage" + error.message); + } + console.log("RpcClient: readByte is: " + ret); ``` - ### writeInt -writeInt(val: number): boolean +writeInt(val: number): void -Writes an Int value to this **MessageParcel** object. +Writes an integer to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Int value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Integer to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeInt(10); - console.log("RpcClient: writeInt is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeInt(10); + } catch(error) { + console.info("rpc write int fail, errorCode " + error.code); + console.info("rpc write int fail, errorMessage" + error.message); + } ``` - ### readInt readInt(): number -Reads the Int value from this **MessageParcel** object. +Reads the integer from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Int value read.| + | Type | Description | + | ------ | ------------ | + | number | Integer read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeInt(10); - console.log("RpcClient: writeInt is " + result); - let ret = data.readInt(); - console.log("RpcClient: readInt is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeInt(10); + } catch(error) { + console.info("rpc write int fail, errorCode " + error.code); + console.info("rpc write int fail, errorMessage" + error.message); + } + try { + let ret = data.readInt(); + console.log("RpcClient: readInt is " + ret); + } catch(error) { + console.info("rpc read int fail, errorCode " + error.code); + console.info("rpc read int fail, errorMessage" + error.message); + } ``` - ### writeLong -writeLong(val: number): boolean +writeLong(val: number): void -Writes a Long int value to this **MessageParcel** object. +Writes a long integer to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Long int value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Long integer to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLong(10000); - console.log("RpcClient: writeLong is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeLong(10000); + } catch(error) { + console.info("rpc write long fail, errorCode " + error.code); + console.info("rpc write long fail, errorMessage" + error.message); + } ``` - ### readLong readLong(): number -Reads the Long int value from this **MessageParcel** object. +Reads the long integer from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Long int value read.| + | Type | Description | + | ------ | -------------- | + | number | Long integer read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLong(10000); - console.log("RpcClient: writeLong is " + result); - let ret = data.readLong(); - console.log("RpcClient: readLong is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeLong(10000); + } catch(error) { + console.info("rpc write long fail, errorCode " + error.code); + console.info("rpc write long fail, errorMessage" + error.message); + } + try { + let ret = data.readLong(); + console.log("RpcClient: readLong is " + ret); + } catch(error) { + console.info("rpc read long fail, errorCode " + error.code); + console.info("rpc read long fail, errorMessage" + error.message); + } ``` - ### writeFloat -writeFloat(val: number): boolean +writeFloat(val: number): void -Writes a Float value to this **MessageParcel** object. +Writes a floating-point number to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Float value to write.| + | ----- | ---- | ---- | ----- | + | val | number | Yes| Floating-point number to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloat(1.2); - console.log("RpcClient: writeFloat is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeFloat(1.2); + } catch(error) { + console.info("rpc write float fail, errorCode " + error.code); + console.info("rpc write float fail, errorMessage" + error.message); + } ``` - ### readFloat readFloat(): number -Reads the Float value from this **MessageParcel** object. +Reads the floating-pointer number from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Float value read.| + | Type | Description | + | ------ | ------------ | + | number | Floating-point number read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloat(1.2); - console.log("RpcClient: writeFloat is " + result); - let ret = data.readFloat(); - console.log("RpcClient: readFloat is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeFloat(1.2); + } catch(error) { + console.info("rpc write float fail, errorCode " + error.code); + console.info("rpc write float fail, errorMessage" + error.message); + } + try { + let ret = data.readFloat(); + console.log("RpcClient: readFloat is " + ret); + } catch(error) { + console.info("rpc read float fail, errorCode " + error.code); + console.info("rpc read float fail, errorMessage" + error.message); + } ``` - ### writeDouble -writeDouble(val: number): boolean +writeDouble(val: number): void -Writes a Double value to this **MessageParcel** object. +Writes a double-precision floating-point number to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Double value to write.| + | ------ | ------ | ---- | ------ | + | val number | Yes| Double-precision floating-point number to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDouble(10.2); - console.log("RpcClient: writeDouble is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeDouble(10.2); + } catch(error) { + console.info("rpc read float fail, errorCode " + error.code); + console.info("rpc read float fail, errorMessage" + error.message); + } ``` - ### readDouble readDouble(): number -Reads the Double value from this **MessageParcel** object. +Reads the double-precision floating-point number from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Double value read.| + | Type | Description | + | ------ | ------------------ | + | number | Double-precision floating-point number read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDouble(10.2); - console.log("RpcClient: writeDouble is " + result); - let ret = data.readDouble(); - console.log("RpcClient: readDouble is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeDouble(10.2); + } catch(error) { + console.info("rpc write double fail, errorCode " + error.code); + console.info("rpc write double fail, errorMessage" + error.message); + } + try { + let ret = data.readDouble(); + console.log("RpcClient: readDouble is " + ret); + } catch(error) { + console.info("rpc read double fail, errorCode " + error.code); + console.info("rpc read double fail, errorMessage" + error.message); + } ``` - ### writeBoolean -writeBoolean(val: boolean): boolean +writeBoolean(val: boolean): void -Writes a Boolean value to this **MessageParcel** object. +Writes a Boolean value to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | boolean | Yes| Boolean value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------- | ---- | ---------------- | + | val | boolean | Yes | Boolean value to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBoolean(false); - console.log("RpcClient: writeBoolean is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeBoolean(false); + } catch(error) { + console.info("rpc write boolean fail, errorCode " + error.code); + console.info("rpc write boolean fail, errorMessage" + error.message); + } ``` - ### readBoolean readBoolean(): boolean -Reads the Boolean value from this **MessageParcel** object. +Reads the Boolean value from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | -------------------- | | boolean | Boolean value read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBoolean(false); - console.log("RpcClient: writeBoolean is " + result); - let ret = data.readBoolean(); - console.log("RpcClient: readBoolean is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeBoolean(false); + } catch(error) { + console.info("rpc write boolean fail, errorCode " + error.code); + console.info("rpc write boolean fail, errorMessage" + error.message); + } + try { + let ret = data.readBoolean(); + console.log("RpcClient: readBoolean is " + ret); + } catch(error) { + console.info("rpc read boolean fail, errorCode " + error.code); + console.info("rpc read boolean fail, errorMessage" + error.message); + } ``` - ### writeChar -writeChar(val: number): boolean +writeChar(val: number): void -Writes a Char value to this **MessageParcel** object. +Writes a character to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | number | Yes| Char value to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | val | number | Yes | Single character to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeChar(97); - console.log("RpcClient: writeChar is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeChar(97); + } catch(error) { + console.info("rpc write char fail, errorCode " + error.code); + console.info("rpc write char fail, errorMessage" + error.message); + } ``` - ### readChar readChar(): number -Reads the Char value from this **MessageParcel** object. +Reads the character from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | Char value read.| + | Type | Description| + | ------ | ---- | + | number | Character read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------ | --------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeChar(97); - console.log("RpcClient: writeChar is " + result); - let ret = data.readChar(); - console.log("RpcClient: readChar is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeChar(97); + } catch(error) { + console.info("rpc write char fail, errorCode " + error.code); + console.info("rpc write char fail, errorMessage" + error.message); + } + try { + let ret = data.readChar(); + console.log("RpcClient: readChar is " + ret); + } catch(error) { + console.info("rpc read char fail, errorCode " + error.code); + console.info("rpc read char fail, errorMessage" + error.message); + } ``` - ### writeString -writeString(val: string): boolean +writeString(val: string): void -Writes a string to this **MessageParcel** object. +Writes a string to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | string | Yes| String to write. The length of the string must be less than 40960 bytes.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ----------------------------------------- | + | val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeString('abc'); - console.log("RpcClient: writeString is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeString('abc'); + } catch(error) { + console.info("rpc write string fail, errorCode " + error.code); + console.info("rpc write string fail, errorMessage" + error.message); + } ``` - ### readString readString(): string -Reads a string from this **MessageParcel** object. +Reads the string from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------------- | | string | String read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeString('abc'); - console.log("RpcClient: writeString is " + result); - let ret = data.readString(); - console.log("RpcClient: readString is " + ret); + let data = rpc.MessageSequence.create(); + try { + data.writeString('abc'); + } catch(error) { + console.info("rpc write string fail, errorCode " + error.code); + console.info("rpc write string fail, errorMessage" + error.message); + } + try { + let ret = data.readString(); + console.log("RpcClient: readString is " + ret); + } catch(error) { + console.info("rpc read string fail, errorCode " + error.code); + console.info("rpc read string fail, errorMessage" + error.message); + } ``` +### writeParcelable -### writeSequenceable - -writeSequenceable(val: Sequenceable): boolean +writeParcelable(val: Parcelable): void -Writes a sequenceable object to this **MessageParcel** object. +Writes a **Parcelable** object to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | val | [Sequenceable](#sequenceable) | Yes| Sequenceable object to write.| + | ------ | --------- | ---- | ------ | + | val | Parcelable | Yes | **Parcelable** object to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** @@ -991,43 +1209,49 @@ Writes a sequenceable object to this **MessageParcel** object. this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceable(sequenceable); - console.log("RpcClient: writeSequenceable is " + result); + let parcelable = new MySequenceable(1, "aaa"); + let data = rpc.MessageSequence.create(); + try { + data.writeParcelable(parcelable); + } catch(error) { + console.info("rpc write parcelable fail, errorCode " + error.code); + console.info("rpc write parcelable fail, errorMessage" + error.message); + } ``` +### readParcelable -### readSequenceable - -readSequenceable(dataIn: Sequenceable) : boolean +readParcelable(dataIn: Parcelable): void -Reads member variables from this **MessageParcel** object. +Reads a **Parcelable** object from this **MessageSequence** object to the specified object (**dataIn**). **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | [Sequenceable](#sequenceable) | Yes| Object that reads member variables from the **MessageParcel** object.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------- | ---- | ----------------------------------------- | + | dataIn | Parcelable | Yes | **Parcelable** object to read.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + | 1900012 | call js callback function failed | **Example** @@ -1039,774 +1263,1110 @@ Reads member variables from this **MessageParcel** object. this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceable(sequenceable); - console.log("RpcClient: writeSequenceable is " + result); + let parcelable = new MySequenceable(1, "aaa"); + let data = rpc.MessageSequence.create(); + data.writeParcelable(parcelable); let ret = new MySequenceable(0, ""); - let result2 = data.readSequenceable(ret); - console.log("RpcClient: writeSequenceable is " + result2); + try { + data.readParcelable(ret); + }catch(error) { + console.info("rpc read parcelable fail, errorCode " + error.code); + console.info("rpc read parcelable fail, errorMessage" + error.message); + } ``` - ### writeByteArray -writeByteArray(byteArray: number[]): boolean +writeByteArray(byteArray: number[]): void -Writes a byte array to this **MessageParcel** object. +Writes a byte array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | byteArray | number[] | Yes| Byte array to write.| + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ------------------ | + | byteArray | number[] | Yes | Byte array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; - let result = data.writeByteArray(ByteArrayVar); - console.log("RpcClient: writeByteArray is " + result); + try { + data.writeByteArray(ByteArrayVar); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } ``` - ### readByteArray -readByteArray(dataIn: number[]) : void +readByteArray(dataIn: number[]): void -Reads a byte array from this **MessageParcel** object. +Reads a byte array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Byte array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Byte array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let ByteArrayVar = [1, 2, 3, 4, 5]; - let result = data.writeByteArray(ByteArrayVar); - console.log("RpcClient: writeByteArray is " + result); - let array = new Array(5); - data.readByteArray(array); + try { + data.writeByteArray(ByteArrayVar); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } + try { + let array = new Array(5); + data.readByteArray(array); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } ``` - ### readByteArray readByteArray(): number[] -Reads the byte array from this **MessageParcel** object. +Reads the byte array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | -------------- | | number[] | Byte array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let ByteArrayVar = [1, 2, 3, 4, 5]; - let result = data.writeByteArray(ByteArrayVar); - console.log("RpcClient: writeByteArray is " + result); - let array = data.readByteArray(); - console.log("RpcClient: readByteArray is " + array); + let data = rpc.MessageSequence.create(); + let byteArrayVar = [1, 2, 3, 4, 5]; + try { + data.writeByteArray(byteArrayVar); + } catch(error) { + console.info("rpc write byteArray fail, errorCode " + error.code); + console.info("rpc write byteArray fail, errorMessage" + error.message); + } + try { + let array = data.readByteArray(); + console.log("RpcClient: readByteArray is " + array); + } catch(error) { + console.info("rpc read byteArray fail, errorCode " + error.code); + console.info("rpc read byteArray fail, errorMessage" + error.message); + } ``` - ### writeShortArray -writeShortArray(shortArray: number[]): boolean +writeShortArray(shortArray: number[]): void -Writes a short array to this **MessageParcel** object. +Writes a short array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | shortArray | number[] | Yes| Short array to write.| + | Name | Type | Mandatory| Description | + | ---------- | -------- | ---- | -------------------- | + | shortArray | number[] | Yes | Short array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ----- | ----- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShortArray([11, 12, 13]); - console.log("RpcClient: writeShortArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeShortArray([11, 12, 13]); + } catch(error) { + console.info("rpc read byteArray fail, errorCode " + error.code); + console.info("rpc read byteArray fail, errorMessage" + error.message); + } ``` - ### readShortArray -readShortArray(dataIn: number[]) : void +readShortArray(dataIn: number[]): void -Reads a short array from this **MessageParcel** object. +Reads a short array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Short array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Short array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------ | ------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShortArray([11, 12, 13]); - console.log("RpcClient: writeShortArray is " + result); - let array = new Array(3); - data.readShortArray(array); + let data = rpc.MessageSequence.create(); + try { + data.writeShortArray([11, 12, 13]); + } catch(error) { + console.info("rpc write shortArray fail, errorCode " + error.code); + console.info("rpc write shortArray fail, errorMessage" + error.message); + } + try { + let array = new Array(3); + data.readShortArray(array); + } catch(error) { + console.info("rpc read shortArray fail, errorCode " + error.code); + console.info("rpc read shortArray fail, errorMessage" + error.message); + } ``` - ### readShortArray readShortArray(): number[] -Reads the short array from this **MessageParcel** object. +Reads the short array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | number[] | Short array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeShortArray([11, 12, 13]); - console.log("RpcClient: writeShortArray is " + result); - let array = data.readShortArray(); - console.log("RpcClient: readShortArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeShortArray([11, 12, 13]); + } catch(error) { + console.info("rpc write shortArray fail, errorCode " + error.code); + console.info("rpc write shortArray fail, errorMessage" + error.message); + } + try { + let array = data.readShortArray(); + console.log("RpcClient: readShortArray is " + array); + } catch(error) { + console.info("rpc read shortArray fail, errorCode " + error.code); + console.info("rpc read shortArray fail, errorMessage" + error.message); + } ``` - ### writeIntArray -writeIntArray(intArray: number[]): boolean +writeIntArray(intArray: number[]): void -Writes an integer array to this **MessageParcel** object. +Writes an integer array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | intArray | number[] | Yes| Integer array to write.| + | Name | Type | Mandatory| Description | + | -------- | -------- | ---- | ------------------ | + | intArray | number[] | Yes | Integer array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ----- | --------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeIntArray([100, 111, 112]); - console.log("RpcClient: writeIntArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeIntArray([100, 111, 112]); + } catch(error) { + console.info("rpc write intArray fail, errorCode " + error.code); + console.info("rpc write intArray fail, errorMessage" + error.message); + } ``` - ### readIntArray -readIntArray(dataIn: number[]) : void +readIntArray(dataIn: number[]): void -Reads an integer array from this **MessageParcel** object. +Reads an integer array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Integer array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Integer array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeIntArray([100, 111, 112]); - console.log("RpcClient: writeIntArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeIntArray([100, 111, 112]); + } catch(error) { + console.info("rpc write intArray fail, errorCode " + error.code); + console.info("rpc write intArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readIntArray(array); + try { + data.readIntArray(array); + } catch(error) { + console.info("rpc read intArray fail, errorCode " + error.code); + console.info("rpc read intArray fail, errorMessage" + error.message); + } ``` - ### readIntArray readIntArray(): number[] -Reads the integer array from this **MessageParcel** object. +Reads the integer array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | -------------- | | number[] | Integer array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ----- | ------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeIntArray([100, 111, 112]); - console.log("RpcClient: writeIntArray is " + result); - let array = data.readIntArray(); - console.log("RpcClient: readIntArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeIntArray([100, 111, 112]); + } catch(error) { + console.info("rpc write intArray fail, errorCode " + error.code); + console.info("rpc write intArray fail, errorMessage" + error.message); + } + try { + let array = data.readIntArray(); + console.log("RpcClient: readIntArray is " + array); + } catch(error) { + console.info("rpc read intArray fail, errorCode " + error.code); + console.info("rpc read intArray fail, errorMessage" + error.message); + } ``` - ### writeLongArray -writeLongArray(longArray: number[]): boolean +writeLongArray(longArray: number[]): void -Writes a long array to this **MessageParcel** object. +Writes a long array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | longArray | number[] | Yes| Long array to write.| + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | -------------------- | + | longArray | number[] | Yes | Long array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ----- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLongArray([1111, 1112, 1113]); - console.log("RpcClient: writeLongArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeLongArray([1111, 1112, 1113]); + }catch(error){ + console.info("rpc write longArray fail, errorCode " + error.code); + console.info("rpc write longArray fail, errorMessage" + error.message); + } ``` - ### readLongArray -readLongArray(dataIn: number[]) : void +readLongArray(dataIn: number[]): void -Reads a long array from this **MessageParcel** object. +Reads a long array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Long array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Long array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLongArray([1111, 1112, 1113]); - console.log("RpcClient: writeLongArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeLongArray([1111, 1112, 1113]); + } catch(error) { + console.info("rpc write longArray fail, errorCode " + error.code); + console.info("rpc write longArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readLongArray(array); + try { + data.readLongArray(array); + } catch(error) { + console.info("rpc read longArray fail, errorCode " + error.code); + console.info("rpc read longArray fail, errorMessage" + error.message); + } ``` - ### readLongArray readLongArray(): number[] -Reads the long array from this **MessageParcel** object. +Reads the long array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | number[] | Long array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeLongArray([1111, 1112, 1113]); - console.log("RpcClient: writeLongArray is " + result); - let array = data.readLongArray(); - console.log("RpcClient: readLongArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeLongArray([1111, 1112, 1113]); + } catch(error) { + console.info("rpc write longArray fail, errorCode " + error.code); + console.info("rpc write longArray fail, errorMessage" + error.message); + } + try { + let array = data.readLongArray(); + console.log("RpcClient: readLongArray is " + array); + } catch(error) { + console.info("rpc read longArray fail, errorCode " + error.code); + console.info("rpc read longArray fail, errorMessage" + error.message); + } ``` - ### writeFloatArray -writeFloatArray(floatArray: number[]): boolean +writeFloatArray(floatArray: number[]): void -Writes a FloatArray to this **MessageParcel** object. +Writes a floating-point array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | floatArray | number[] | Yes| FloatArray to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + | Name | Type | Mandatory| Description | + | ---------- | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | + | floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloatArray([1.2, 1.3, 1.4]); - console.log("RpcClient: writeFloatArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeFloatArray([1.2, 1.3, 1.4]); + } catch(error) { + console.info("rpc write floatArray fail, errorCode " + error.code); + console.info("rpc write floatArray fail, errorMessage" + error.message); + } ``` - ### readFloatArray -readFloatArray(dataIn: number[]) : void +readFloatArray(dataIn: number[]): void -Reads a FloatArray from this **MessageParcel** object. +Reads a floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| FloatArray to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ----------------------------------------------------------------------------------------------------------------------- | + | dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + +**Error codes** +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloatArray([1.2, 1.3, 1.4]); - console.log("RpcClient: writeFloatArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeFloatArray([1.2, 1.3, 1.4]); + }catch(error){ + console.info("rpc write floatArray fail, errorCode " + error.code); + console.info("rpc write floatArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readFloatArray(array); + try { + data.readFloatArray(array); + } catch(error) { + console.info("rpc read floatArray fail, errorCode " + error.code); + console.info("rpc read floatArray fail, errorMessage" + error.message); + } ``` - ### readFloatArray readFloatArray(): number[] -Reads the FloatArray from this **MessageParcel** object. +Reads the floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number[] | FloatArray read.| + | Type | Description | + | -------- | -------------- | + | number[] | Floating-point array read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeFloatArray([1.2, 1.3, 1.4]); - console.log("RpcClient: writeFloatArray is " + result); - let array = data.readFloatArray(); - console.log("RpcClient: readFloatArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeFloatArray([1.2, 1.3, 1.4]); + } catch(error) { + console.info("rpc write floatArray fail, errorCode " + error.code); + console.info("rpc write floatArray fail, errorMessage" + error.message); + } + try { + let array = data.readFloatArray(); + console.log("RpcClient: readFloatArray is " + array); + } catch(error) { + console.info("rpc read floatArray fail, errorCode " + error.code); + console.info("rpc read floatArray fail, errorMessage" + error.message); + } ``` - ### writeDoubleArray -writeDoubleArray(doubleArray: number[]): boolean +writeDoubleArray(doubleArray: number[]): void -Writes a DoubleArray to this **MessageParcel** object. +Writes a double-precision floating-point array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | doubleArray | number[] | Yes| DoubleArray to write.| + | Name | Type | Mandatory| Description | + | ----------- | -------- | ---- | ------------------------ | + | doubleArray | number[] | Yes | Double-precision floating-point array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDoubleArray([11.1, 12.2, 13.3]); - console.log("RpcClient: writeDoubleArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeDoubleArray([11.1, 12.2, 13.3]); + } catch(error) { + console.info("rpc write doubleArray fail, errorCode " + error.code); + console.info("rpc write doubleArray fail, errorMessage" + error.message); + } ``` - ### readDoubleArray -readDoubleArray(dataIn: number[]) : void +readDoubleArray(dataIn: number[]): void -Reads a DoubleArray from this **MessageParcel** object. +Reads a double-precision floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| DoubleArray to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------------ | + | dataIn | number[] | Yes | Double-precision floating-point array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDoubleArray([11.1, 12.2, 13.3]); - console.log("RpcClient: writeDoubleArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeDoubleArray([11.1, 12.2, 13.3]); + } catch(error) { + console.info("rpc write doubleArray fail, errorCode " + error.code); + console.info("rpc write doubleArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readDoubleArray(array); + try { + data.readDoubleArray(array); + } catch(error) { + console.info("rpc read doubleArray fail, errorCode " + error.code); + console.info("rpc read doubleArray fail, errorMessage" + error.message); + } ``` - ### readDoubleArray readDoubleArray(): number[] -Reads the DoubleArray from this **MessageParcel** object. +Reads the double-precision floating-point array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number[] | DoubleArray read.| + | Type | Description | + | -------- | -------------------- | + | number[] | Double-precision floating-point array read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeDoubleArray([11.1, 12.2, 13.3]); - console.log("RpcClient: writeDoubleArray is " + result); - let array = data.readDoubleArray(); - console.log("RpcClient: readDoubleArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeDoubleArray([11.1, 12.2, 13.3]); + } catch(error) { + console.info("rpc write doubleArray fail, errorCode " + error.code); + console.info("rpc write doubleArray fail, errorMessage" + error.message); + } + try { + let array = data.readDoubleArray(); + console.log("RpcClient: readDoubleArray is " + array); + } catch(error) { + console.info("rpc read doubleArray fail, errorCode " + error.code); + console.info("rpc read doubleArray fail, errorMessage" + error.message); + } ``` - ### writeBooleanArray -writeBooleanArray(booleanArray: boolean[]): boolean +writeBooleanArray(booleanArray: boolean[]): void -Writes a Boolean array to this **MessageParcel** object. +Writes a Boolean array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | booleanArray | boolean[] | Yes| Boolean array to write.| + | Name | Type | Mandatory| Description | + | ------------ | --------- | ---- | ------------------ | + | booleanArray | boolean[] | Yes | Boolean array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBooleanArray([false, true, false]); - console.log("RpcClient: writeBooleanArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeBooleanArray([false, true, false]); + } catch(error) { + console.info("rpc write booleanArray fail, errorCode " + error.code); + console.info("rpc write booleanArray fail, errorMessage" + error.message); + } ``` - ### readBooleanArray -readBooleanArray(dataIn: boolean[]) : void +readBooleanArray(dataIn: boolean[]): void -Reads a Boolean array from this **MessageParcel** object. +Reads a Boolean array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | boolean[] | Yes| Boolean array to read.| + | Name| Type | Mandatory| Description | + | ------ | --------- | ---- | ------------------ | + | dataIn | boolean[] | Yes | Boolean array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBooleanArray([false, true, false]); - console.log("RpcClient: writeBooleanArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeBooleanArray([false, true, false]); + } catch(error) { + console.info("rpc write booleanArray fail, errorCode " + error.code); + console.info("rpc write booleanArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readBooleanArray(array); + try { + data.readBooleanArray(array); + } catch(error) { + console.info("rpc read booleanArray fail, errorCode " + error.code); + console.info("rpc read booleanArray fail, errorMessage" + error.message); + } ``` - ### readBooleanArray readBooleanArray(): boolean[] -Reads the Boolean array from this **MessageParcel** object. +Reads the Boolean array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | --------- | -------------- | | boolean[] | Boolean array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + +**Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeBooleanArray([false, true, false]); - console.log("RpcClient: writeBooleanArray is " + result); - let array = data.readBooleanArray(); - console.log("RpcClient: readBooleanArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeBooleanArray([false, true, false]); + } catch(error) { + console.info("rpc write booleanArray fail, errorCode " + error.code); + console.info("rpc write booleanArray fail, errorMessage" + error.message); + } + try { + let array = data.readBooleanArray(); + console.log("RpcClient: readBooleanArray is " + array); + } catch(error) { + console.info("rpc read booleanArray fail, errorCode " + error.code); + console.info("rpc read booleanArray fail, errorMessage" + error.message); + } ``` - ### writeCharArray -writeCharArray(charArray: number[]): boolean +writeCharArray(charArray: number[]): void -Writes a character array to this **MessageParcel** object. +Writes a character array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | charArray | number[] | Yes| Character array to write.| + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ---------------------- | + | charArray | number[] | Yes | Character array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------ | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeCharArray([97, 98, 88]); - console.log("RpcClient: writeCharArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeCharArray([97, 98, 88]); + } catch(error) { + console.info("rpc write charArray fail, errorCode " + error.code); + console.info("rpc write charArray fail, errorMessage" + error.message); + } ``` - ### readCharArray -readCharArray(dataIn: number[]) : void +readCharArray(dataIn: number[]): void -Reads a character array from this **MessageParcel** object. +Reads a character array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | number[] | Yes| Character array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ---------------------- | + | dataIn | number[] | Yes | Character array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeCharArray([97, 98, 99]); - console.log("RpcClient: writeCharArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeCharArray([97, 98, 88]); + } catch(error) { + console.info("rpc write charArray fail, errorCode " + error.code); + console.info("rpc write charArray fail, errorMessage" + error.message); + } let array = new Array(3); - data.readCharArray(array); + try { + data.readCharArray(array); + } catch(error) { + console.info("rpc read charArray fail, errorCode " + error.code); + console.info("rpc read charArray fail, errorMessage" + error.message); + } ``` - ### readCharArray readCharArray(): number[] -Reads the character array from this **MessageParcel** object. +Reads the character array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ------------------ | | number[] | Character array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeCharArray([97, 98, 99]); - console.log("RpcClient: writeCharArray is " + result); - let array = data.readCharArray(); - console.log("RpcClient: readCharArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeCharArray([97, 98, 88]); + } catch(error) { + console.info("rpc write charArray fail, errorCode " + error.code); + console.info("rpc write charArray fail, errorMessage" + error.message); + } + let array = new Array(3); + try { + let array = data.readCharArray(); + console.log("RpcClient: readCharArray is " + array); + } catch(error) { + console.info("rpc read charArray fail, errorCode " + error.code); + console.info("rpc read charArray fail, errorMessage" + error.message); + } ``` - ### writeStringArray -writeStringArray(stringArray: string[]): boolean +writeStringArray(stringArray: string[]): void -Writes a string array to this **MessageParcel** object. +Writes a string array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | stringArray | string[] | Yes| String array to write. The length of a single element in the array must be less than 40960 bytes.| + | Name | Type | Mandatory| Description | + | ----------- | -------- | ---- | ------------------------------------------------------- | + | stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeStringArray(["abc", "def"]); - console.log("RpcClient: writeStringArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeStringArray(["abc", "def"]); + } catch(error) { + console.info("rpc write stringArray fail, errorCode " + error.code); + console.info("rpc write stringArray fail, errorMessage" + error.message); + } ``` - ### readStringArray -readStringArray(dataIn: string[]) : void +readStringArray(dataIn: string[]): void -Reads a string array from this **MessageParcel** object. +Reads a string array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | string[] | Yes| String array to read.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | string[] | Yes | String array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeStringArray(["abc", "def"]); - console.log("RpcClient: writeStringArray is " + result); + let data = rpc.MessageSequence.create(); + try { + data.writeStringArray(["abc", "def"]); + } catch(error) { + console.info("rpc write stringArray fail, errorCode " + error.code); + console.info("rpc write stringArray fail, errorMessage" + error.message); + } let array = new Array(2); - data.readStringArray(array); + try { + data.readStringArray(array); + } catch(error) { + console.info("rpc read stringArray fail, errorCode " + error.code); + console.info("rpc read stringArray fail, errorMessage" + error.message); + } ``` - ### readStringArray readStringArray(): string[] -Reads the string array from this **MessageParcel** object. +Reads the string array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | string[] | String array read.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` - let data = rpc.MessageParcel.create(); - let result = data.writeStringArray(["abc", "def"]); - console.log("RpcClient: writeStringArray is " + result); - let array = data.readStringArray(); - console.log("RpcClient: readStringArray is " + array); + let data = rpc.MessageSequence.create(); + try { + data.writeStringArray(["abc", "def"]); + } catch(error) { + console.info("rpc write stringArray fail, errorCode " + error.code); + console.info("rpc write stringArray fail, errorMessage" + error.message); + } + try { + let array = data.readStringArray(); + console.log("RpcClient: readStringArray is " + array); + } catch(error) { + console.info("rpc read stringArray fail, errorCode " + error.code); + console.info("rpc read stringArray fail, errorMessage" + error.message); + } ``` - -### writeNoException8+ +### writeNoException writeNoException(): void -Writes information to this **MessageParcel** object indicating that no exception occurred. +Writes information to this **MessageSequence** object indicating that no exception occurred. **System capability**: SystemCapability.Communication.IPC.Core +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | + **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } + onRemoteRequest(code, data, reply, option) { if (code === 1) { console.log("RpcServer: onRemoteRequest called"); - reply.writeNoException(); + try { + reply.writeNoException(); + } catch(error) { + console.info("rpc write no exception fail, errorCode " + error.code); + console.info("rpc write no exception fail, errorMessage" + error.message); + } return true; } else { console.log("RpcServer: unknown code: " + code); @@ -1816,15 +2376,22 @@ Writes information to this **MessageParcel** object indicating that no exception } ``` - -### readException8+ +### readException readException(): void -Reads the exception information from this **MessageParcel** object. +Reads the exception information from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + **Example** ``` @@ -1848,194 +2415,219 @@ Reads the exception information from this **MessageParcel** object. }; FA.connectAbility(want, connect); let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); data.writeInt(1); data.writeString("hello"); - proxy.sendRequestAsync(1, data, reply, option) + proxy.sendMessageRequest(1, data, reply, option) .then(function(errCode) { if (errCode === 0) { - console.log("sendRequestAsync got result"); - reply.readException(); + console.log("sendMessageRequest got result"); + try { + reply.readException(); + } catch(error) { + console.info("rpc read exception fail, errorCode " + error.code); + console.info("rpc read no exception fail, errorMessage" + error.message); + } let msg = reply.readString(); console.log("RPCTest: reply msg: " + msg); } else { - console.log("RPCTest: sendRequestAsync failed, errCode: " + errCode); + console.log("RPCTest: sendMessageRequest failed, errCode: " + errCode); } }).catch(function(e) { - console.log("RPCTest: sendRequestAsync got exception: " + e.message); + console.log("RPCTest: sendMessageRequest got exception: " + e.message); }).finally (() => { - console.log("RPCTest: sendRequestAsync ends, reclaim parcel"); + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); data.reclaim(); reply.reclaim(); }); ``` +### writeParcelableArray -### writeSequenceableArray - -writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean +writeParcelableArray(parcelableArray: Parcelable[]): void -Writes a sequenceable array to this **MessageParcel** object. +Writes a **Parcelable** array to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sequenceableArray | Sequenceable[] | Yes| Sequenceable array to write.| + | Name | Type | Mandatory| Description | + | --------------- | ------------ | ---- | -------------------------- | + | parcelableArray | Parcelable[] | Yes | **Parcelable** array to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900009 | write data to message sequence failed | **Example** ``` - class MySequenceable { + class MyParcelable { num: number; str: string; constructor(num, str) { this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let sequenceable2 = new MySequenceable(2, "bbb"); - let sequenceable3 = new MySequenceable(3, "ccc"); - let a = [sequenceable, sequenceable2, sequenceable3]; - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceableArray(a); - console.log("RpcClient: writeSequenceableArray is " + result); + let parcelable = new MyParcelable(1, "aaa"); + let parcelable2 = new MyParcelable(2, "bbb"); + let parcelable3 = new MyParcelable(3, "ccc"); + let a = [parcelable, parcelable2, parcelable3]; + let data = rpc.MessageSequence.create(); + try { + data.writeParcelableArray(a); + } catch(error) { + console.info("rpc write parcelable array fail, errorCode " + error.code); + console.info("rpc write parcelable array fail, errorMessage" + error.message); + } ``` +### readParcelableArray -### readSequenceableArray8+ - -readSequenceableArray(sequenceableArray: Sequenceable[]): void +readParcelableArray(parcelableArray: Parcelable[]): void -Reads a sequenceable array from this **MessageParcel** object. +Reads a **Parcelable** array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | sequenceableArray | Sequenceable[] | Yes| Sequenceable array to read.| + | Name | Type | Mandatory| Description | + | --------------- | ------------ | ---- | -------------------------- | + | parcelableArray | Parcelable[] | Yes | **Parcelable** array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + | 1900012 | call js callback function failed | **Example** ``` - class MySequenceable { + class MyParcelable { num: number; str: string; constructor(num, str) { this.num = num; this.str = str; } - marshalling(messageParcel) { - messageParcel.writeInt(this.num); - messageParcel.writeString(this.str); + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); return true; } - unmarshalling(messageParcel) { - this.num = messageParcel.readInt(); - this.str = messageParcel.readString(); + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); return true; } } - let sequenceable = new MySequenceable(1, "aaa"); - let sequenceable2 = new MySequenceable(2, "bbb"); - let sequenceable3 = new MySequenceable(3, "ccc"); - let a = [sequenceable, sequenceable2, sequenceable3]; - let data = rpc.MessageParcel.create(); - let result = data.writeSequenceableArray(a); - console.log("RpcClient: writeSequenceableArray is " + result); - let b = [new MySequenceable(0, ""), new MySequenceable(0, ""), new MySequenceable(0, "")]; - data.readSequenceableArray(b); + let parcelable = new MyParcelable(1, "aaa"); + let parcelable2 = new MyParcelable(2, "bbb"); + let parcelable3 = new MyParcelable(3, "ccc"); + let a = [parcelable, parcelable2, parcelable3]; + let data = rpc.MessageSequence.create(); + let result = data.writeParcelableArray(a); + console.log("RpcClient: writeParcelableArray is " + result); + let b = [new MyParcelable(0, ""), new MyParcelable(0, ""), new MyParcelable(0, "")]; + try { + data.readParcelableArray(b); + } catch(error) { + console.info("rpc read parcelable array fail, errorCode " + error.code); + console.info("rpc read parcelable array fail, errorMessage" + error.message); + } + data.readParcelableArray(b); ``` +### writeRemoteObjectArray -### writeRemoteObjectArray8+ - -writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean +writeRemoteObjectArray(objectArray: IRemoteObject[]): void -Writes an array of **IRemoteObject** objects to this **MessageParcel** object. +Writes an array of **IRemoteObject** objects to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | objectArray | IRemoteObject[] | Yes| Array of **IRemoteObject** objects to write.| + | Name | Type | Mandatory| Description | + | ----------- | --------------- | ---- | ---------------------------------------------- | + | objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900009 | write data to message sequence failed | **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); - this.attachLocalInterface(this, descriptor); - } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; + this.modifyLocalInterface(this, descriptor); } + asObject(): rpc.IRemoteObject { return this; } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; - let data = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); let result = data.writeRemoteObjectArray(a); + try { + data.writeRemoteObjectArray(a); + } catch(error) { + console.info("rpc write remote object array fail, errorCode " + error.code); + console.info("rpc write remote object array fail, errorMessage" + error.message); + } console.log("RpcClient: writeRemoteObjectArray is " + result); ``` - -### readRemoteObjectArray8+ +### readRemoteObjectArray readRemoteObjectArray(objects: IRemoteObject[]): void -Reads an **IRemoteObject** array from this **MessageParcel** object. +Reads an array of **IRemoteObject** objects from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | objects | IRemoteObject[] | Yes| **IRemoteObject** array to read.| + | Name | Type | Mandatory| Description | + | ------- | --------------- | ---- | ---------------------------------------------- | + | objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** @@ -2048,79 +2640,75 @@ Reads an **IRemoteObject** array from this **MessageParcel** object. class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); - this.attachLocalInterface(this, descriptor); - } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; + this.modifyLocalInterface(this, descriptor); } + asObject(): rpc.IRemoteObject { return this; } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; - let data = rpc.MessageParcel.create(); - let result = data.writeRemoteObjectArray(a); + let data = rpc.MessageSequence.create(); + data.writeRemoteObjectArray(a); let b = new Array(3); + try { + data.readRemoteObjectArray(b); + } catch(error) { + console.info("rpc read remote object array fail, errorCode " + error.code); + console.info("rpc read remote object array fail, errorMessage" + error.message); + } data.readRemoteObjectArray(b); ``` - -### readRemoteObjectArray8+ +### readRemoteObjectArray readRemoteObjectArray(): IRemoteObject[] -Reads the **IRemoteObject** array from this **MessageParcel** object. +Reads the **IRemoteObject** object array from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteObject[] | **IRemoteObject** object array obtained.| + | Type | Description | + | --------------- | --------------------------- | + | IRemoteObject[] | **IRemoteObject** object array read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); - this.attachLocalInterface(this, descriptor); - } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; + this.modifyLocalInterface(this, descriptor); } + asObject(): rpc.IRemoteObject { return this; } } let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; - let data = rpc.MessageParcel.create(); - let result = data.writeRemoteObjectArray(a); - console.log("RpcClient: readRemoteObjectArray is " + result); - let b = data.readRemoteObjectArray(); - console.log("RpcClient: readRemoteObjectArray is " + b); + let data = rpc.MessageSequence.create(); + data.writeRemoteObjectArray(a); + try { + let b = data.readRemoteObjectArray(); + console.log("RpcClient: readRemoteObjectArray is " + b); + } catch(error) { + console.info("rpc read remote object array fail, errorCode " + error.code); + console.info("rpc read remote object array fail, errorMessage" + error.message); + } ``` -### closeFileDescriptor8+ +### closeFileDescriptor9+ static closeFileDescriptor(fd: number): void @@ -2130,9 +2718,9 @@ Closes a file descriptor. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor to close.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | fd | number | Yes | File descriptor to close.| **Example** @@ -2140,11 +2728,15 @@ Closes a file descriptor. import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - rpc.MessageParcel.closeFileDescriptor(fd); + try { + rpc.MessageSequence.closeFileDescriptor(fd); + } catch(error) { + console.info("rpc close file descriptor fail, errorCode " + error.code); + console.info("rpc close file descriptor fail, errorMessage" + error.message); + } ``` - -### dupFileDescriptor8+ +### dupFileDescriptor static dupFileDescriptor(fd: number) :number @@ -2154,104 +2746,2589 @@ Duplicates a file descriptor. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor to duplicate.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | fd | number | Yes | File descriptor to duplicate.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------------------- | | number | New file descriptor.| +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900013 | call os dup function failed | + **Example** ``` import fileio from '@ohos.fileio'; let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let newFd = rpc.MessageParcel.dupFileDescriptor(fd); + try { + let newFd = rpc.MessageSequence.dupFileDescriptor(fd); + } catch(error) { + console.info("rpc dup file descriptor fail, errorCode " + error.code); + console.info("rpc dup file descriptor fail, errorMessage" + error.message); + } ``` - -### containFileDescriptors8+ +### containFileDescriptors containFileDescriptors(): boolean -Checks whether this **MessageParcel** object contains a file descriptor. +Checks whether this **MessageSequence** object contains file descriptors. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| + | Type | Description | + | ------- | -------------------------------------------------------------------- | + | boolean | Returns **true** if the **MessageSequence** object contains file descriptors; returns **false** otherwise.| **Example** + ``` import fileio from '@ohos.fileio'; - let parcel = new rpc.MessageParcel(); + let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; - let r1 = parcel.containFileDescriptors(); + let r1 = sequence.containFileDescriptors(); let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let writeResult = parcel.writeFileDescriptor(fd); - console.log("RpcTest: parcel writeFd result is : " + writeResult); - let containFD = parcel.containFileDescriptors(); - console.log("RpcTest: parcel after write fd containFd result is : " + containFD); + try { + sequence.writeFileDescriptor(fd); + } catch(error) { + console.info("rpc write file descriptor fail, errorCode " + error.code); + console.info("rpc write file descriptor fail, errorMessage" + error.message); + } + try { + let containFD = sequence.containFileDescriptors(); + console.log("RpcTest: sequence after write fd containFd result is : " + containFD); + } catch(error) { + console.info("rpc contain file descriptor fail, errorCode " + error.code); + console.info("rpc contain file descriptor fail, errorMessage" + error.message); + } ``` +### writeFileDescriptor -### writeFileDescriptor8+ - -writeFileDescriptor(fd: number): boolean +writeFileDescriptor(fd: number): void -Writes a file descriptor to this **MessageParcel** object. +Writes a file descriptor to this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | fd | number | Yes| File descriptor to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor to write.| -**Return value** +**Error codes** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------ | + | 1900009 | write data to message sequence failed | **Example** ``` import fileio from '@ohos.fileio'; - let parcel = new rpc.MessageParcel(); + let sequence = new rpc.MessageSequence(); let filePath = "path/to/file"; let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); - let writeResult = parcel.writeFileDescriptor(fd); - console.log("RpcTest: parcel writeFd result is : " + writeResult); + try { + sequence.writeFileDescriptor(fd); + } catch(error) { + console.info("rpc write file descriptor fail, errorCode " + error.code); + console.info("rpc write file descriptor fail, errorMessage" + error.message); + } ``` -### readFileDescriptor8+ +### readFileDescriptor readFileDescriptor(): number -Reads the file descriptor from this **MessageParcel** object. +Reads the file descriptor from this **MessageSequence** object. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------- | | number | File descriptor read.| -**Example** +**Error codes** - ``` +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let sequence = new rpc.MessageSequence(); + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + try { + sequence.writeFileDescriptor(fd); + } catch(error) { + console.info("rpc write file descriptor fail, errorCode " + error.code); + console.info("rpc write file descriptor fail, errorMessage" + error.message); + } + try { + let readFD = sequence.readFileDescriptor(); + } catch(error) { + console.info("rpc read file descriptor fail, errorCode " + error.code); + console.info("rpc read file descriptor fail, errorMessage" + error.message); + } + ``` + + +### writeAshmem + +writeAshmem(ashmem: Ashmem): void + +Writes an anonymous shared object to this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------- | + | ashmem | Ashmem | Yes | Anonymous shared object to write.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------- | + | 1900003 | write to ashmem failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let ashmem; + try { + ashmem = rpc.Ashmem.create("ashmem", 1024); + } catch(error) { + console.info("rpc create ashmem fail, errorCode " + error.code); + console.info("rpc creat ashmem fail, errorMessage" + error.message); + } + try { + sequence.writeAshmem(ashmem); + } catch(error) { + console.info("rpc write ashmem fail, errorCode " + error.code); + console.info("rpc write ashmem fail, errorMessage" + error.message); + } + ``` + + +### readAshmem + +readAshmem(): Ashmem + +Reads the anonymous shared object from this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------ | + | Ashmem | Anonymous share object read.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900004 | read from ashmem failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let ashmem; + try { + ashmem = rpc.Ashmem.create("ashmem", 1024); + } catch(error) { + console.info("rpc create ashmem fail, errorCode " + error.code); + console.info("rpc creat ashmem fail, errorMessage" + error.message); + } + try { + sequence.writeAshmem(ashmem); + } catch(error) { + console.info("rpc write ashmem fail, errorCode " + error.code); + console.info("rpc write ashmem fail, errorMessage" + error.message); + } + try { + let readAshmem = sequence.readAshmem(); + console.log("RpcTest: read ashmem to result is : " + readAshmem); + } catch(error) { + console.info("rpc read ashmem fail, errorCode " + error.code); + console.info("rpc read ashmem fail, errorMessage" + error.message); + } + ``` + + +### getRawDataCapacity + +getRawDataCapacity(): number + +Obtains the maximum amount of raw data that can be held by this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------------------------------------------------ | + | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageSequence** object.| + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let result = sequence.getRawDataCapacity(); + console.log("RpcTest: sequence get RawDataCapacity result is : " + result); + ``` + + +### writeRawData + +writeRawData(rawData: number[], size: number): void + +Writes raw data to this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | -------- | ---- | ---------------------------------- | + | rawData | number[] | Yes | Raw data to write. | + | size | number | Yes | Size of the raw data, in bytes.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900009 | write data to message sequence failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let arr = [1, 2, 3, 4, 5]; + try { + sequence.writeRawData(arr, arr.length); + } catch(error) { + console.info("rpc write rawdata fail, errorCode " + error.code); + console.info("rpc write rawdata fail, errorMessage" + error.message); + } + ``` + + +### readRawData + +readRawData(size: number): number[] + +Reads raw data from this **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | size | number | Yes | Size of the raw data to read.| + +**Return value** + + | Type | Description | + | -------- | ------------------------------ | + | number[] | Raw data read, in bytes.| + +**Error codes** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900010 | read data from message sequence failed | + +**Example** + + ``` + let sequence = new rpc.MessageSequence(); + let arr = [1, 2, 3, 4, 5]; + try { + sequence.writeRawData(arr, arr.length); + } catch(error) { + console.info("rpc write rawdata fail, errorCode " + error.code); + console.info("rpc write rawdata fail, errorMessage" + error.message); + } + try { + let result = sequence.readRawData(5); + console.log("RpcTest: sequence read raw data result is : " + result); + } catch(error) { + console.info("rpc read rawdata fail, errorCode " + error.code); + console.info("rpc read rawdata fail, errorMessage" + error.message); + } + ``` + +## MessageParcel(deprecated) + +>This class is no longer maintained since API version 9. You are advised to use [MessageSequence](#messagesequence9). + +Provides APIs for reading and writing data in specific format. During RPC, the sender can use the **write()** method provided by **MessageParcel** to write data in specific format to a **MessageParcel** object. The receiver can use the **read()** method provided by **MessageParcel** to read data in specific format from a **MessageParcel** object. The data formats include basic data types and arrays, IPC objects, interface tokens, and custom sequenceable objects. + +### create + +create(): MessageParcel + +Creates a **MessageParcel** object. This method is a static method. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------------- | ----------------------------- | + | MessageParcel | **MessageParcel** object created.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + console.log("RpcClient: data is " + data); + ``` + +### reclaim + +reclaim(): void + +Reclaims the **MessageParcel** object that is no longer used. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Example** + + ``` + let reply = rpc.MessageParcel.create(); + reply.reclaim(); + ``` + +### writeRemoteObject + +writeRemoteObject(object: [IRemoteObject](#iremoteobject)): boolean + +Serializes a remote object and writes it to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | --------------------------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | Remote object to serialize and write to the **MessageParcel** object.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + } + let data = rpc.MessageParcel.create(); + let testRemoteObject = new TestRemoteObject("testObject"); + data.writeRemoteObject(testRemoteObject); + ``` + +### readRemoteObject + +readRemoteObject(): IRemoteObject + +Reads the remote object from this **MessageParcel** object. You can use this method to deserialize the **MessageParcel** object to generate an **IRemoteObject**. The remote objects are read in the order in which they are written to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------------------------------- | ------------------ | + | [IRemoteObject](#iremoteobject) | Remote object obtained.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + } + let data = rpc.MessageParcel.create(); + let testRemoteObject = new TestRemoteObject("testObject"); + data.writeRemoteObject(testRemoteObject); + let proxy = data.readRemoteObject(); + ``` + +### writeInterfaceToken + +writeInterfaceToken(token: string): boolean + +Writes an interface token to this **MessageParcel** object. The remote object can use this interface token to verify the communication. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | token | string | Yes | Interface token to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeInterfaceToken("aaa"); + console.log("RpcServer: writeInterfaceToken is " + result); + ``` + + +### readInterfaceToken + +readInterfaceToken(): string + +Reads the interface token from this **MessageParcel** object. The interface token is read in the sequence in which it is written to the **MessageParcel** object. The local object can use it to verify the communication. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------------ | + | string | Interface token obtained.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteMessageRequest(code, data, reply, option) { + let interfaceToken = data.readInterfaceToken(); + console.log("RpcServer: interfaceToken is " + interfaceToken); + return true; + } + } + ``` + + +### getSize + +getSize(): number + +Obtains the data size of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------- | + | number | Size of the **MessageParcel** object obtained, in bytes.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let size = data.getSize(); + console.log("RpcClient: size is " + size); + ``` + + +### getCapacity + +getCapacity(): number + +Obtains the capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------- | + | number | **MessageParcel** capacity obtained, in bytes.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.getCapacity(); + console.log("RpcClient: capacity is " + result); + ``` + + +### setSize + +setSize(size: number): boolean + +Sets the size of data contained in this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------------- | + | size | number | Yes | Data size to set, in bytes.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let setSize = data.setSize(16); + console.log("RpcClient: setSize is " + setSize); + ``` + + +### setCapacity + +setCapacity(size: number): boolean + +Sets the storage capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------------------------- | + | size | number | Yes | Storage capacity to set, in bytes.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.setCapacity(100); + console.log("RpcClient: setCapacity is " + result); + ``` + + +### getWritableBytes + +getWritableBytes(): number + +Obtains the writable capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------------- | + | number | **MessageParcel** writable capacity obtained, in bytes.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteMessageRequest(code, data, reply, option) { + let getWritableBytes = data.getWritableBytes(); + console.log("RpcServer: getWritableBytes is " + getWritableBytes); + return true; + } + } + ``` + + +### getReadableBytes + +getReadableBytes(): number + +Obtains the readable capacity of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------------------- | + | number | **MessageParcel** object readable capacity, in bytes.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteRequest(code, data, reply, option) { + let result = data.getReadableBytes(); + console.log("RpcServer: getReadableBytes is " + result); + return true; + } + } + ``` + + +### getReadPosition + +getReadPosition(): number + +Obtains the read position of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------- | + | number | Current read position of the **MessageParcel** object.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let readPos = data.getReadPosition(); + console.log("RpcClient: readPos is " + readPos); + ``` + + +### getWritePosition + +getWritePosition(): number + +Obtains the write position of this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | --------------------------------------- | + | number | Current write position of the **MessageParcel** object.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + data.writeInt(10); + let bwPos = data.getWritePosition(); + console.log("RpcClient: bwPos is " + bwPos); + ``` + + +### rewindRead + +rewindRead(pos: number): boolean + +Moves the read pointer to the specified position. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | pos | number | Yes | Position from which data is to read.| + +**Return value** + + | Type | Description | + | ------- | ------------------------------------------------- | + | boolean | Returns **true** if the read position changes; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + data.writeInt(12); + data.writeString("parcel"); + let number = data.readInt(); + console.log("RpcClient: number is " + number); + data.rewindRead(0); + let number2 = data.readInt(); + console.log("RpcClient: rewindRead is " + number2); + ``` + + +### rewindWrite + +rewindWrite(pos: number): boolean + +Moves the write pointer to the specified position. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | pos | number | Yes | Position from which data is to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the write position changes; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + data.writeInt(4); + data.rewindWrite(0); + data.writeInt(5); + let number = data.readInt(); + console.log("RpcClient: rewindWrite is: " + number); + ``` + + +### writeByte + +writeByte(val: number): boolean + +Writes a Byte value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Byte value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeByte(2); + console.log("RpcClient: writeByte is: " + result); + ``` + + +### readByte + +readByte(): number + +Reads the Byte value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------ | + | number | Byte value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeByte(2); + console.log("RpcClient: writeByte is: " + result); + let ret = data.readByte(); + console.log("RpcClient: readByte is: " + ret); + ``` + + +### writeShort + +writeShort(val: number): boolean + +Writes a Short int value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------ | + | val | number | Yes | Short int value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShort(8); + console.log("RpcClient: writeShort is: " + result); + ``` + + +### readShort + +readShort(): number + +Reads the Short int value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | -------------- | + | number | Short int value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShort(8); + console.log("RpcClient: writeShort is: " + result); + let ret = data.readShort(); + console.log("RpcClient: readShort is: " + ret); + ``` + + +### writeInt + +writeInt(val: number): boolean + +Writes an Int value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Int value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeInt(10); + console.log("RpcClient: writeInt is " + result); + ``` + + +### readInt + +readInt(): number + +Reads the Int value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------ | + | number | Int value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeInt(10); + console.log("RpcClient: writeInt is " + result); + let ret = data.readInt(); + console.log("RpcClient: readInt is " + ret); + ``` + + +### writeLong + +writeLong(val: number): boolean + +Writes a Long int value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Long int value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLong(10000); + console.log("RpcClient: writeLong is " + result); + ``` + + +### readLong + +readLong(): number + +Reads the Long int value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | -------------- | + | number | Long int value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLong(10000); + console.log("RpcClient: writeLong is " + result); + let ret = data.readLong(); + console.log("RpcClient: readLong is " + ret); + ``` + + +### writeFloat + +writeFloat(val: number): boolean + +Writes a Float value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------- | + | val | number | Yes | Float value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloat(1.2); + console.log("RpcClient: writeFloat is " + result); + ``` + + +### readFloat + +readFloat(): number + +Reads the Float value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------ | + | number | Float value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloat(1.2); + console.log("RpcClient: writeFloat is " + result); + let ret = data.readFloat(); + console.log("RpcClient: readFloat is " + ret); + ``` + + +### writeDouble + +writeDouble(val: number): boolean + +Writes a Double value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------- | + | val | number | Yes | Double value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDouble(10.2); + console.log("RpcClient: writeDouble is " + result); + ``` + + +### readDouble + +readDouble(): number + +Reads the Double value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------ | + | number | Double value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDouble(10.2); + console.log("RpcClient: writeDouble is " + result); + let ret = data.readDouble(); + console.log("RpcClient: readDouble is " + ret); + ``` + +### writeBoolean + +writeBoolean(val: boolean): boolean + +Writes a Boolean value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------- | ---- | ---------------- | + | val | boolean | Yes | Boolean value to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBoolean(false); + console.log("RpcClient: writeBoolean is " + result); + ``` + + +### readBoolean + +readBoolean(): boolean + +Reads the Boolean value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------- | -------------------- | + | boolean | Boolean value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBoolean(false); + console.log("RpcClient: writeBoolean is " + result); + let ret = data.readBoolean(); + console.log("RpcClient: readBoolean is " + ret); + ``` + + +### writeChar + +writeChar(val: number): boolean + +Writes a Char value to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | val | number | Yes | Char value to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeChar(97); + console.log("RpcClient: writeChar is " + result); + ``` + + +### readChar + +readChar(): number + +Reads the Char value from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ---------------- | + | number | Char value read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeChar(97); + console.log("RpcClient: writeChar is " + result); + let ret = data.readChar(); + console.log("RpcClient: readChar is " + ret); + ``` + + +### writeString + +writeString(val: string): boolean + +Writes a string to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ----------------------------------------- | + | val | string | Yes | String to write. The length of the string must be less than 40960 bytes.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeString('abc'); + console.log("RpcClient: writeString is " + result); + ``` + + +### readString + +readString(): string + +Reads the string from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | -------------- | + | string | String read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeString('abc'); + console.log("RpcClient: writeString is " + result); + let ret = data.readString(); + console.log("RpcClient: readString is " + ret); + ``` + + +### writeSequenceable + +writeSequenceable(val: Sequenceable): boolean + +Writes a sequenceable object to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ----------------------------- | ---- | -------------------- | + | val | [Sequenceable](#sequenceable) | Yes | Sequenceable object to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceable(sequenceable); + console.log("RpcClient: writeSequenceable is " + result); + ``` + + +### readSequenceable + +readSequenceable(dataIn: Sequenceable): boolean + +Reads member variables from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ----------------------------- | ---- | --------------------------------------- | + | dataIn | [Sequenceable](#sequenceabledeprecated) | Yes | Object that reads member variables from the **MessageParcel** object.| + +**Return value** + + | Type | Description | + | ------- | ------------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceable(sequenceable); + console.log("RpcClient: writeSequenceable is " + result); + let ret = new MySequenceable(0, ""); + let result2 = data.readSequenceable(ret); + console.log("RpcClient: writeSequenceable is " + result2); + ``` + + +### writeByteArray + +writeByteArray(byteArray: number[]): boolean + +Writes a byte array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ------------------ | + | byteArray | number[] | Yes | Byte array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let ByteArrayVar = [1, 2, 3, 4, 5]; + let result = data.writeByteArray(ByteArrayVar); + console.log("RpcClient: writeByteArray is " + result); + ``` + + +### readByteArray + +readByteArray(dataIn: number[]): void + +Reads a byte array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Byte array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let ByteArrayVar = [1, 2, 3, 4, 5]; + let result = data.writeByteArray(ByteArrayVar); + console.log("RpcClient: writeByteArray is " + result); + let array = new Array(5); + data.readByteArray(array); + ``` + + +### readByteArray + +readByteArray(): number[] + +Reads the byte array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------- | + | number[] | Byte array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let ByteArrayVar = [1, 2, 3, 4, 5]; + let result = data.writeByteArray(ByteArrayVar); + console.log("RpcClient: writeByteArray is " + result); + let array = data.readByteArray(); + console.log("RpcClient: readByteArray is " + array); + ``` + + +### writeShortArray + +writeShortArray(shortArray: number[]): boolean + +Writes a short array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | -------- | ---- | -------------------- | + | shortArray | number[] | Yes | Short array to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShortArray([11, 12, 13]); + console.log("RpcClient: writeShortArray is " + result); + ``` + + +### readShortArray + +readShortArray(dataIn: number[]): void + +Reads a short array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Short array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShortArray([11, 12, 13]); + console.log("RpcClient: writeShortArray is " + result); + let array = new Array(3); + data.readShortArray(array); + ``` + + +### readShortArray + +readShortArray(): number[] + +Reads the short array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | number[] | Short array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeShortArray([11, 12, 13]); + console.log("RpcClient: writeShortArray is " + result); + let array = data.readShortArray(); + console.log("RpcClient: readShortArray is " + array); + ``` + + +### writeIntArray + +writeIntArray(intArray: number[]): boolean + +Writes an integer array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | -------- | ---- | ------------------ | + | intArray | number[] | Yes | Integer array to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeIntArray([100, 111, 112]); + console.log("RpcClient: writeIntArray is " + result); + ``` + + +### readIntArray + +readIntArray(dataIn: number[]): void + +Reads an integer array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------ | + | dataIn | number[] | Yes | Integer array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeIntArray([100, 111, 112]); + console.log("RpcClient: writeIntArray is " + result); + let array = new Array(3); + data.readIntArray(array); + ``` + + +### readIntArray + +readIntArray(): number[] + +Reads the integer array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------- | + | number[] | Integer array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeIntArray([100, 111, 112]); + console.log("RpcClient: writeIntArray is " + result); + let array = data.readIntArray(); + console.log("RpcClient: readIntArray is " + array); + ``` + + +### writeLongArray + +writeLongArray(longArray: number[]): boolean + +Writes a long array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | -------------------- | + | longArray | number[] | Yes | Long array to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLongArray([1111, 1112, 1113]); + console.log("RpcClient: writeLongArray is " + result); + ``` + + +### readLongArray + +readLongArray(dataIn: number[]): void + +Reads a long array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | number[] | Yes | Long array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLongArray([1111, 1112, 1113]); + console.log("RpcClient: writeLongArray is " + result); + let array = new Array(3); + data.readLongArray(array); + ``` + + +### readLongArray + +readLongArray(): number[] + +Reads the long array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | number[] | Long array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeLongArray([1111, 1112, 1113]); + console.log("RpcClient: writeLongArray is " + result); + let array = data.readLongArray(); + console.log("RpcClient: readLongArray is " + array); + ``` + + +### writeFloatArray + +writeFloatArray(floatArray: number[]): boolean + +Writes a FloatArray to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | ---------- | -------- | ---- | --- | + | floatArray | number[] | Yes | Floating-point array to write. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloatArray([1.2, 1.3, 1.4]); + console.log("RpcClient: writeFloatArray is " + result); + ``` + + +### readFloatArray + +readFloatArray(dataIn: number[]): void + +Reads a FloatArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type| Mandatory| Description| + | ------ | -------- | ---- | ------ | + | dataIn | number[] | Yes | Floating-point array to read. The system processes Float data as that of the Double type. Therefore, the total number of bytes occupied by a FloatArray must be calculated as the Double type.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloatArray([1.2, 1.3, 1.4]); + console.log("RpcClient: writeFloatArray is " + result); + let array = new Array(3); + data.readFloatArray(array); + ``` + + +### readFloatArray + +readFloatArray(): number[] + +Reads the FloatArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------- | + | number[] | FloatArray read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeFloatArray([1.2, 1.3, 1.4]); + console.log("RpcClient: writeFloatArray is " + result); + let array = data.readFloatArray(); + console.log("RpcClient: readFloatArray is " + array); + ``` + + +### writeDoubleArray + +writeDoubleArray(doubleArray: number[]): boolean + +Writes a DoubleArray to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ----------- | -------- | ---- | ------------------------ | + | doubleArray | number[] | Yes | DoubleArray to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDoubleArray([11.1, 12.2, 13.3]); + console.log("RpcClient: writeDoubleArray is " + result); + ``` + + +### readDoubleArray + +readDoubleArray(dataIn: number[]): void + +Reads a DoubleArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ------------------------ | + | dataIn | number[] | Yes | DoubleArray to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDoubleArray([11.1, 12.2, 13.3]); + console.log("RpcClient: writeDoubleArray is " + result); + let array = new Array(3); + data.readDoubleArray(array); + ``` + + +### readDoubleArray + +readDoubleArray(): number[] + +Reads the DoubleArray from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | -------------------- | + | number[] | DoubleArray read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeDoubleArray([11.1, 12.2, 13.3]); + console.log("RpcClient: writeDoubleArray is " + result); + let array = data.readDoubleArray(); + console.log("RpcClient: readDoubleArray is " + array); + ``` + + +### writeBooleanArray + +writeBooleanArray(booleanArray: boolean[]): boolean + +Writes a Boolean array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------------ | --------- | ---- | ------------------ | + | booleanArray | boolean[] | Yes | Boolean array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBooleanArray([false, true, false]); + console.log("RpcClient: writeBooleanArray is " + result); + ``` + + +### readBooleanArray + +readBooleanArray(dataIn: boolean[]): void + +Reads a Boolean array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | --------- | ---- | ------------------ | + | dataIn | boolean[] | Yes | Boolean array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBooleanArray([false, true, false]); + console.log("RpcClient: writeBooleanArray is " + result); + let array = new Array(3); + data.readBooleanArray(array); + ``` + + +### readBooleanArray + +readBooleanArray(): boolean[] + +Reads the Boolean array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | --------- | -------------- | + | boolean[] | Boolean array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeBooleanArray([false, true, false]); + console.log("RpcClient: writeBooleanArray is " + result); + let array = data.readBooleanArray(); + console.log("RpcClient: readBooleanArray is " + array); + ``` + + +### writeCharArray + +writeCharArray(charArray: number[]): boolean + +Writes a character array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | -------- | ---- | ---------------------- | + | charArray | number[] | Yes | Character array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeCharArray([97, 98, 88]); + console.log("RpcClient: writeCharArray is " + result); + ``` + + +### readCharArray + +readCharArray(dataIn: number[]): void + +Reads a character array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | ---------------------- | + | dataIn | number[] | Yes | Character array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeCharArray([97, 98, 99]); + console.log("RpcClient: writeCharArray is " + result); + let array = new Array(3); + data.readCharArray(array); + ``` + + +### readCharArray + +readCharArray(): number[] + +Reads the character array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ------------------ | + | number[] | Character array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeCharArray([97, 98, 99]); + console.log("RpcClient: writeCharArray is " + result); + let array = data.readCharArray(); + console.log("RpcClient: readCharArray is " + array); + ``` + + +### writeStringArray + +writeStringArray(stringArray: string[]): boolean + +Writes a string array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | -------- | ---- | ---------------- | + | stringArray | string[] | Yes | String array to write. The length of a single element in the array must be less than 40960 bytes.| + +**Return value** + + | Type | Description| + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeStringArray(["abc", "def"]); + console.log("RpcClient: writeStringArray is " + result); + ``` + + +### readStringArray + +readStringArray(dataIn: string[]): void + +Reads a string array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------- | + | dataIn | string[] | Yes | String array to read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeStringArray(["abc", "def"]); + console.log("RpcClient: writeStringArray is " + result); + let array = new Array(2); + data.readStringArray(array); + ``` + + +### readStringArray + +readStringArray(): string[] + +Reads the string array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | string[] | String array read.| + +**Example** + + ``` + let data = rpc.MessageParcel.create(); + let result = data.writeStringArray(["abc", "def"]); + console.log("RpcClient: writeStringArray is " + result); + let array = data.readStringArray(); + console.log("RpcClient: readStringArray is " + array); + ``` + + +### writeNoException8+ + +writeNoException(): void + +Writes information to this **MessageParcel** object indicating that no exception occurred. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + onRemoteRequest(code, data, reply, option) { + if (code === 1) { + console.log("RpcServer: onRemoteRequest called"); + reply.writeNoException(); + return true; + } else { + console.log("RpcServer: unknown code: " + code); + return false; + } + } + } + ``` + +### readException8+ + +readException(): void + +Reads the exception information from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageParcel.create(); + let reply = rpc.MessageParcel.create(); + data.writeInt(1); + data.writeString("hello"); + proxy.sendMessageRequest(1, data, reply, option) + .then(function(errCode) { + if (errCode === 0) { + console.log("sendMessageRequest got result"); + reply.readException(); + let msg = reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendMessageRequest failed, errCode: " + errCode); + } + }).catch(function(e) { + console.log("RPCTest: sendMessageRequest got exception: " + e.message); + }).finally (() => { + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); + data.reclaim(); + reply.reclaim(); + }); + ``` + +### writeSequenceableArray + +writeSequenceableArray(sequenceableArray: Sequenceable[]): boolean + +Writes a sequenceable array to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ----------------- | -------------- | ---- | -------------------------- | + | sequenceableArray | Sequenceable[] | Yes | Sequenceable array to write.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let sequenceable2 = new MySequenceable(2, "bbb"); + let sequenceable3 = new MySequenceable(3, "ccc"); + let a = [sequenceable, sequenceable2, sequenceable3]; + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceableArray(a); + console.log("RpcClient: writeSequenceableArray is " + result); + ``` + + +### readSequenceableArray8+ + +readSequenceableArray(sequenceableArray: Sequenceable[]): void + +Reads a sequenceable array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ----------------- | -------------- | ---- | -------------------------- | + | sequenceableArray | Sequenceable[] | Yes | Sequenceable array to read.| + +**Example** + + ``` + class MySequenceable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageParcel) { + messageParcel.writeInt(this.num); + messageParcel.writeString(this.str); + return true; + } + unmarshalling(messageParcel) { + this.num = messageParcel.readInt(); + this.str = messageParcel.readString(); + return true; + } + } + let sequenceable = new MySequenceable(1, "aaa"); + let sequenceable2 = new MySequenceable(2, "bbb"); + let sequenceable3 = new MySequenceable(3, "ccc"); + let a = [sequenceable, sequenceable2, sequenceable3]; + let data = rpc.MessageParcel.create(); + let result = data.writeSequenceableArray(a); + console.log("RpcClient: writeSequenceableArray is " + result); + let b = [new MySequenceable(0, ""), new MySequenceable(0, ""), new MySequenceable(0, "")]; + data.readSequenceableArray(b); + ``` + + +### writeRemoteObjectArray8+ + +writeRemoteObjectArray(objectArray: IRemoteObject[]): boolean + +Writes an array of **IRemoteObject** objects to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description| + | ----------- | --------------- | ---- | ----- | + | objectArray | IRemoteObject[] | Yes | Array of **IRemoteObject** objects to write.| + +**Return value** + + | Type | Description | + | ------- | -------------------------------------------------------------------------------------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** if the operation fails or if the **IRemoteObject** array is null.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + this.attachLocalInterface(this, descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } + } + let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; + let data = rpc.MessageParcel.create(); + let result = data.writeRemoteObjectArray(a); + console.log("RpcClient: writeRemoteObjectArray is " + result); + ``` + + +### readRemoteObjectArray8+ + +readRemoteObjectArray(objects: IRemoteObject[]): void + +Reads an **IRemoteObject** array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description| + | ------- | --------------- | ---- | --------- | + | objects | IRemoteObject[] | Yes | **IRemoteObject** array to read.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + this.attachLocalInterface(this, descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } + } + let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; + let data = rpc.MessageParcel.create(); + let result = data.writeRemoteObjectArray(a); + let b = new Array(3); + data.readRemoteObjectArray(b); + ``` + + +### readRemoteObjectArray8+ + +readRemoteObjectArray(): IRemoteObject[] + +Reads the **IRemoteObject** array from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type| Description| + | --------------- | -------- | + | IRemoteObject[] | **IRemoteObject** object array obtained.| + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + this.attachLocalInterface(this, descriptor); + } + addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { + return true; + } + isObjectDead(): boolean { + return false; + } + asObject(): rpc.IRemoteObject { + return this; + } + } + let a = [new TestRemoteObject("testObject1"), new TestRemoteObject("testObject2"), new TestRemoteObject("testObject3")]; + let data = rpc.MessageParcel.create(); + let result = data.writeRemoteObjectArray(a); + console.log("RpcClient: readRemoteObjectArray is " + result); + let b = data.readRemoteObjectArray(); + console.log("RpcClient: readRemoteObjectArray is " + b); + ``` + + +### closeFileDescriptor8+ + +static closeFileDescriptor(fd: number): void + +Closes a file descriptor. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | fd | number | Yes | File descriptor to close.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + rpc.MessageParcel.closeFileDescriptor(fd); + ``` + + +### dupFileDescriptor8+ + +static dupFileDescriptor(fd: number) :number + +Duplicates a file descriptor. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | fd | number | Yes | File descriptor to duplicate.| + +**Return value** + + | Type | Description | + | ------ | -------------------- | + | number | New file descriptor.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let newFd = rpc.MessageParcel.dupFileDescriptor(fd); + ``` + + +### containFileDescriptors8+ + +containFileDescriptors(): boolean + +Checks whether this **MessageParcel** object contains a file descriptor. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------- | ------------------------------------------------------------------ | + | boolean | Returns **true** if the **MessageParcel** object contains a file descriptor; returns **false** otherwise.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let parcel = new rpc.MessageParcel(); + let filePath = "path/to/file"; + let r1 = parcel.containFileDescriptors(); + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let writeResult = parcel.writeFileDescriptor(fd); + console.log("RpcTest: parcel writeFd result is : " + writeResult); + let containFD = parcel.containFileDescriptors(); + console.log("RpcTest: parcel after write fd containFd result is : " + containFD); + ``` + + +### writeFileDescriptor8+ + +writeFileDescriptor(fd: number): boolean + +Writes a file descriptor to this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------ | + | fd | number | Yes | File descriptor to write.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + import fileio from '@ohos.fileio'; + let parcel = new rpc.MessageParcel(); + let filePath = "path/to/file"; + let fd = fileio.openSync(filePath, 0o2| 0o100, 0o666); + let writeResult = parcel.writeFileDescriptor(fd); + console.log("RpcTest: parcel writeFd result is : " + writeResult); + ``` + + +### readFileDescriptor8+ + +readFileDescriptor(): number + +Reads the file descriptor from this **MessageParcel** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ---------------- | + | number | File descriptor read.| + +**Example** + + ``` import fileio from '@ohos.fileio'; let parcel = new rpc.MessageParcel(); let filePath = "path/to/file"; @@ -2272,14 +5349,14 @@ Writes an anonymous shared object to this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ashmem | Ashmem | Yes| Anonymous shared object to write.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ----------------------------------- | + | ashmem | Ashmem | Yes | Anonymous shared object to write.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | -------------------------------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2302,8 +5379,8 @@ Reads the anonymous shared object from this **MessageParcel** object. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------ | | Ashmem | Anonymous share object obtained.| **Example** @@ -2328,8 +5405,8 @@ Obtains the maximum amount of raw data that can be held by this **MessageParcel* **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------------------------------------------- | | number | 128 MB, which is the maximum amount of raw data that can be held by this **MessageParcel** object.| **Example** @@ -2351,15 +5428,15 @@ Writes raw data to this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | rawData | number[] | Yes| Raw data to write.| - | size | number | Yes| Size of the raw data, in bytes.| + | Name | Type | Mandatory| Description | + | ------- | -------- | ---- | ---------------------------------- | + | rawData | number[] | Yes | Raw data to write. | + | size | number | Yes | Size of the raw data, in bytes.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2382,14 +5459,14 @@ Reads raw data from this **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | size | number | Yes| Size of the raw data to read.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | size | number | Yes | Size of the raw data to read.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ------------------------------ | | number[] | Raw data obtained, in bytes.| **Example** @@ -2403,10 +5480,118 @@ Reads raw data from this **MessageParcel** object. console.log("RpcTest: parcel read raw data result is : " + result); ``` -## Sequenceable -Writes objects of classes to a **MessageParcel** and reads them from the **MessageParcel** during IPC. +## Parcelable9+ + +Writes an object to a **MessageSequence** and reads it from the **MessageSequence** during IPC. + +### marshalling + +marshalling(dataOut: MessageSequence): boolean + +Marshals this **Parcelable** object into a **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | --------------- | ---- | ------------------------------------------- | + | dataOut | MessageSequence | Yes | **MessageSequence** object to which the **Parcelable** object is to be marshaled.| + +**Return value** + + | Type | Description | + | ------- | ----------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MyParcelable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + let parcelable = new MyParcelable(1, "aaa"); + let data = rpc.MessageSequence.create(); + let result = data.writeParcelable(parcelable); + console.log("RpcClient: writeParcelable is " + result); + let ret = new MyParcelable(0, ""); + let result2 = data.readParcelable(ret); + console.log("RpcClient: readParcelable is " + result2); + ``` + + +### unmarshalling + +unmarshalling(dataIn: MessageSequence): boolean + +Unmarshals this **Parcelable** object from a **MessageSequence** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | --------------- | ---- | ----------------------------------------------- | + | dataIn | MessageSequence | Yes | **MessageSequence** object from which the **Parcelable** object is to be unmarshaled.| + +**Return value** + + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + +**Example** + + ``` + class MyParcelable { + num: number; + str: string; + constructor(num, str) { + this.num = num; + this.str = str; + } + marshalling(messageSequence) { + messageSequence.writeInt(this.num); + messageSequence.writeString(this.str); + return true; + } + unmarshalling(messageSequence) { + this.num = messageSequence.readInt(); + this.str = messageSequence.readString(); + return true; + } + } + let parcelable = new MyParcelable(1, "aaa"); + let data = rpc.MessageSequence.create(); + let result = data.writeParcelable(parcelable); + console.log("RpcClient: writeParcelable is " + result); + let ret = new MyParcelable(0, ""); + let result2 = data.readParcelable(ret); + console.log("RpcClient: readParcelable is " + result2); + ``` + +## Sequenceable(deprecated) + +>This class is no longer maintained since API version 9. You are advised to use the [Parcelable](#parcelable9). + +Writes objects of classes to a **MessageParcel** and reads them from the **MessageParcel** during IPC. ### marshalling @@ -2418,14 +5603,14 @@ Marshals the sequenceable object into a **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataOut | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object to which the sequenceable object is to be marshaled.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | ----------------------------------------- | + | dataOut | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object to which the sequenceable object is to be marshaled.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2461,7 +5646,7 @@ Marshals the sequenceable object into a **MessageParcel** object. ### unmarshalling -unmarshalling(dataIn: MessageParcel) : boolean +unmarshalling(dataIn: MessageParcel): boolean Unmarshals this sequenceable object from a **MessageParcel** object. @@ -2469,14 +5654,14 @@ Unmarshals this sequenceable object from a **MessageParcel** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | dataIn | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object in which the sequenceable object is to be unmarshaled.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | --------------------------------------------- | + | dataIn | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object in which the sequenceable object is to be unmarshaled.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -2514,7 +5699,6 @@ Unmarshals this sequenceable object from a **MessageParcel** object. Provides the holder of a remote proxy object. - ### asObject asObject(): IRemoteObject @@ -2525,9 +5709,9 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl **Return value** - | Type| Description| - | -------- | -------- | - | [IRemoteObject](#iremoteobject) | Returns the [RemoteObject](#ashmem8) if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| + | Type | Description| + | ---- | ----- | + | [IRemoteObject](#iremoteobject) | Returns the **RemoteObject** if it is the caller; returns the [IRemoteObject](#iremoteobject), the holder of this **RemoteProxy** object, if the caller is a [RemoteProxy](#remoteproxy) object.| **Example** @@ -2553,12 +5737,10 @@ Obtains a proxy or remote object. This API must be implemented by its derived cl } ``` - ## DeathRecipient Subscribes to death notifications of a remote object. When the remote object is dead, the local end will receive a notification and **[onRemoteDied](#onremotedied)** will be called. A remote object is dead when the process holding the object is terminated or the device of the remote object is shut down or restarted. If the local and remote objects belong to different devices, the remote object is dead when the device holding the remote object is detached from the network. - ### onRemoteDied onRemoteDied(): void @@ -2577,27 +5759,61 @@ Called to perform subsequent operations when a death notification of the remote } ``` - -## SendRequestResult8+ +## RequestResult9+ Defines the response to the request. **System capability**: SystemCapability.Communication.IPC.Core - | Parameter| Value| Description| -| -------- | -------- | -------- | -| errCode | number | Error Code| -| code | number | Message code.| -| data | MessageParcel | **MessageParcel** object sent to the remote process.| -| reply | MessageParcel | **MessageParcel** object returned by the remote process.| + | Name | Type | Readable| Writable| Description | + | ------- | --------------- | ---- | ---- |-------------------------------------- | + | errCode | number | Yes | No | Error Code | + | code | number | Yes | No | Message code. | + | data | MessageSequence | Yes | No | **MessageSequence** object sent to the remote process.| + | reply | MessageSequence | Yes | No | **MessageSequence** object returned by the remote process. | + +## SendRequestResult8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [RequestResult](#requestresult9). + +Defines the response to the request. + +**System capability**: SystemCapability.Communication.IPC.Core + | Name | Type | Readable| Writable| Description | + | ------- | ------------- | ---- | ---- | ----------------------------------- | + | errCode | number | Yes | No | Error Code | + | code | number | Yes | No | Message code. | + | data | MessageParcel | Yes | No | **MessageParcel** object sent to the remote process.| + | reply | MessageParcel | Yes | No | **MessageParcel** object returned by the remote process. | ## IRemoteObject Provides methods to query of obtain interface descriptors, add or delete death notifications, dump object status to specific files, and send messages. +### getLocalInterface9+ + +getLocalInterface(descriptor: string): IRemoteBroker + +Obtains the interface. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | -------------------- | + | descriptor | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | --------------------------------------------- | + | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| -### queryLocalInterface +### queryLocalInterface(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). queryLocalInterface(descriptor: string): IRemoteBroker @@ -2607,23 +5823,22 @@ Obtains the interface. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | descriptor | string | Yes| Interface descriptor.| + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | -------------------- | + | descriptor | string | Yes | Interface descriptor.| **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteBroker | **IRemoteBroker** object bound to the specified interface descriptor.| + | Type | Description | + | ------------- | --------------------------------------------- | + | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| ### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2631,26 +5846,25 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type| Mandatory| Description | + | ------- | ------------------------------- | ---- | ---- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ### sendRequest8+(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2658,106 +5872,206 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + +**Return value** + + | Type | Description | + | -------------------------------- | --------------------------------------------- | + | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + +**Return value** + + | Type | Description | + | ---------------------------- | ----------------------------------------- | + | Promise<RequestResult> | Promise used to return the **requestResult** object.| + + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | + + +### sendRequest8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). + +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void + +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | + + +### registerDeathRecipient9+ + +registerDeathRecipient(recipient: DeathRecipient, flags: number): void + +Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | flags | number | Yes | Flag of the death notification.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | -**Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| +### addDeathrecipient(deprecated) -### sendRequestAsync9+ +>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). -sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +addDeathRecipient(recipient: DeathRecipient, flags: number): boolean -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information. +Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | flags | number | Yes | Flag of the death notification.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| -### sendRequest8+ -sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void +### unregisterDeathRecipient9+ -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +unregisterDeathRecipient(recipient: DeathRecipient, flags: number): void + +Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| - | callback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | flags | number | Yes | Flag of the death notification.| +**Error Code** -### addDeathrecipient +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). -addDeathRecipient(recipient: DeathRecipient, flags: number): boolean + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | -Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. + +### removeDeathRecipient(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). + +removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean + +Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| - | flags | number | Yes| Flag of the death notification.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | flags | number | Yes | Flag of the death notification.| **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| -### removeDeathRecipient +### getDescriptor9+ -removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean +getDescriptor(): string -Removes the callback used to receive death notifications of the remote object. +Obtains the interface descriptor of this object. The interface descriptor is a string. **System capability**: SystemCapability.Communication.IPC.Core -**Parameters** +**Return value** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| - | flags | number | Yes| Flag of the death notification.| + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| -**Return value** +**Error Code** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | -### getInterfaceDescriptor +### getInterfaceDescriptor(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). getInterfaceDescriptor(): string @@ -2767,8 +6081,8 @@ Obtains the interface descriptor of this object. The interface descriptor is a s **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------- | | string | Interface descriptor obtained.| @@ -2782,34 +6096,31 @@ Checks whether this object is dead. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ------------------------------------------- | | boolean | Returns **true** if the object is dead; returns **false** otherwise.| ## RemoteProxy -Provides methods to implement **IRemoteObject**. +Provides APIs to implement **IRemoteObject**. **System capability**: SystemCapability.Communication.IPC.Core -| Parameter | Value | Description | +| Name | Value | Description | | --------------------- | ----------------------- | --------------------------------- | | PING_TRANSACTION | 1599098439 (0x5f504e47) | Internal instruction code used to test whether the IPC service is normal.| -| DUMP_TRANSACTION | 1598311760 (0x5f444d50) | Internal instruction code used to obtain the internal status of the binder.| -| INTERFACE_TRANSACTION | 1598968902 (0x5f4e5446) | Internal instruction code used to obtain the remote interface descriptor. | +| DUMP_TRANSACTION | 1598311760 (0x5f444d50) | Internal instruction code used to obtain the internal status of the binder. | +| INTERFACE_TRANSACTION | 1598968902 (0x5f4e5446) | Internal instruction code used to obtain the remote interface token. | | MIN_TRANSACTION_ID | 1 (0x00000001) | Minimum valid instruction code. | | MAX_TRANSACTION_ID | 16777215 (0x00FFFFFF) | Maximum valid instruction code. | - - ### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9-1). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2817,20 +6128,19 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ``` @@ -2871,12 +6181,82 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch reply.reclaim(); ``` + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + +**Return value** + + | Type | Description | + | ---------------------------- | ----------------------------------------- | + | Promise<RequestResult> | Promise used to return the **requestResult** object.| + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); + data.writeInt(1); + data.writeString("hello"); + proxy.sendMessageRequest(1, data, reply, option) + .then(function(result) { + if (result.errCode === 0) { + console.log("sendMessageRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendMessageRequest failed, errCode: " + result.errCode); + } + }).catch(function(e) { + console.log("RPCTest: sendMessageRequest got exception: " + e.message); + }).finally (() => { + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); + data.reclaim(); + reply.reclaim(); + }); + ``` + + ### sendRequest8+(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9-1). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -2884,17 +6264,17 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------------------------------- | --------------------------------------------- | | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| **Example** @@ -2943,28 +6323,219 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch }); ``` -### sendRequestAsync9+ +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked at certain time after the response to **sendMessageRequest** is returned, and the reply contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | + + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + function sendRequestCallback(result) { + if (result.errCode === 0) { + console.log("sendRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + result.data.reclaim(); + result.reply.reclaim(); + } + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); + data.writeInt(1); + data.writeString("hello"); + try { + proxy.sendRequest(1, data, reply, option, sendRequestCallback); + } catch(error) { + console.info("rpc send sequence request fail, errorCode " + error.code); + console.info("rpc send sequence request fail, errorMessage " + error.message); + } + ``` + + +### sendRequest8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). + +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void + +Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | callback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + function sendRequestCallback(result) { + if (result.errCode === 0) { + console.log("sendRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + result.data.reclaim(); + result.reply.reclaim(); + } + FA.connectAbility(want, connect); + let option = new rpc.MessageOption(); + let data = rpc.MessageParcel.create(); + let reply = rpc.MessageParcel.create(); + data.writeInt(1); + data.writeString("hello"); + proxy.sendRequest(1, data, reply, option, sendRequestCallback); + ``` + + +### getLocalInterface9+ + +getLocalInterface(interface: string): IRemoteBroker + +Obtains the **LocalInterface** object of an interface token. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | ---------------------- | + | interface | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | ------------------------------------------ | + | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900006 | only remote object permitted | + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function (elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName":"com.ohos.server", + "abilityName":"com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + try { + let broker = proxy.getLocalInterface("testObject"); + console.log("RpcClient: getLocalInterface is " + broker); + } catch(error) { + console.info("rpc get local interface fail, errorCode " + error.code); + console.info("rpc get local interface fail, errorMessage " + error.message); + } + ``` + + +### queryLocalInterface(deprecated) -sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). + +queryLocalInterface(interface: string): IRemoteBroker -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information. +Obtains the **LocalInterface** object of an interface token. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | ---------------------- | + | interface | string | Yes | Interface descriptor.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + | Type | Description | + | ------------- | ------------------------------------------ | + | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| **Example** @@ -2976,7 +6547,7 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, - onDisconnect: function(elementName) { + onDisconnect: function (elementName) { console.log("RpcClient: onDisconnect"); }, onFailed: function() { @@ -2984,51 +6555,37 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch } }; let want = { - "bundleName": "com.ohos.server", - "abilityName": "com.ohos.server.MainAbility", + "bundleName":"com.ohos.server", + "abilityName":"com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); - let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); - data.writeInt(1); - data.writeString("hello"); - proxy.sendRequestAsync(1, data, reply, option) - .then(function(result) { - if (result.errCode === 0) { - console.log("sendRequestAsync got result"); - result.reply.readException(); - let msg = result.reply.readString(); - console.log("RPCTest: reply msg: " + msg); - } else { - console.log("RPCTest: sendRequestAsync failed, errCode: " + result.errCode); - } - }).catch(function(e) { - console.log("RPCTest: sendRequestAsync got exception: " + e.message); - }).finally (() => { - console.log("RPCTest: sendRequestAsync ends, reclaim parcel"); - data.reclaim(); - reply.reclaim(); - }); + let broker = proxy.queryLocalInterface("testObject"); + console.log("RpcClient: queryLocalInterface is " + broker); ``` -### sendRequest8+ -sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void +### registerDeathRecipient9+ -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to sendRequest is returned, and the reply message contains the returned information. +registerDeathRecipient(recipient: DeathRecipient, flags: number): void + +Adds a callback for receiving death notifications of the remote object. This method is called if the remote object process matching the **RemoteProxy** object is killed. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| - | callback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add.| + | flags | number | Yes | Flag of the death notification.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | **Example** @@ -3051,48 +6608,44 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch "bundleName": "com.ohos.server", "abilityName": "com.ohos.server.MainAbility", }; - function sendRequestCallback(result) { - if (result.errCode === 0) { - console.log("sendRequest got result"); - result.reply.readException(); - let msg = result.reply.readString(); - console.log("RPCTest: reply msg: " + msg); - } else { - console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + FA.connectAbility(want, connect); + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); } - console.log("RPCTest: sendRequest ends, reclaim parcel"); - result.data.reclaim(); - result.reply.reclaim(); } - FA.connectAbility(want, connect); - let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); - data.writeInt(1); - data.writeString("hello"); - proxy.sendRequest(1, data, reply, option, sendRequestCallback); + let deathRecipient = new MyDeathRecipient(); + try { + proxy.registerDeathRecippient(deathRecipient, 0); + } catch(error) { + console.info("proxy register deathRecipient fail, errorCode " + error.code); + console.info("proxy register deathRecipient fail, errorMessage " + error.message); + } ``` -### queryLocalInterface +### addDeathRecippient(deprecated) -queryLocalInterface(interface: string): IRemoteBroker +>This API is no longer maintained since API version 9. You are advised to use [registerDeathRecipient](#registerdeathrecipient9). + +addDeathRecipient(recipient: DeathRecipient, flags: number): boolean -Obtains the **LocalInterface** object of an interface descriptor. +Adds a callback for receiving the death notifications of the remote object, including the death notifications of the remote proxy. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | interface | string | Yes| Interface descriptor.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | --------------------------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to add. | + | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteBroker | Returns **Null** by default, which indicates a proxy interface.| + | Type | Description | + | ------- | --------------------------------------------- | + | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| **Example** @@ -3104,7 +6657,7 @@ Obtains the **LocalInterface** object of an interface descriptor. console.log("RpcClient: js onConnect called."); proxy = remoteProxy; }, - onDisconnect: function (elementName) { + onDisconnect: function(elementName) { console.log("RpcClient: onDisconnect"); }, onFailed: function() { @@ -3112,35 +6665,41 @@ Obtains the **LocalInterface** object of an interface descriptor. } }; let want = { - "bundleName":"com.ohos.server", - "abilityName":"com.ohos.server.MainAbility", + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", }; FA.connectAbility(want, connect); - let broker = proxy.queryLocalInterface("testObject"); - console.log("RpcClient: queryLocalInterface is " + broker); + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + let deathRecipient = new MyDeathRecipient(); + proxy.addDeathRecippient(deathRecipient, 0); ``` +### unregisterDeathRecipient9+ -### addDeathRecippient +unregisterDeathRecipient(recipient: DeathRecipient, flags: number): boolean -addDeathRecipient(recipient : DeathRecipient, flags : number): boolean - -Adds a callback for receiving the death notifications of the remote object, including the death notifications of the remote proxy. +Removes the callback used to receive death notifications of the remote object. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to add.| - | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | -------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove.| + | flags | number | Yes | Flag of the death notification.| -**Return value** +**Error Code** - | Type| Description| - | -------- | -------- | - | boolean | Returns **true** if the callback is added successfully; returns **false** otherwise.| +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | **Example** @@ -3170,13 +6729,21 @@ Adds a callback for receiving the death notifications of the remote object, incl } } let deathRecipient = new MyDeathRecipient(); - proxy.addDeathRecippient(deathRecipient, 0); + try { + proxy.registerDeathRecippient(deathRecipient, 0); + proxy.unregisterDeathRecippient(deathRecipient, 0); + } catch(error) { + console.info("proxy register deathRecipient fail, errorCode " + error.code); + console.info("proxy register deathRecipient fail, errorMessage " + error.message); + } ``` -### removeDeathRecipient +### removeDeathRecipient(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [unregisterDeathRecipient](#unregisterdeathrecipient9). -removeDeathRecipient(recipient : DeathRecipient, flags : number): boolean +removeDeathRecipient(recipient: DeathRecipient, flags: number): boolean Removes the callback used to receive death notifications of the remote object. @@ -3184,15 +6751,15 @@ Removes the callback used to receive death notifications of the remote object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | recipient | [DeathRecipient](#deathrecipient) | Yes| Callback to remove.| - | flags | number | Yes| Flag of the death notification. This parameter is reserved. It is set to **0**.| + | Name | Type | Mandatory| Description | + | --------- | --------------------------------- | ---- | --------------------------------- | + | recipient | [DeathRecipient](#deathrecipient) | Yes | Callback to remove. | + | flags | number | Yes | Flag of the death notification. This parameter is reserved. It is set to **0**.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the callback is removed successfully; returns **false** otherwise.| **Example** @@ -3228,7 +6795,64 @@ Removes the callback used to receive death notifications of the remote object. ``` -### getInterfaceDescriptor +### getDescriptor9+ + +getDescriptor(): string + +Obtains the interface descriptor of this object. The interface descriptor is a string. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900008 | proxy or remote object is invalid | + | 1900007 | communication failed | + +**Example** + + ``` + import FA from "@ohos.ability.featureAbility"; + let proxy; + let connect = { + onConnect: function(elementName, remoteProxy) { + console.log("RpcClient: js onConnect called."); + proxy = remoteProxy; + }, + onDisconnect: function(elementName) { + console.log("RpcClient: onDisconnect"); + }, + onFailed: function() { + console.log("RpcClient: onFailed"); + } + }; + let want = { + "bundleName": "com.ohos.server", + "abilityName": "com.ohos.server.MainAbility", + }; + FA.connectAbility(want, connect); + try { + let descriptor = proxy.getDescriptor(); + console.log("RpcClient: descriptor is " + descriptor); + } catch(error) { + console.info("rpc get interface descriptor fail, errorCode " + error.code); + console.info("rpc get interface descriptor fail, errorMessage " + error.message); + } + ``` + + +### getInterfaceDescriptor(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). getInterfaceDescriptor(): string @@ -3238,8 +6862,8 @@ Obtains the interface descriptor of this proxy object. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------ | | string | Interface descriptor obtained.| **Example** @@ -3279,8 +6903,8 @@ Checks whether the **RemoteObject** is dead. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------------------- | | boolean | Returns **true** if the **RemoteObject** is dead; returns **false** otherwise.| **Example** @@ -3312,21 +6936,36 @@ Checks whether the **RemoteObject** is dead. ## MessageOption -Provides common message options (flag and wait time). The flag is used to construct the specified **MessageOption** object. +Provides common message options (flag and wait time). Use the specified flag to construct the **MessageOption** object. + +**System capability**: SystemCapability.Communication.IPC.Core + + | Name | Value | Description | + | ------------- | ---- | ----------------------------------------------------------- | + | TF_SYNC | 0 | Synchronous call. | + | TF_ASYNC | 1 | Asynchronous call. | + | TF_ACCEPT_FDS | 0x10 | Indication to **sendMessageRequest9+** for returning the file descriptor.| + | TF_WAIT_TIME | 8 | Default waiting time, in seconds. | + + +### constructor9+ + +constructor(async?: boolean); + +A constructor used to create a **MessageOption** object. **System capability**: SystemCapability.Communication.IPC.Core - | Parameter| Value| Description| -| -------- | -------- | -------- | -| TF_SYNC | 0 | Synchronous call.| -| TF_ASYNC | 1 | Asynchronous call.| -| TF_ACCEPT_FDS | 0x10 | Indication to [sendRequestAsync](#sendrequestasync9) for returning the file descriptor.| -| TF_WAIT_TIME | 8 | Time to wait, in seconds.| +**Parameters** + + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | -------------------------------------- | + | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| ### constructor -constructor(syncFlags?: number, waitTime = TF_WAIT_TIME) +constructor(syncFlags?: number, waitTime?: number) A constructor used to create a **MessageOption** object. @@ -3334,10 +6973,34 @@ A constructor used to create a **MessageOption** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | syncFlags | number | No| Call flag, which can be synchronous or asynchronous. The default value is **synchronous**.| - | waitTime | number | No| Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| + | Name | Type | Mandatory| Description | + | --------- | ------ | ---- | --------------------------------------------- | + | syncFlags | number | No | Call flag, which can be synchronous or asynchronous. The default value is **synchronous**. | + | waitTime | number | No | Maximum wait time for an RPC call. The default value is **TF_WAIT_TIME**.| + + +### isAsync9+ + +isAsync(): boolean; + +Checks whether **SendMessageRequest** is called synchronously or asynchronously. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------- | ------------------------------------ | + | boolean | Call mode obtained.| + + +### setAsync9+ + +setAsync(async: boolean): void; + +Sets whether **SendMessageRequest** is called synchronously or asynchronously. + +**System capability**: SystemCapability.Communication.IPC.Core ### getFlags @@ -3350,8 +7013,8 @@ Obtains the call flag, which can be synchronous or asynchronous. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------------------------ | | number | Call mode obtained.| @@ -3365,9 +7028,9 @@ Sets the call flag, which can be synchronous or asynchronous. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | flags | number | Yes| Call flag to set.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ------------------------ | + | flags | number | Yes | Call flag to set.| ### getWaitTime @@ -3380,8 +7043,8 @@ Obtains the maximum wait time for this RPC call. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------- | | number | Maximum wait time obtained.| @@ -3395,16 +7058,15 @@ Sets the maximum wait time for this RPC call. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | waitTime | number | Yes| Maximum wait time to set.| + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | --------------------- | + | waitTime | number | Yes | Maximum wait time to set.| ## IPCSkeleton Obtains IPC context information, including the UID and PID, local and remote device IDs, and whether the method is invoked on the same device. - ### getContextObject static getContextObject(): IRemoteObject @@ -3415,8 +7077,8 @@ Obtains the system capability manager. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------------------------------- | -------------------- | | [IRemoteObject](#iremoteobject) | System capability manager obtained.| **Example** @@ -3437,20 +7099,20 @@ Obtains the PID of the caller. This method is invoked by the **RemoteObject** ob **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------- | | number | PID of the caller.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerPid = rpc.IPCSkeleton.getCallingPid(); console.log("RpcServer: getCallingPid result: " + callerPid); return true; } - } + } ``` @@ -3464,15 +7126,15 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------- | | number | UID of the caller.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerUid = rpc.IPCSkeleton.getCallingUid(); console.log("RpcServer: getCallingUid result: " + callerUid); return true; @@ -3480,6 +7142,7 @@ Obtains the UID of the caller. This method is invoked by the **RemoteObject** ob } ``` + ### getCallingTokenId8+ static getCallingTokenId(): number; @@ -3488,17 +7151,18 @@ Obtains the caller's token ID, which is used to verify the caller identity. **System capability**: SystemCapability.Communication.IPC.Core -* Return value - - | Type | Description | - | ------ | --------------------- | - | number | Token ID of the caller obtained.| -* Example +**Return value** + + | Type | Description | + | ------ | --------------------- | + | number | Token ID of the caller obtained.| + +**Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerTokenId = rpc.IPCSkeleton.getCallingTokenId(); console.log("RpcServer: getCallingTokenId result: " + callerTokenId); return true; @@ -3517,15 +7181,15 @@ Obtains the ID of the device hosting the caller's process. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------------- | | string | Device ID obtained.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callerDeviceID = rpc.IPCSkeleton.getCallingDeviceID(); console.log("RpcServer: callerDeviceID is: " + callerDeviceID); return true; @@ -3544,15 +7208,15 @@ Obtains the local device ID. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ------------------ | | string | Local device ID obtained.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let localDeviceID = rpc.IPCSkeleton.getLocalDeviceID(); console.log("RpcServer: localDeviceID is: " + localDeviceID); return true; @@ -3571,15 +7235,15 @@ Checks whether the remote process is a process of the local device. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------------------- | | boolean | Returns **true** if the local and remote processes are on the same device; returns **false** otherwise.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let isLocalCalling = rpc.IPCSkeleton.isLocalCalling(); console.log("RpcServer: isLocalCalling is: " + isLocalCalling); return true; @@ -3588,9 +7252,9 @@ Checks whether the remote process is a process of the local device. ``` -### flushCommands +### flushCmdBuffer9+ -static flushCommands(object : IRemoteObject): number +static flushCmdBuffer(object: IRemoteObject): void Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. @@ -3598,15 +7262,49 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | object | [IRemoteObject](#iremoteobject) | Yes| **RemoteProxy** specified. | + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | + + +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + let remoteObject = new TestRemoteObject("aaa"); + try { + rpc.IPCSkeleton.flushCmdBuffer(remoteObject); + } catch(error) { + console.info("proxy set calling identity fail, errorCode " + error.code); + console.info("proxy set calling identity fail, errorMessage " + error.message); + } + ``` + + +### flushCommands(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [flushCmdBuffer](#flushcmdbuffer9). + +static flushCommands(object: IRemoteObject): number +Flushes all suspended commands from the specified **RemoteProxy** to the corresponding **RemoteObject**. It is recommended that this method be called before any time-sensitive operation is performed. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ------------------- | + | object | [IRemoteObject](#iremoteobject) | Yes | **RemoteProxy** specified. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | --------------------------------------------------------------------------------- | | number | Returns **0** if the operation is successful; returns an error code if the input object is null or a **RemoteObject**, or if the operation fails.| **Example** @@ -3636,37 +7334,70 @@ Flushes all suspended commands from the specified **RemoteProxy** to the corresp console.log("RpcServer: flushCommands result: " + ret); ``` - ### resetCallingIdentity -static resetCallingIdentity(): string +static resetCallingIdentity(): string + +Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ------------------------------------ | + | string | String containing the UID and PID of the remote user.| + +**Example** + + ``` + class Stub extends rpc.RemoteObject { + onRemoteMessageRequest(code, data, reply, option) { + let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); + console.log("RpcServer: callingIdentity is: " + callingIdentity); + return true; + } + } + ``` + + +### restoreCallingIdentity9+ + +static restoreCallingIdentity(identity: string): void Changes the UID and PID of the remote user to the UID and PID of the local user. This method is used in scenarios such as identity authentication. **System capability**: SystemCapability.Communication.IPC.Core -**Return value** +**Parameters** - | Type| Description| - | -------- | -------- | - | string | String containing the UID and PID of the remote user.| + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------------ | + | identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { - let callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); - console.log("RpcServer: callingIdentity is: " + callingIdentity); + onRemoteMessageRequest(code, data, reply, option) { + let callingIdentity = null; + try { + callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); + console.log("RpcServer: callingIdentity is: " + callingIdentity); + } finally { + rpc.IPCSkeleton.restoreCallingIdentity("callingIdentity "); + } return true; } } ``` -### setCallingIdentity +### setCallingIdentity(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [restoreCallingIdentity](#restorecallingidentity9). -static setCallingIdentity(identity : string): boolean +static setCallingIdentity(identity: string): boolean Restores the UID and PID of the remote user. It is usually called when the UID and PID of the remote user are required. The UID and PID of the remote user are returned by **resetCallingIdentity**. @@ -3674,21 +7405,21 @@ Restores the UID and PID of the remote user. It is usually called when the UID a **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | identity | string | Yes| String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| + | Name | Type | Mandatory| Description | + | -------- | ------ | ---- | ------------------------------------------------------------------ | + | identity | string | Yes | String containing the remote user UID and PID, which are returned by **resetCallingIdentity**.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** ``` class Stub extends rpc.RemoteObject { - onRemoteRequest(code, data, reply, option) { + onRemoteMessageRequest(code, data, reply, option) { let callingIdentity = null; try { callingIdentity = rpc.IPCSkeleton.resetCallingIdentity(); @@ -3707,7 +7438,6 @@ Restores the UID and PID of the remote user. It is usually called when the UID a Provides methods to implement **RemoteObject**. The service provider must inherit from this class. - ### constructor constructor(descriptor: string) @@ -3718,17 +7448,16 @@ A constructor used to create a **RemoteObject** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | descriptor | string | Yes| Interface descriptor.| + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | ------------ | + | descriptor | string | Yes | Interface descriptor.| ### sendRequest(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): boolean +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 8. You are advised to use [sendRequestAsync9+](#sendrequestasync9-2). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -3736,20 +7465,19 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | --------------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ``` @@ -3794,10 +7522,9 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ### sendRequest8+(deprecated) -sendRequest(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [sendRequestAsync9+](#sendrequestasync9-2). +sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): Promise<SendRequestResult> Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequest** is returned, and the reply message contains the returned information. @@ -3805,20 +7532,19 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------------------------------- | --------------------------------------------- | | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| - **Example** ``` @@ -3866,77 +7592,115 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch }); ``` -### sendRequestAsync9+ +### sendMessageRequest9+ -sendRequestAsync(code : number, data : MessageParcel, reply : MessageParcel, options : MessageOption): Promise<SendRequestResult> +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): Promise<RequestResult> -Sends a **MessageParcel** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendRequestAsync** is returned, and the reply message contains the returned information. +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a promise will be fulfilled immediately and the reply message does not contain any content. If **options** is the synchronous mode, a promise will be fulfilled when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| + | Name | Type | Mandatory| Description | + | ------- | ------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | - | Promise<SendRequestResult> | Promise used to return the **sendRequestResult** object.| + | Type | Description | + | ---------------------------- | --------------------------------------------- | + | Promise<RequestResult> | Promise used to return the **sendRequestResult** object.| **Example** ``` - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } } let testRemoteObject = new TestRemoteObject("testObject"); let option = new rpc.MessageOption(); - let data = rpc.MessageParcel.create(); - let reply = rpc.MessageParcel.create(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); data.writeInt(1); data.writeString("hello"); - testRemoteObject.sendRequestAsync(1, data, reply, option) + testRemoteObject.sendMessageRequest(1, data, reply, option) .then(function(result) { if (result.errCode === 0) { - console.log("sendRequestAsync got result"); + console.log("sendMessageRequest got result"); result.reply.readException(); let msg = result.reply.readString(); console.log("RPCTest: reply msg: " + msg); } else { - console.log("RPCTest: sendRequestAsync failed, errCode: " + result.errCode); + console.log("RPCTest: sendMessageRequest failed, errCode: " + result.errCode); } }).catch(function(e) { - console.log("RPCTest: sendRequestAsync got exception: " + e.message); + console.log("RPCTest: sendMessageRequest got exception: " + e.message); }).finally (() => { - console.log("RPCTest: sendRequestAsync ends, reclaim parcel"); + console.log("RPCTest: sendMessageRequest ends, reclaim parcel"); data.reclaim(); reply.reclaim(); }); ``` -### sendRequest8+ + +### sendMessageRequest9+ + +sendMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption, callback: AsyncCallback<RequestResult>): void + +Sends a **MessageSequence** message to the remote process in synchronous or asynchronous mode. If **options** is the asynchronous mode, a callback will be invoked immediately and the reply message does not contain any content. If **options** is the synchronous mode, a callback will be invoked when the response to **sendMessageRequest** is returned, and the reply message contains the returned information. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------------- | ---------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object holding the data to send. | + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | AsyncCallback | AsyncCallback<RequestResult> | Yes | Callback for receiving the sending result. | + +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + function sendRequestCallback(result) { + if (result.errCode === 0) { + console.log("sendRequest got result"); + result.reply.readException(); + let msg = result.reply.readString(); + console.log("RPCTest: reply msg: " + msg); + } else { + console.log("RPCTest: sendRequest failed, errCode: " + result.errCode); + } + console.log("RPCTest: sendRequest ends, reclaim parcel"); + result.data.reclaim(); + result.reply.reclaim(); + } + let testRemoteObject = new TestRemoteObject("testObject"); + let option = new rpc.MessageOption(); + let data = rpc.MessageSequence.create(); + let reply = rpc.MessageSequence.create(); + data.writeInt(1); + data.writeString("hello"); + testRemoteObject.sendMessageRequest(1, data, reply, option, sendRequestCallback); + ``` + + +### sendRequest8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [sendMessageRequest](#sendmessagerequest9). sendRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption, callback: AsyncCallback<SendRequestResult>): void @@ -3946,14 +7710,13 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object holding the data to send.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that receives the response.| - | options | [MessageOption](#messageoption) | Yes| Request sending mode, which can be synchronous (default) or asynchronous.| - | AsyncCallback | AsyncCallback<SendRequestResult> | Yes| Callback for receiving the sending result.| - + | Name | Type | Mandatory| Description | + | ------------- | -------------------------------------- | ---- | -------------------------------------------------------------------------------------- | + | code | number | Yes | Message code called by the request, which is determined by the client and server. If the method is generated by an IDL tool, the message code is automatically generated by the IDL tool.| + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object holding the data to send. | + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that receives the response. | + | options | [MessageOption](#messageoption) | Yes | Request sending mode, which can be synchronous (default) or asynchronous. | + | AsyncCallback | AsyncCallback<SendRequestResult> | Yes | Callback for receiving the sending result. | **Example** @@ -4002,32 +7765,29 @@ Sends a **MessageParcel** message to the remote process in synchronous or asynch ### onRemoteRequest8+(deprecated) +>This API is no longer maintained since API version 9. You are advised to use [onRemoteMessageRequest](#onremotemessagerequest9). -onRemoteRequest(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean - -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [onRemoteRequestEx9+](#onremoterequestex9). +onRemoteRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean -Provides a response to **sendRequestAsync()**. The server processes the request and returns a response in this function. +Provides a response to **sendMessageRequest()**. The server processes the request and returns a response in this API. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Service request code sent by the remote end.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that holds the parameters called by the client.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object carrying the result.| - | option | [MessageOption](#messageoption) | Yes| Whether the operation is synchronous or asynchronous.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | --------------------------------------- | + | code | number | Yes | Service request code sent by the remote end. | + | data | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object that holds the parameters called by the client.| + | reply | [MessageParcel](#messageparceldeprecated) | Yes | **MessageParcel** object carrying the result. | + | option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| - **Example** ```ets @@ -4049,7 +7809,6 @@ Provides a response to **sendRequestAsync()**. The server processes the request isObjectDead(): boolean { return false; } - onRemoteRequest(code, data, reply, option) { if (code === 1) { console.log("RpcServer: onRemoteRequest called"); @@ -4061,59 +7820,47 @@ Provides a response to **sendRequestAsync()**. The server processes the request } } ``` -### onRemoteRequestEx9+ -onRemoteRequestEx(code : number, data : MessageParcel, reply: MessageParcel, options : MessageOption): boolean | Promise +### onRemoteMessageRequest9+ + +onRemoteMessageRequest(code: number, data: MessageSequence, reply: MessageSequence, options: MessageOption): boolean | Promise\ > **NOTE**
->- You are advised to overload **onRemoteRequestEx** preferentially, which implements synchronous and asynchronous message processing. ->- If both **onRemoteRequest** and **onRemoteRequestEx** are overloaded, only **onRemoteRequestEx** takes effect. +> +>* You are advised to overload **onRemoteMessageRequest** preferentially, which implements synchronous and asynchronous message processing. +>* If both onRemoteRequest() and onRemoteMessageRequest() are overloaded, only the onRemoteMessageRequest() takes effect. -Provides a response to **sendRequestAsync()**. The server processes the request synchronously or asynchronously and returns the result in this API. +Provides a response to **sendMessageRequest()**. The server processes the request synchronously or asynchronously and returns the result in this API. **System capability**: SystemCapability.Communication.IPC.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | code | number | Yes| Service request code sent by the remote end.| - | data | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object that holds the parameters called by the client.| - | reply | [MessageParcel](#messageparcel) | Yes| **MessageParcel** object carrying the result.| - | option | [MessageOption](#messageoption) | Yes| Whether the operation is synchronous or asynchronous.| + | Name| Type | Mandatory| Description | + | ------ | ------------------------------- | ---- | ----------------------------------------- | + | code | number | Yes | Service request code sent by the remote end. | + | data | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object that holds the parameters called by the client.| + | reply | [MessageSequence](#messagesequence9) | Yes | **MessageSequence** object to which the result is written. | + | option | [MessageOption](#messageoption) | Yes | Whether the operation is synchronous or asynchronous. | **Return value** - | Type| Description| - | -------- | -------- | - | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteRequestEx**. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| - | Promise | Returns a promise object if the request is processed asynchronously in **onRemoteRequestEx**.| - + | Type | Description | + | ----------------- | ---------------------------------------------------------------------------------------------- | + | boolean | Returns a Boolean value if the request is processed synchronously in **onRemoteMessageRequest**. If the operation is successful, **true** is returned. Otherwise, **false** is returned.| + | Promise\ | Returns a promise object if the request is processed asynchronously in **onRemoteMessageRequest**. | -**Example**: Overload **onRemoteRequestEx** to process a request synchronously. +**Example**: Overload **onRemoteMessageRequest** to process requests synchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } - onRemoteRequestEx(code, data, reply, option) { + + onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteMessageRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); @@ -4122,30 +7869,18 @@ Provides a response to **sendRequestAsync()**. The server processes the request } } ``` - **Example**: Overload **onRemoteRequestEx** to process a request asynchronously. + + **Example**: Overload **onRemoteMessageRequest** to process requests asynchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } - async onRemoteRequestEx(code, data, reply, option) { + + async onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; @@ -4157,94 +7892,72 @@ Provides a response to **sendRequestAsync()**. The server processes the request } } ``` -**Example**: Overload **onRemoteRequestEx** and **onRemoteRequest** to process requests synchronously. + +**Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests synchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } + onRemoteRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteMessageRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); return false; } } - // Only onRemoteRequestEx is executed when onRemoteRequestEx and onRemoteRequest are called. - onRemoteRequestEx(code, data, reply, option) { + // Only onRemoteMessageRequest is executed. + onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; } - + return true; } } ``` - **Example**: Overload **onRemoteRequestEx** and **onRemoteRequest** to process requests asynchronously. + + **Example**: Overload **onRemoteMessageRequest** and **onRemoteRequest** to process requests asynchronously. ```ets - class MyDeathRecipient { - onRemoteDied() { - console.log("server died"); - } - } class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - isObjectDead(): boolean { - return false; - } + onRemoteRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: sync onRemoteRequestEx is called"); + console.log("RpcServer: sync onRemoteRequest is called"); return true; } else { console.log("RpcServer: unknown code: " + code); return false; } } - // Only onRemoteRequestEx is executed when onRemoteRequestEx and onRemoteRequest are called. - async onRemoteRequestEx(code, data, reply, option) { + // Only onRemoteMessageRequest is executed. + async onRemoteMessageRequest(code, data, reply, option) { if (code === 1) { - console.log("RpcServer: async onRemoteRequestEx is called"); + console.log("RpcServer: async onRemoteMessageRequest is called"); } else { console.log("RpcServer: unknown code: " + code); return false; } - await new Promise((resolve) => { + await new Promise((resolve) => { setTimeout(resolve, 100); }) return true; } } ``` + + ### getCallingUid getCallingUid(): number @@ -4254,11 +7967,118 @@ Obtains the UID of the remote process. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ----------------------- | | number | UID of the remote process obtained.| +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + let testRemoteObject = new TestRemoteObject("testObject"); + console.log("RpcServer: getCallingUid: " + testRemoteObject.getCallingUid()); + ``` + +### getCallingPid + +getCallingPid(): number + +Obtains the PID of the remote process. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Return value** + + | Type | Description | + | ------ | ----------------------- | + | number | PID of the remote process obtained.| + +**Example** + + ``` + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + } + let testRemoteObject = new TestRemoteObject("testObject"); + console.log("RpcServer: getCallingPid: " + testRemoteObject.getCallingPid()); + ``` + +### getLocalInterface9+ + +getLocalInterface(descriptor: string): IRemoteBroker + +Obtains the interface. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | -------------------- | + | descriptor | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | --------------------------------------------- | + | IRemoteBroker | **IRemoteBroker** object bound to the specified interface token.| + + +**Example** + + ``` + class MyDeathRecipient { + onRemoteDied() { + console.log("server died"); + } + } + class TestRemoteObject extends rpc.RemoteObject { + constructor(descriptor) { + super(descriptor); + } + registerDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); + isObjectDead(): boolean { + return false; + } + } + let testRemoteObject = new TestRemoteObject("testObject"); + try { + let broker = testRemoteObject.getLocalInterface("testObject"); + } catch(error) { + console.info(rpc get local interface fail, errorCode " + error.code); + console.info(rpc get local interface fail, errorMessage " + error.message); + } + ``` + + +### queryLocalInterface(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [getLocalInterface](#getlocalinterface9). + +queryLocalInterface(descriptor: string): IRemoteBroker + +Checks whether the remote object corresponding to the specified interface token exists. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ---------- | ------ | ---- | ---------------------- | + | descriptor | string | Yes | Interface descriptor.| + +**Return value** + + | Type | Description | + | ------------- | ------------------------------------------------------------------ | + | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| **Example** @@ -4283,24 +8103,31 @@ Obtains the UID of the remote process. } } let testRemoteObject = new TestRemoteObject("testObject"); - console.log("RpcServer: getCallingUid: " + testRemoteObject.getCallingUid()); + let broker = testRemoteObject.queryLocalInterface("testObject"); ``` -### getCallingPid +### getDescriptor9+ -getCallingPid(): number +getDescriptor(): string -Obtains the PID of the remote process. +Obtains the interface descriptor of this object. The interface descriptor is a string. **System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | number | PID of the remote process obtained.| + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| + +**Error Code** +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900008 | proxy or remote object is invalid | **Example** @@ -4314,41 +8141,38 @@ Obtains the PID of the remote process. constructor(descriptor) { super(descriptor); } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } + addDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); isObjectDead(): boolean { return false; } } let testRemoteObject = new TestRemoteObject("testObject"); - console.log("RpcServer: getCallingPid: " + testRemoteObject.getCallingPid()); + try { + let descriptor = testRemoteObject.getDescriptor(); + } catch(error) { + console.info(rpc get local interface fail, errorCode " + error.code); + console.info(rpc get local interface fail, errorMessage " + error.message); + } + console.log("RpcServer: descriptor is: " + descriptor); ``` -### queryLocalInterface - -queryLocalInterface(descriptor: string): IRemoteBroker +### getInterfaceDescriptor(deprecated) -Checks whether the remote object corresponding to the specified interface descriptor exists. +>This API is no longer maintained since API version 9. You are advised to use [getDescriptor](#getdescriptor9). -**System capability**: SystemCapability.Communication.IPC.Core +getInterfaceDescriptor(): string -**Parameters** +Obtains the interface descriptor. - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | descriptor | string | Yes| Interface descriptor.| +**System capability**: SystemCapability.Communication.IPC.Core **Return value** - | Type| Description| - | -------- | -------- | - | IRemoteBroker | Returns the remote object if a match is found; returns **Null** otherwise.| - + | Type | Description | + | ------ | ---------------- | + | string | Interface descriptor obtained.| **Example** @@ -4373,23 +8197,25 @@ Checks whether the remote object corresponding to the specified interface descri } } let testRemoteObject = new TestRemoteObject("testObject"); - let broker = testRemoteObject.queryLocalInterface("testObject"); + let descriptor = testRemoteObject.getInterfaceDescriptor(); + console.log("RpcServer: descriptor is: " + descriptor); ``` -### getInterfaceDescriptor +### modifyLocalInterface9+ -getInterfaceDescriptor(): string +modifyLocalInterface(localInterface: IRemoteBroker, descriptor: string): void -Obtains the interface descriptor. +Binds an interface descriptor to an **IRemoteBroker** object. **System capability**: SystemCapability.Communication.IPC.Core -**Return value** +**Parameters** - | Type| Description| - | -------- | -------- | - | string | Interface descriptor obtained.| + | Name | Type | Mandatory| Description | + | -------------- | ------------- | ---- | ------------------------------------- | + | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | + | descriptor | string | Yes | Interface descriptor.| **Example** @@ -4403,24 +8229,28 @@ Obtains the interface descriptor. class TestRemoteObject extends rpc.RemoteObject { constructor(descriptor) { super(descriptor); + try { + this.modifyLocalInterface(this, descriptor); + } catch(error) { + console.info(rpc attach local interface fail, errorCode " + error.code); + console.info(rpc attach local interface fail, errorMessage " + error.message); + } } - addDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } - removeDeathRecipient(recipient: MyDeathRecipient, flags: number): boolean { - return true; - } + registerDeathRecipient(recipient: MyDeathRecipient, flags: number); + unregisterDeathRecipient(recipient: MyDeathRecipient, flags: number); isObjectDead(): boolean { return false; } + asObject(): rpc.IRemoteObject { + return this; + } } let testRemoteObject = new TestRemoteObject("testObject"); - let descriptor = testRemoteObject.getInterfaceDescriptor(); - console.log("RpcServer: descriptor is: " + descriptor); ``` +### attachLocalInterface(deprecated) -### attachLocalInterface +>This API is no longer maintained since API version 9. You are advised to use [modifyLocalInterface](#modifylocalinterface9). attachLocalInterface(localInterface: IRemoteBroker, descriptor: string): void @@ -4430,11 +8260,10 @@ Binds an interface descriptor to an **IRemoteBroker** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | localInterface | IRemoteBroker | Yes| **IRemoteBroker** object.| - | descriptor | string | Yes| Interface descriptor.| - + | Name | Type | Mandatory| Description | + | -------------- | ------------- | ---- | ------------------------------------- | + | localInterface | IRemoteBroker | Yes | **IRemoteBroker** object. | + | descriptor | string | Yes | Interface descriptor.| **Example** @@ -4474,17 +8303,17 @@ The table below describes the protection types of the mapped memory. **System capability**: SystemCapability.Communication.IPC.Core - | Name| Value| Description| -| -------- | -------- | -------- | -| PROT_EXEC | 4 | The mapped memory is executable.| -| PROT_NONE | 0 | The mapped memory is inaccessible.| -| PROT_READ | 1 | The mapped memory is readable.| -| PROT_WRITE | 2 | The mapped memory is writeable.| + | Name | Value | Description | + | ---------- | --- | ------------------ | + | PROT_EXEC | 4 | The mapped memory is executable. | + | PROT_NONE | 0 | The mapped memory is inaccessible.| + | PROT_READ | 1 | The mapped memory is readable. | + | PROT_WRITE | 2 | The mapped memory is writeable. | -### createAshmem8+ +### create9+ -static createAshmem(name: string, size: number): Ashmem +static create(name: string, size: number): Ashmem Creates an **Ashmem** object with the specified name and size. @@ -4492,18 +8321,56 @@ Creates an **Ashmem** object with the specified name and size. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | name | string | Yes| Name of the **Ashmem** object to create.| - | size | number | Yes| Size (in bytes) of the **Ashmem** object to create.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------------- | + | name | string | Yes | Name of the **Ashmem** object to create. | + | size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------------------------------- | | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| +**Example** + + ``` + let ashmem; + try { + ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + } catch(error) { + console.info("Rpc creat ashmem fail, errorCode " + error.code); + console.info("Rpc creat ashmem fail, errorMessage " + error.message); + } + let size = ashmem.getAshmemSize(); + console.log("RpcTest: get ashemm by create : " + ashmem + " size is : " + size); + ``` + + +### createAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [create](#create9). + +static createAshmem(name: string, size: number): Ashmem + +Creates an **Ashmem** object with the specified name and size. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | ---------------------------- | + | name | string | Yes | Name of the **Ashmem** object to create. | + | size | number | Yes | Size (in bytes) of the **Ashmem** object to create.| + +**Return value** + + | Type | Description | + | ------ | ---------------------------------------------- | + | Ashmem | Returns the **Ashmem** object if it is created successfully; returns null otherwise.| + **Example** ``` @@ -4513,9 +8380,9 @@ Creates an **Ashmem** object with the specified name and size. ``` -### createAshmemFromExisting8+ +### create9+ -static createAshmemFromExisting(ashmem: Ashmem): Ashmem +static create(ashmem: Ashmem): Ashmem Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. @@ -4523,17 +8390,55 @@ Creates an **Ashmem** object by copying the file descriptor (FD) of an existing **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | ashmem | Ashmem | Yes| Existing **Ashmem** object.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | ashmem | Ashmem | Yes | Existing **Ashmem** object.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | ---------------------- | | Ashmem | **Ashmem** object created.| +**Example** + + ``` + let ashmem2; + try { + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + let ashmem2 = rpc.Ashmem.create(ashmem); + } catch(error) { + console.info("Rpc creat ashmem from existing fail, errorCode " + error.code); + console.info("Rpc creat ashmem from existing fail, errorMessage " + error.message); + } + let size = ashmem2.getAshmemSize(); + console.log("RpcTest: get ashemm by create : " + ashmem2 + " size is : " + size); + ``` + + +### createAshmemFromExisting8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [create](#create9). + +static createAshmemFromExisting(ashmem: Ashmem): Ashmem + +Creates an **Ashmem** object by copying the file descriptor (FD) of an existing Ashmem object. The two **Ashmem** objects point to the same shared memory region. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------- | + | ashmem | Ashmem | Yes | Existing **Ashmem** object.| + +**Return value** + + | Type | Description | + | ------ | ---------------------- | + | Ashmem | **Ashmem** object created.| + **Example** ``` @@ -4555,7 +8460,7 @@ Closes this **Ashmem** object. **Example** ``` - let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.closeAshmem(); ``` @@ -4571,7 +8476,7 @@ Deletes the mappings for the specified address range of this **Ashmem** object. **Example** ``` - let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); ashmem.unmapAshmem(); ``` @@ -4586,8 +8491,8 @@ Obtains the memory size of this **Ashmem** object. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------ | -------------------------- | | number | **Ashmem** size obtained.| **Example** @@ -4599,7 +8504,44 @@ Obtains the memory size of this **Ashmem** object. ``` -### mapAshmem8+ +### mapTypedAshmem9+ + +mapTypedAshmem(mapType: number): void + +Creates the shared file mapping on the virtual address space of this process. The size of the mapping region is specified by this **Ashmem** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------------------------ | + | mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | ------ | + | 1900001 | call mmap function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.mapTypedAshmem(ashmem.PROT_READ | ashmem.PROT_WRITE); + } catch(error) { + console.info("Rpc map ashmem fail, errorCode " + error.code); + console.info("Rpc map ashmem fail, errorMessage " + error.message); + } + ``` + + +### mapAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [mapTypedAshmem](#maptypedashmem9). mapAshmem(mapType: number): boolean @@ -4609,14 +8551,14 @@ Creates the shared file mapping on the virtual address space of this process. Th **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | mapType | number | Yes| Protection level of the memory region to which the shared file is mapped.| + | Name | Type | Mandatory| Description | + | ------- | ------ | ---- | ------------------------------ | + | mapType | number | Yes | Protection level of the memory region to which the shared file is mapped.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4628,7 +8570,38 @@ Creates the shared file mapping on the virtual address space of this process. Th ``` -### mapReadAndWriteAshmem8+ +### mapReadWriteAshmem9+ + +mapReadWriteAshmem(): void + +Maps the shared file to the readable and writable virtual address space of the process. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900001 | call mmap function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.mapReadWriteAshmem(); + } catch(error) { + console.info("Rpc map read and write ashmem fail, errorCode " + error.code); + console.info("Rpc map read and write ashmem fail, errorMessage " + error.message); + } + ``` + + +### mapReadAndWriteAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [mapReadWriteAshmem](#mapreadwriteashmem9). mapReadAndWriteAshmem(): boolean @@ -4638,8 +8611,8 @@ Maps the shared file to the readable and writable virtual address space of the p **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4651,7 +8624,38 @@ Maps the shared file to the readable and writable virtual address space of the p ``` -### mapReadOnlyAshmem8+ +### mapReadonlyAshmem9+ + +mapReadonlyAshmem(): void + +Maps the shared file to the read-only virtual address space of the process. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900001 | call mmap function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.mapReadonlyAshmem(); + } catch(error) { + console.info("Rpc map read and write ashmem fail, errorCode " + error.code); + console.info("Rpc map read and write ashmem fail, errorMessage " + error.message); + } + ``` + + +### mapReadOnlyAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [mapReadonlyAshmem](#mapreadonlyashmem9). mapReadOnlyAshmem(): boolean @@ -4661,8 +8665,8 @@ Maps the shared file to the read-only virtual address space of the process. **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4674,7 +8678,44 @@ Maps the shared file to the read-only virtual address space of the process. ``` -### setProtection8+ +### setProtectionType9+ + +setProtectionType(protectionType: number): void + +Sets the protection level of the memory region to which the shared file is mapped. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ------------------ | + | protectionType | number | Yes | Protection type to set.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | -------- | ------- | + | 1900002 | call os ioctl function failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + try { + ashmem.setProtection(ashmem.PROT_READ); + } catch(error) { + console.info("Rpc set protection type fail, errorCode " + error.code); + console.info("Rpc set protection type fail, errorMessage " + error.message); + } + ``` + + +### setProtection8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [setProtectionType](#setprotectiontype9). setProtection(protectionType: number): boolean @@ -4684,14 +8725,14 @@ Sets the protection level of the memory region to which the shared file is mappe **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | protectionType | number | Yes| Protection type to set.| + | Name | Type | Mandatory| Description | + | -------------- | ------ | ---- | ------------------ | + | protectionType | number | Yes | Protection type to set.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -4703,7 +8744,48 @@ Sets the protection level of the memory region to which the shared file is mappe ``` -### writeToAshmem8+ +### writeAshmem9+ + +writeAshmem(buf: number[], size: number, offset: number): void + +Writes data to the shared file associated with this **Ashmem** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------------------------------------- | + | buf | number[] | Yes | Data to write. | + | size | number | Yes | Size of the data to write. | + | offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| + +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID| Error Message| + | ------- | -------- | + | 1900003 | write to ashmem failed | + +**Example** + + ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + ashmem.mapReadWriteAshmem(); + var ByteArrayVar = [1, 2, 3, 4, 5]; + try { + ashmem.writeAshmem(ByteArrayVar, 5, 0); + } catch(error) { + console.info("Rpc write to ashmem fail, errorCode " + error.code); + console.info("Rpc write to ashmem fail, errorMessage " + error.message); + } + ``` + + +### writeToAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [writeAshmem](#writeashmem9). writeToAshmem(buf: number[], size: number, offset: number): boolean @@ -4713,16 +8795,16 @@ Writes data to the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | buf | number[] | Yes| Data to write.| - | size | number | Yes| Size of the data to write.| - | offset | number | Yes| Start position of the data to write in the memory region associated with this **Ashmem** object.| + | Name| Type | Mandatory| Description | + | ------ | -------- | ---- | -------------------------------------------------- | + | buf | number[] | Yes | Data to write. | + | size | number | Yes | Size of the data to write. | + | offset | number | Yes | Start position of the data to write in the memory region associated with this **Ashmem** object.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | ------- | ----------------------------------------------------------------------------------------- | | boolean | Returns **true** is the data is written successfully; returns **false** otherwise.| **Example** @@ -4737,9 +8819,9 @@ Writes data to the shared file associated with this **Ashmem** object. ``` -### readFromAshmem8+ +### readAshmem9+ -readFromAshmem(size: number, offset: number): number[] +readAshmem(size: number, offset: number): number[] Reads data from the shared file associated with this **Ashmem** object. @@ -4747,21 +8829,68 @@ Reads data from the shared file associated with this **Ashmem** object. **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | size | number | Yes| Size of the data to read.| - | offset | number | Yes| Start position of the data to read in the memory region associated with this **Ashmem** object.| + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------------------------------------- | + | size | number | Yes | Size of the data to read. | + | offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| **Return value** - | Type| Description| - | -------- | -------- | + | Type | Description | + | -------- | ---------------- | | number[] | Data read.| +**Error Code** + +For details about the error codes, see [RPC Error Codes](../errorcodes/errorcode-rpc.md). + + | ID | Error Message| + | -------- | -------- | + | 1900004 | read from ashmem failed | **Example** ``` + let ashmem = rpc.Ashmem.create("ashmem", 1024*1024); + ashmem.mapReadWriteAshmem(); + var ByteArrayVar = [1, 2, 3, 4, 5]; + ashmem.writeAshmem(ByteArrayVar, 5, 0); + try { + let readResult = ashmem.readAshmem(5, 0); + console.log("RpcTest: read from Ashmem result is : " + readResult); + } catch(error) { + console.info("Rpc read from ashmem fail, errorCode " + error.code); + console.info("Rpc read from ashmem fail, errorMessage " + error.message); + } + ``` + + +### readFromAshmem8+(deprecated) + +>This API is no longer maintained since API version 9. You are advised to use [readAshmem](#readashmem9). + +readFromAshmem(size: number, offset: number): number[] + +Reads data from the shared file associated with this **Ashmem** object. + +**System capability**: SystemCapability.Communication.IPC.Core + +**Parameters** + + | Name| Type | Mandatory| Description | + | ------ | ------ | ---- | -------------------------------------------------- | + | size | number | Yes | Size of the data to read. | + | offset | number | Yes | Start position of the data to read in the memory region associated with this **Ashmem** object.| + +**Return value** + + | Type | Description | + | -------- | ---------------- | + | number[] | Data read.| + +**Example** + + ``` let ashmem = rpc.Ashmem.createAshmem("ashmem", 1024*1024); let mapResult = ashmem.mapReadAndWriteAshmem(); console.info("RpcTest map ashmem result is " + mapResult); diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md index 1b25989357a2e101b5b6e95d05b5ca60dab2fb6f..ee70e09ca874602bf8e41f3d4001b61caa5a0344 100644 --- a/en/application-dev/reference/apis/js-apis-runninglock.md +++ b/en/application-dev/reference/apis/js-apis-runninglock.md @@ -1,95 +1,205 @@ -# Running Lock +# @ohos.runningLock (Runninglock) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+The **runningLock** module provides APIs for creating, querying, holding, and releasing running locks. + +> **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 Running Lock module provides APIs for creating, querying, holding, and releasing running locks. +## Modules to Import +```js +import runningLock from '@ohos.runningLock'; +``` -## Modules to Import +## runningLock.isSupported9+ + +isSupported(type: RunningLockType): boolean; + +Checks whether a specified type of **RunningLock** is supported. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| + +**Return value** + +| Type | Description | +| ------- | --------------------------------------- | +| boolean | The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** +```js +try { + var isSupported = runningLock.isSupported(runningLock.RunningLockType.BACKGROUND); + console.info('BACKGROUND type supported: ' + isSupported); +} catch(err) { + console.error('check supported failed, err: ' + err); +} ``` -import runningLock from '@ohos.runningLock'; + +## runningLock.create9+ + +create(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void + +Creates a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created. | +| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to return the result. If a lock is successfully created, **err** is **undefined** and **data** is the created **RunningLock**. Otherwise, **err** is an error object.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); + } else { + console.error('create running lock failed, err: ' + err); + } +}); ``` +## runningLock.create9+ -## RunningLockType +create(name: string, type: RunningLockType): Promise<RunningLock> -Enumerates the types of **RunningLock** objects. +Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core -| Name | Default Value | Description | -| ------------------------ | ---- | ------------------- | -| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. | -| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.| +**Required permission:** ohos.permission.RUNNING_LOCK +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| + +**Return value** + +| Type | Description | +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise used to return the result.| -## isRunningLockTypeSupported +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); +}) +.catch(err => { + console.error('create running lock failed, error: ' + err); +}); +``` + +## runningLock.isRunningLockTypeSupported(deprecated) isRunningLockTypeSupported(type: RunningLockType, callback: AsyncCallback<boolean>): void -Checks whether a specified type of **RunningLock** is supported. This function uses an asynchronous callback to return the result. +> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. + +Checks whether a specified type of **RunningLock** is supported. This API uses an asynchronous callback to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------- | ---- | ---------------------------------------- | -| type | RunningLockType | Yes | Type of the **RunningLock** object. | -| callback | AsyncCallback<boolean> | Yes | Callback used to obtain the return value.
Return value: The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------- | ---- | ------------------------------------------------------------ | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object. | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the query result obtained, where the value **true** indicates that **RunningLock** is supported and **false** indicates the opposite. Otherwise, **err** is an error object.| **Example** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (error, supported) => { - if (typeof error === "undefined") { - console.info('BACKGROUND support status is ' + supported); +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND, (err, data) => { + if (typeof err === 'undefined') { + console.info('BACKGROUND lock support status: ' + data); } else { - console.log('error: ' + error); + console.log('check BACKGROUND lock support status failed, err: ' + err); } -}) +}); ``` +## runningLock.isRunningLockTypeSupported(deprecated) -## isRunningLockTypeSupported +isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> -isRunningLockTypeSupported(type: RunningLockType): Promise<boolean> +> This API is deprecated since API version 9. You are advised to use [runningLock.isSupported](#runninglockissupported9) instead. -Checks whether a specified type of **RunningLock** is supported. This function uses an asynchronous callback to return the result. +Checks whether a specified type of **RunningLock** is supported. This API uses a promise to return the result. **System capability:** SystemCapability.PowerManager.PowerManager.Core **Parameters** -| Name | Type | Mandatory | Description | -| ---- | --------------- | ---- | ---------- | -| type | RunningLockType | Yes | Type of the **RunningLock** object.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | -------------------- | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object.| -**Return Value** +**Return value** -| Type | Description | -| ---------------------- | ---------------------------------------- | -| Promise<boolean> | Promise used to asynchronously obtain the return value.
Return value: The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| +| Type | Description | +| ---------------------- | ---------------------------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the specified type of **RunningLock** is supported, and the value **false** indicates the opposite.| **Example** -``` -runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.PROXIMITY_SCREEN_CONTROL) -.then(supported => { - console.info('PROXIMITY_SCREEN_CONTROL support status is ' + supported); +```js +runningLock.isRunningLockTypeSupported(runningLock.RunningLockType.BACKGROUND) +.then(data => { + console.info('BACKGROUND lock support status: ' + data); }) -.catch(error => { - console.log('error: ' + error); +.catch(err => { + console.log('check BACKGROUND lock support status failed, err: ' + err); }); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType, callback: AsyncCallback<RunningLock>): void +> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. + Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -98,33 +208,30 @@ Creates a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ---------------------------------------- | ---- | -------------------------------------- | -| name | string | Yes | Name of the **RunningLock** object. | -| type | RunningLockType | Yes | Type of the **RunningLock** object to be created. | -| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to obtain the return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------ | ---- | ------------------------------------------------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created. | +| callback | AsyncCallback<[RunningLock](#runninglock)> | Yes | Callback used to return the result. If a lock is successfully created, **err** is **undefined** and **data** is the created **RunningLock**. Otherwise, **err** is an error object.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND, (error, lockIns) => { - if (typeof error === "undefined") { - var used = lockIns.isUsed(); - console.info('runninglock is used: ' + used); - lockIns.lock(500); - used = lockIns.isUsed(); - console.info('after lock runninglock is used ' + used); +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND, (err, lock) => { + if (typeof err === 'undefined') { + console.info('created running lock: ' + lock); } else { - console.log('create runningLock test error: ' + error); + console.error('create running lock failed, err: ' + err); } -}) +}); ``` - -## createRunningLock +## runningLock.createRunningLock(deprecated) createRunningLock(name: string, type: RunningLockType): Promise<RunningLock> +> This API is deprecated since API version 9. You are advised to use [runningLock.create](#runninglockcreate9) instead. + Creates a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -133,39 +240,157 @@ Creates a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| ---- | --------------- | ---- | --------- | -| name | string | Yes | Name of the **RunningLock** object. | -| type | RunningLockType | Yes | Type of the **RunningLock** object to be created.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------------- | ---- | ------------------ | +| name | string | Yes | Name of the **RunningLock** object. | +| type | [RunningLockType](#runninglocktype) | Yes | Type of the **RunningLock** object to be created.| -**Return Value** +**Return value** | Type | Description | -| ---------------------------------------- | ---------------------------------- | -| Promise<[RunningLock](#runninglock)> | Promise used to asynchronously obtain the returned **RunningLock** object.| +| ------------------------------------------ | ------------------------------------ | +| Promise<[RunningLock](#runninglock)> | Promise used to return the result.| **Example** +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('created running lock: ' + lock); +}) +.catch(err => { + console.log('create running lock failed, err: ' + err); +}); ``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runninglock => { - console.info('create runningLock success'); + +## RunningLock + +Represents a **RunningLock** object. + +### hold9+ + +hold(timeout: number): void + +Locks and holds a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------- | +| timeout | number | Yes | Duration for locking and holding the **RunningLock** object, in ms.| + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.hold(500); + console.info('hold running lock success'); + } catch(err) { + console.error('hold running lock failed, err: ' + err); + } }) -.catch(error => { - console.log('create runningLock test error: ' + error); +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### unhold9+ + +unhold(): void + +Releases a **RunningLock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +**Required permission:** ohos.permission.RUNNING_LOCK + +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|----------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + lock.unhold(); + console.info('unhold running lock success'); + } catch(err) { + console.error('unhold running lock failed, err: ' + err); + } }) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); ``` +### isHolding9+ -## RunningLock +isHolding(): boolean + +Checks the hold status of the **Runninglock** object. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core -Defines a **RunningLock** object. +**Return value** +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.| -### lock +**Error codes** + +For details about the error codes, see [RunningLock Error Codes](../errorcodes/errorcode-runninglock.md). + +| Code | Error Message | +|---------|---------| +| 4900101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +runningLock.create('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + console.info('create running lock success'); + try { + var isHolding = lock.isHolding(); + console.info('check running lock holding status: ' + isHolding); + } catch(err) { + console.error('check running lock holding status failed, err: ' + err); + } +}) +.catch(err => { + console.error('create running lock failed, err: ' + err); +}); +``` + +### lock(deprecated) lock(timeout: number): void +> This API is deprecated since API version 9. You are advised to use [RunningLock.hold](#hold9) instead. + Locks and holds a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -174,29 +399,30 @@ Locks and holds a **RunningLock** object. **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ------ | ---- | -------------------------- | -| timeout | number | No | Duration for locking and holding the **RunningLock** object, in ms.| +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ----------------------------------------- | +| timeout | number | Yes | Duration for locking and holding the **RunningLock** object, in ms.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.lock(100) - console.info('create runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.lock(500); + console.info('create running lock and lock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### unlock +### unlock(deprecated) unlock(): void -Releases a **Runninglock** object. +> This API is deprecated since API version 9. You are advised to use [RunningLock.unhold](#unhold9) instead. + +Releases a **RunningLock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core @@ -204,40 +430,52 @@ Releases a **Runninglock** object. **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - runningLock.unlock() - console.info('create and unLock runningLock success') +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + lock.unlock(); + console.info('create running lock and unlock success'); }) -.catch(error => { - console.log('create runningLock test error: ' + error) +.catch(err => { + console.error('create running lock failed, err: ' + err); }); ``` - -### isUsed +### isUsed(deprecated) isUsed(): boolean -Checks the status of the **Runninglock** object. +> This API is deprecated since API version 9. You are advised to use [RunningLock.isHolding](#isholding9) instead. + +Checks the hold status of the **Runninglock** object. **System capability:** SystemCapability.PowerManager.PowerManager.Core -**Return Value** -| Type | Description | -| ------- | ------------------------------------- | -| boolean | Returns **true** if the **Runninglock** object is held; returns **false** if the **Runninglock** object is released.| +**Return value** +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | The value **true** indicates that the **Runninglock** object is held; and the value **false** indicates that the **Runninglock** object is released.| **Example** -``` -runningLock.createRunningLock("running_lock_test", runningLock.RunningLockType.BACKGROUND) -.then(runningLock => { - var used = runningLock.isUsed() - console.info('runningLock used status: ' + used) +```js +runningLock.createRunningLock('running_lock_test', runningLock.RunningLockType.BACKGROUND) +.then(lock => { + var isUsed = lock.isUsed(); + console.info('check running lock used status: ' + isUsed); }) -.catch(error => { - console.log('runningLock isUsed test error: ' + error) +.catch(err => { + console.error('check running lock used status failed, err: ' + err); }); ``` + +## RunningLockType + +Enumerates the types of **RunningLock** objects. + +**System capability:** SystemCapability.PowerManager.PowerManager.Core + +| Name | Value | Description | +| ------------------------ | ---- | -------------------------------------- | +| BACKGROUND | 1 | A lock that prevents the system from hibernating when the screen is off. | +| PROXIMITY_SCREEN_CONTROL | 2 | A lock that determines whether to turn on or off the screen based on the distance away from the screen.| diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index c006791851e65d913d830904998ab08ebb347f0a..c726ec7c8fdd4cd6f16d71f5a6892bc565b66cf6 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -1,4 +1,4 @@ -# Screen Lock Management +# @ohos.screenLock (Screenlock) The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set. @@ -12,445 +12,498 @@ The **screenlock** module is a system module in OpenHarmony. It provides APIs fo import screenlock from '@ohos.screenLock'; ``` -## screenlock.isScreenLocked - -isScreenLocked(callback: AsyncCallback<boolean>): void - -Checks whether the screen is locked. This API uses an asynchronous callback to return the result. +## EventType -> **NOTE** -> ->This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked9+](#screenlockislocked9) instead. +Defines the system event type. **System capability**: SystemCapability.MiscServices.ScreenLock -**Parameters** +| Event Type | Description | +| ------------------ | ------------------------ | +| beginWakeUp | Wakeup starts.| +| endWakeUp | Wakeup ends.| +| beginScreenOn | Screen turn-on starts.| +| endScreenOn | Screen turn-on ends.| +| beginScreenOff | Screen turn-off starts.| +| endScreenOff | Screen turn-off ends.| +| unlockScreen | The screen is unlocked. | +| lockScreen | The screen is locked. | +| beginExitAnimation | Exit animation starts. | +| beginSleep | The device enters sleep mode. | +| endSleep | The device exits sleep mode. | +| changeUser | The user is switched. | +| screenlockEnabled | Screen lock is enabled. | +| serviceRestart | The screen lock service is restarted. | -| Name | Type | Mandatory| Description | -| -------- | ---------------------------- | ---- | ----------------------------------------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.| +## SystemEvent -**Example** +Defines the structure of the system event callback. -```js -screenlock.isScreenLocked((err, data)=>{ - if (err) { - console.error('isScreenLocked callback error -> ${JSON.stringify(err)}'); - return; - } - console.info('isScreenLocked callback success data -> ${JSON.stringify(data)}'); -}); -``` +**System capability**: SystemCapability.MiscServices.ScreenLock -## screenlock.isScreenLocked +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------- | +| eventType | [EventType](#eventtype) | Yes | System event type.| +| params | string | Yes | System event parameters.| -isScreenLocked(): Promise<boolean> +## screenlock.isLocked9+ -Checks whether the screen is locked. This API uses a promise to return the result. +isLocked(): boolean -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked9+](#screenlockislocked9) instead. +Checks whether the screen is locked. **System capability**: SystemCapability.MiscServices.ScreenLock **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------- | -| Promise<boolean> | Promise used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.| +| Type | Description | +| ------- | ------------------------------------------------- | +| boolean | Returns **true** if the screen is locked; returns **false** otherwise.| **Example** ```js -screenlock.isScreenLocked().then((data) => { - console.log('isScreenLocked success: data -> ${JSON.stringify(data)}'); -}).catch((err) => { - console.error('isScreenLocked fail, promise: err -> ${JSON.stringify(err)}'); -}); +let isLocked = screenlock.isLocked(); ``` -## screenlock.isLocked9+ +## screenlock.isSecure9+ -isLocked(): boolean +isSecure(): boolean -Checks whether the screen is locked. This API returns the result synchronously. +Checks whether the device is in secure mode. When the device is in secure mode, its screen requires a password, unlock pattern, or other user credentials to unlock. **System capability**: SystemCapability.MiscServices.ScreenLock **Return value** -| Type | Description | -| ------- | ------------------------------------------------- | -| boolean | Returns **true** if the screen is locked; returns **false** otherwise.| +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Returns **true** if the device is in secure mode; returns **false** otherwise.| **Example** ```js -let isLocked = screenlock.isLocked(); +let isSecure = screenlock.isSecure(); ``` -## screenlock.isSecureMode - -isSecureMode(callback: AsyncCallback<boolean>): void +## screenlock.unlock9+ -Checks whether the device is in secure mode. This API uses an asynchronous callback to return the result. +unlock(callback: AsyncCallback<boolean>): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure9+](#screenlockissecure9) instead. +Unlocks the screen. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------ | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Screen Lock Management Error Codes](../errorcodes/errorcode-screenlock.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 13200002 | The screenlock management service is abnormal. | **Example** ```js -screenlock.isSecureMode((err, data)=>{ +screenlock.unlock((err, data) => { if (err) { - console.error('isSecureMode callback error -> ${JSON.stringify(err)}'); + console.error(`Failed to unlock the screen, because: ${err.message}`); return; } - console.info('isSecureMode callback success data -> ${JSON.stringify(err)}'); + console.info(`unlock the screen successfully. result: ${data}`); }); ``` -## screenlock.isSecureMode - -isSecureMode(): Promise<boolean> +## screenlock.unlock9+ -Checks whether the device is in secure mode. This API uses a promise to return the result. +unlock(): Promise<boolean> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure9+](#screenlockissecure9) instead. +Unlocks the screen. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.| +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Screen Lock Management Error Codes](../errorcodes/errorcode-screenlock.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 13200002 | The screenlock management service is abnormal. | **Example** ```js -screenlock.isSecureMode().then((data) => { - console.log('isSecureMode success: data->${JSON.stringify(data)}'); +screenlock.unlock().then((data) => { + console.info(`unlock the screen successfully. result: ${data}`); }).catch((err) => { - console.error('isSecureMode fail, promise: err->${JSON.stringify(err)}'); + console.error(`Failed to unlock the screen, because: ${err.message}`); }); ``` -## screenlock.isSecure9+ +## screenlock.lock9+ -isSecure(): boolean +lock(callback: AsyncCallback<boolean>): void -Checks whether the device is in secure mode. +Locks the screen. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -**Return value** +**System API**: This is a system API. -| Type | Description | -| ------- | ------------------------------------------------------------ | -| boolean | The value **true** means that the device is in secure mode, and **false** means the opposite.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ---------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Screen Lock Management Error Codes](../errorcodes/errorcode-screenlock.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 13200002 | The screenlock management service is abnormal. | **Example** ```js -let isSecure = screenlock.isSecure(); +screenlock.lock((err, data) => { + if (err) { + console.error(`Failed to lock the screen, because: ${err.message}`); + return; + } + console.info(`lock the screen successfully. result: ${data}`); +}); ``` -## screenlock.unlockScreen - -unlockScreen(callback: AsyncCallback<void>): void +## screenlock.lock9+ -Unlocks the screen. This API uses an asynchronous callback to return the result. +lock(): Promise<boolean> -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock9+](#screenlockunlock9) instead. +Locks the screen. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock -**Parameters** +**System API**: This is a system API. -| Name | Type | Mandatory| Description | -| -------- | ------------- | ---- | --------------- | -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation fails, an error message is returned.| +**Return value** + +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [Screen Lock Management Error Codes](../errorcodes/errorcode-screenlock.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 13200002 | The screenlock management service is abnormal. | **Example** ```js -screenlock.unlockScreen((err) => { - if (err) { - console.error('unlockScreen callback error -> ${JSON.stringify(err)}'); - return; - } - console.info('unlockScreen callback success'); +screenlock.lock().then((data) => { + console.info(`lock the screen successfully. result: ${data}`); +}).catch((err) => { + console.error(`Failed to lock the screen, because: ${err.message}`); }); ``` -## screenlock.unlockScreen - -unlockScreen(): Promise<void> +## screenlock.onSystemEvent9+ -Unlocks the screen. This API uses a promise to return the result. +onSystemEvent(callback: Callback<SystemEvent>): boolean -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock9+](#screenlockunlock9) instead. +Registers a callback for system events related to screen locking. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ----------------- | +| callback | Callback\<[SystemEvent](#systemevent)> | Yes | Callback for system events related to screen locking.| + **Return value** -| Type | Description | -| ------------------- | ------------------------- | -| Promise<void> | Promise that returns no value.| +| Type | Description | +| ------- | ------------------------------------------------- | +| boolean | Returns **true** if the callback is registered successfully; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Screen Lock Management Error Codes](../errorcodes/errorcode-screenlock.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 13200002 | The screenlock management service is abnormal. | **Example** ```js -screenlock.unlockScreen().then(() => { - console.log('unlockScreen success'); -}).catch((err) => { - console.error('unlockScreen fail, promise: err->${JSON.stringify(err)}'); -}); +try { + let isSuccess = screenlock.onSystemEvent((event) => { + console.log(`Register the system event which related to screenlock successfully. eventType: ${event.eventType}`) + }); +} catch (err) { + console.error(`Failed to register the system event which related to screenlock, because: ${err.message}`) +} ``` -## screenlock.unlock9+ +## screenlock.sendScreenLockEvent9+ -unlock(callback: AsyncCallback<boolean>): void +sendScreenLockEvent(event: string, parameter: number, callback: AsyncCallback<boolean>): void -Unlocks the screen. This API uses an asynchronous callback to return the result. +Sends an event to the screen lock service. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| --------- | ------------------------ | ---- | -------------------- | +| event | string | Yes | Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| +| parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**, the operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. The **value** true means that the event is sent successfully, and **false** means the opposite. | + +**Error codes** + +For details about the error codes, see [Screen Lock Management Error Codes](../errorcodes/errorcode-screenlock.md). + +| ID| Error Message| +| -------- | ---------------------------------------- | +| 13200002 | The screenlock management service is abnormal. | **Example** ```js -screenlock.unlock((err,data) => { +screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { if (err) { - console.error('unlock error -> ${JSON.stringify(err)}'); - return; + console.error(`Failed to send screenlock event, because: ${err.message}`); + return; } - console.info('unlock success data -> ${JSON.stringify(data)}'); + console.info(`Send screenlock event successfully. result: ${result}`); }); ``` -## screenlock.unlock9+ +## screenlock.sendScreenLockEvent9+ -unlock(): Promise<boolean> +sendScreenLockEvent(event: string, parameter: number): Promise<boolean> -Unlocks the screen. This API uses a promise to return the result. +Sends an event to the screen lock service. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.ScreenLock +**System API**: This is a system API. + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | --------------------------------------- | +| event | string | Yes | Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"lockScreenResult"**: Screen lock result.
- **"screenDrawDone"**: Screen drawing is complete.| +| parameter | number | Yes | Result.
- **0**: The operation is successful. For example, the screen is locked or unlocked successfully.
- **1**, the operation fails. For example, screen locking or unlocking fails.
- **2**: The operation is canceled. For example, screen locking or unlocking is canceled.| + **Return value** -| Type | Description | -| ------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value **true** means that the screen is unlocked successfully, and **false** means the opposite.| +| Type | Description | +| ----------------- | ---------------------------------------------- | +| Promise\ | Promise used to return the result. The **value** true means that the event is sent successfully, and **false** means the opposite.| **Example** ```js -screenlock.unlock().then((data) => { - console.log('unlock success'); +screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => { + console.info(`Send screenlock event successfully. result: ${result}`); }).catch((err) => { - console.error('unlock fail, : err->${JSON.stringify(err)}'); + console.error(`Failed to send screenlock event, because: ${err.message}`); }); ``` -## screenlock.lock9+ +## screenlock.isScreenLocked(deprecated) -lock(callback: AsyncCallback<boolean>): void +isScreenLocked(callback: AsyncCallback<boolean>): void -Locks the screen. This API uses an asynchronous callback to return the result. +Checks whether the screen is locked. This API uses an asynchronous callback to return the result. -**System capability**: SystemCapability.MiscServices.ScreenLock +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked9+](#screenlockislocked9) instead. -**System API**: This is a system API. +**System capability**: SystemCapability.MiscServices.ScreenLock **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ---------------- | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ----------------------------------------------------------- | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.| **Example** ```js -screenlock.lock((err,data) => { +screenlock.isScreenLocked((err, data)=>{ if (err) { - console.error('lock callback error -> ${JSON.stringify(err)}'); + console.error(`Failed to obtain whether the screen is locked, because: ${err.message}`); return; } - console.info('lock callback success'); + console.info(`Obtain whether the screen is locked successfully. result: ${data}`); }); ``` -## screenlock.lock9+ +## screenlock.isScreenLocked(deprecated) -lock(): Promise<boolean> +isScreenLocked(): Promise<boolean> -Locks the screen. This API uses a promise to return the result. +Checks whether the screen is locked. This API uses a promise to return the result. -**System capability**: SystemCapability.MiscServices.ScreenLock +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isLocked9+](#screenlockislocked9) instead. -**System API**: This is a system API. +**System capability**: SystemCapability.MiscServices.ScreenLock **Return value** -| Type | Description | -| ---------------------- | ------------------------------------------------------------ | -| Promise<boolean> | Promise used to return the result. The value **true** means that the screen is locked successfully, and **false** means the opposite.| +| Type | Description | +| ---------------------- | ------------------------------------------- | +| Promise<boolean> | Promise used to return the result. The value **true** means that the screen is locked, and **false** means the opposite.| **Example** ```js -screenlock.lock().then((data) => { - console.log('lock success'); +screenlock.isScreenLocked().then((data) => { + console.info(`Obtain whether the screen is locked successfully. result: ${data}`); }).catch((err) => { - console.error('lock fail, promise: err->${JSON.stringify(err)}'); + console.error(`Failed to obtain whether the screen is locked, because: ${err.message}`); }); ``` -## EventType - -Defines the system event type. - -**System capability**: SystemCapability.MiscServices.ScreenLock - -| Event Type | Description | -| ------------------ | ------------------------ | -| beginWakeUp | Wakeup starts when the event starts.| -| endWakeUp | Wakeup ends when the event ends.| -| beginScreenOn | Screen turn-on starts when the event starts.| -| endScreenOn | Screen turn-on ends when the event ends.| -| beginScreenOff | Screen turn-off starts when the event starts.| -| endScreenOff | Screen turn-off ends when the event ends.| -| unlockScreen | The screen is unlocked. | -| lockScreen | The screen is locked. | -| beginExitAnimation | Animation starts to exit. | -| beginSleep | The screen enters sleep mode. | -| endSleep | The screen exits sleep mode. | -| changeUser | The user is switched. | -| screenlockEnabled | Screen lock is enabled. | -| serviceRestart | The screen lock service is restarted. | +## screenlock.isSecureMode(deprecated) +isSecureMode(callback: AsyncCallback<boolean>): void -## SystemEvent +Checks whether the device is in secure mode. When the device is in secure mode, its screen requires a password, unlock pattern, or other user credentials to unlock. This API uses an asynchronous callback to return the result. -Defines the structure of the system event callback. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure9+](#screenlockissecure9) instead. **System capability**: SystemCapability.MiscServices.ScreenLock -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | ------------- | -| eventType | [EventType](#eventtype) | Yes | System event type.| -| params | string | Yes | System event parameters.| +**Parameters** -## screenlock.onSystemEvent9+ +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------ | +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.| -onSystemEvent(callback: Callback\): boolean +**Example** -Registers a callback for system events related to screen locking. +```js +screenlock.isSecureMode((err, data)=>{ + if (err) { + console.error(`Failed to obtain whether the device is in secure mode, because: ${err.message}`); + return; + } + console.info(`Obtain whether the device is in secure mode successfully. result: ${data}`); +}); +``` -**System capability**: SystemCapability.MiscServices.ScreenLock +## screenlock.isSecureMode(deprecated) -**System API**: This is a system API. +isSecureMode(): Promise<boolean> -**Parameters** +Checks whether the device is in secure mode. When the device is in secure mode, its screen requires a password, unlock pattern, or other user credentials to unlock. This API uses a promise to return the result. -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------- | ---- | ---------------------------- | -| callback | Callback\<[SystemEvent](#systemevent)> | Yes | Callback for system events related to screen locking.| +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.isSecure9+](#screenlockissecure9) instead. + +**System capability**: SystemCapability.MiscServices.ScreenLock **Return value** -| Type | Description | -| ------- | ------------------------------------------------- | -| boolean | Returns **true** if the callback is registered successfully; returns **false** otherwise.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. The value **true** means that the device is in secure mode, and **false** means the opposite.| **Example** ```js -let isSuccess = screenlock.onSystemEvent((event)=>{ - console.log(`onSystemEvent:callback:${event.eventType}`) +screenlock.isSecureMode().then((data) => { + console.info(`Obtain whether the device is in secure mode successfully. result: ${data}`); +}).catch((err) => { + console.error(`Failed to obtain whether the device is in secure mode, because: ${err.message}`); }); -if (!isSuccess) { - console.log(`onSystemEvent result is false`) -} ``` +## screenlock.unlockScreen(deprecated) -## screenlock.sendScreenLockEvent9+ +unlockScreen(callback: AsyncCallback<void>): void -sendScreenLockEvent(event: String, parameter: number, callback: AsyncCallback\): void +Unlocks the screen. This API uses an asynchronous callback to return the result. -Sends an event to the screen lock service. 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 [screenlock.unlock9+](#screenlockunlock9) instead. **System capability**: SystemCapability.MiscServices.ScreenLock -**System API**: This is a system API. - **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------ | ---- | -------------------- | -| event | String | Yes | Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.| -| parameter | number | Yes | Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.| -| callback | AsyncCallback\ | Yes | Callback used to return the result. The value **true** means that the operation is successful, and **false** means the opposite. | +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | --------------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the screen is unlocked successfully, **err** is **undefined**; otherwise, **err** is an error object.| **Example** ```js -screenlock.sendScreenLockEvent('unlockScreenResult', 0, (err, result) => { - console.log('sending result:' + result); +screenlock.unlockScreen((err) => { + if (err) { + console.error(`Failed to unlock the screen, because: ${err.message}`); + return; + } + console.info('unlock the screen successfully.'); }); ``` -## screenlock.sendScreenLockEvent9+ - -sendScreenLockEvent(event: String, parameter: number): Promise\ - -Sends an event to the screen lock service. This API uses a promise to return the result. +## screenlock.unlockScreen(deprecated) -**System capability**: SystemCapability.MiscServices.ScreenLock +unlockScreen(): Promise<void> -**System API**: This is a system API. +Unlocks the screen. This API uses a promise to return the result. -**Parameters** +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [screenlock.unlock9+](#screenlockunlock9) instead. -| Name | Type | Mandatory| Description | -| --------- | ------ | ---- | --------------------------------------- | -| event | String | Yes | Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.| -| parameter | number | Yes | Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.| +**System capability**: SystemCapability.MiscServices.ScreenLock **Return value** -| Type | Description | -| ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. The value **true** means that the operation is successful, and **false** means the opposite.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js -screenlock.sendScreenLockEvent('unlockScreenResult', 0).then((result) => { - console.log('sending result:' + result); +screenlock.unlockScreen().then(() => { + console.info('unlock the screen successfully.'); +}).catch((err) => { + console.error(`Failed to unlock the screen, because: ${err.message}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md index 0f5d909e9b038c65bcd353afae633495a9bd2c4b..22f25f8f0185b954270c2169fc657f0676244623 100644 --- a/en/application-dev/reference/apis/js-apis-screen.md +++ b/en/application-dev/reference/apis/js-apis-screen.md @@ -1,4 +1,4 @@ -# Screen +# @ohos.screen (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. diff --git a/en/application-dev/reference/apis/js-apis-screenshot.md b/en/application-dev/reference/apis/js-apis-screenshot.md index 0e8b04295567caf1a018a9f9d3c8122b7f89e41d..4fa5e15b59c8d70b09f5bcf8cd1e9686ba329a14 100644 --- a/en/application-dev/reference/apis/js-apis-screenshot.md +++ b/en/application-dev/reference/apis/js-apis-screenshot.md @@ -1,4 +1,5 @@ -# Screenshot +# @ohos.screenshot + The **Screenshot** module provides APIs for you to set information such as the region to capture and the size of the screen region when capturing a screen. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-sensor.md b/en/application-dev/reference/apis/js-apis-sensor.md index 6fdc718f8df4868cb7e7f9c12f2346b36032b953..69845e5552e2c21cb49852513e837c7976dcb8b3 100644 --- a/en/application-dev/reference/apis/js-apis-sensor.md +++ b/en/application-dev/reference/apis/js-apis-sensor.md @@ -1,8 +1,9 @@ -# Sensor +# @ohos.sensor (Sensor) The **Sensor** module provides APIs for obtaining the sensor list and subscribing to sensor data. It also provides some common sensor algorithms. > **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. @@ -3495,9 +3496,9 @@ Describes the acceleration sensor data. It extends from [Response](#response). | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ------------------------------------ | -| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s2.| +| x | number | Yes | Yes | Acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Acceleration along the z-axis of the device, in m/s². | ## LinearAccelerometerResponse @@ -3509,9 +3510,9 @@ Describes the linear acceleration sensor data. It extends from [Response](#respo | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | -| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s2.| +| x | number | Yes | Yes | Linear acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Linear acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Linear acceleration along the z-axis of the device, in m/s². | ## AccelerometerUncalibratedResponse @@ -3523,12 +3524,12 @@ Describes the uncalibrated acceleration sensor data. It extends from [Response]( | Name | Type | Readable| Writable| Description | | ----- | ------ | ---- | ---- | ------------------------------------------------ | -| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s2. | -| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s2. | -| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s2. | -| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s2. | -| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s2.| -| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s2. | +| x | number | Yes | Yes | Uncalibrated acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Uncalibrated acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Uncalibrated acceleration along the z-axis of the device, in m/s². | +| biasX | number | Yes | Yes | Uncalibrated acceleration bias along the x-axis of the device, in m/s². | +| biasY | number | Yes | Yes | Uncalibrated acceleration bias along the y-axis of the device, in m/s². | +| biasZ | number | Yes | Yes | Uncalibrated acceleration bias along the z-axis of the device, in m/s². | ## GravityResponse @@ -3540,9 +3541,9 @@ Describes the gravity sensor data. It extends from [Response](#response). | Name| Type | Readable| Writable| Description | | ---- | ------ | ---- | ---- | ---------------------------------------- | -| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s2.| -| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s2.| -| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s2.| +| x | number | Yes | Yes | Gravitational acceleration along the x-axis of the device, in m/s². | +| y | number | Yes | Yes | Gravitational acceleration along the y-axis of the device, in m/s². | +| z | number | Yes | Yes | Gravitational acceleration along the z-axis of the device, in m/s². | ## OrientationResponse diff --git a/en/application-dev/reference/apis/js-apis-settings.md b/en/application-dev/reference/apis/js-apis-settings.md index 9474b7a298b40546ae1b5fe1a7c639efb1195de3..5972e0cd9a278dcc49b634b6d05e8d76f3fa0a1d 100644 --- a/en/application-dev/reference/apis/js-apis-settings.md +++ b/en/application-dev/reference/apis/js-apis-settings.md @@ -1,4 +1,4 @@ -# Settings +# @ohos.settings The **settings** module provides APIs for setting data items. @@ -24,8 +24,8 @@ Provides data items for setting the time and date formats. | ------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | 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.| +| 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 @@ -39,7 +39,7 @@ Provides data items for setting the display effects. | ----------------------------- | ------ | ---- | ---- | ------------------------------------------------------------ | | 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 | 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). | @@ -47,7 +47,7 @@ Provides data items for setting the display effects. | 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.| +| 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 @@ -248,7 +248,7 @@ Obtains the value of a data item in the database. This API uses an asynchronous | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-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. | @@ -280,7 +280,7 @@ Obtains the value of a data item in the database. This API uses a promise to ret | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-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** @@ -315,7 +315,7 @@ Sets the value for a data item. This API uses an asynchronous callback to return | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-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. | @@ -347,7 +347,7 @@ Sets the value for a data item. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-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. | @@ -512,9 +512,9 @@ Obtains the value of a data item. Unlike **getValue**, this API returns the resu | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-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.| +| defValue | string | Yes | Default value, which is returned when the value of a data item is not found in the database. Set this parameter as needed. | **Return value** @@ -541,7 +541,7 @@ Sets the value for a data item. Unlike **setValue**, this API returns the result 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.MANAGE_SECUER_SETTINGS (available only to system applications) +**Required permissions**: ohos.permission.MANAGE_SECURE_SETTINGS (available only to system applications) **System capability**: SystemCapability.Applications.settings.Core @@ -549,7 +549,7 @@ If the specified data item exists in the database, the **setValueSync** method u | Name | Type | Mandatory| Description | | ----------------- | ------------------------------------------------- | ---- | ------------------------------------------------------------ | -| dataAbilityHelper | [DataAbilityHelper](js-apis-dataAbilityHelper.md) | Yes | **DataAbilityHelper** class. | +| dataAbilityHelper | [DataAbilityHelper](js-apis-inner-ability-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. | diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index a5515dadfbd141dc16bfa44b2edffea5013109f4..eb88ca8c05459fca0ba2ecd4dfcab60d49677aae 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -1,6 +1,6 @@ -# SIM Management +# @ohos.telephony.sim (SIM Management) -The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. +The **sim** module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card. >**NOTE** > @@ -1155,6 +1155,8 @@ Obtains the lock status of the SIM card in the specified slot. This API uses an **System API**: This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -1182,6 +1184,8 @@ Obtains the lock status of the SIM card in the specified slot. This API uses a p **System API**: This is a system API. +**Required permission**: ohos.permission.GET_TELEPHONY_STATE + **System capability**: SystemCapability.Telephony.CoreService **Parameters** @@ -2238,7 +2242,6 @@ Adds contact numbers for the SIM card in the specified slot. This API uses an as let diallingNumbersInof = { alphaTag: "alpha", number: "138xxxxxxxx", - recordNumber: 123, pin2: "1234" }; sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { @@ -2278,9 +2281,7 @@ Adds contact numbers for the SIM card in the specified slot. This API uses a pro ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + number: "138xxxxxxxx" }; let promise = sim.addIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { @@ -2316,9 +2317,7 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + number: "138xxxxxxxx" }; sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -2357,9 +2356,7 @@ Deletes contact numbers from the SIM card in the specified slot. This API uses a ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + number: "138xxxxxxxx" }; let promise = sim.delIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof); promise.then(data => { @@ -2395,9 +2392,7 @@ Updates contact numbers for the SIM card in the specified slot. This API uses an ```js let diallingNumbersInof = { alphaTag: "alpha", - number: "138xxxxxxxx", - recordNumber: 123, - pin2: "1234" + number: "138xxxxxxxx" }; sim.updateIccDiallingNumbers(0, sim.ContactType.GENERAL_CONTACT, diallingNumbersInof, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); @@ -2852,10 +2847,10 @@ Defines the lock status response. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| --------------- | ------ | ------------------ | -| result | number | Operation result. | -| remain?: number | number | Remaining attempts (can be null).| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| result | number | Yes | Operation result. | +| remain?: number | number | Yes | Remaining attempts (can be null).| ## LockInfo8+ @@ -2865,11 +2860,11 @@ Defines the lock information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | ------------------------ | ------ | -| lockType | [LockType](#locktype8) | Lock type.| -| password | string | Password. | -| state | [LockState](#lockstate8) | Lock state.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lockType | [LockType](#locktype8) | Yes | Lock type.| +| password | string | Yes | Password. | +| state | [LockState](#lockstate8) | Yes | Lock state.| ## PersoLockInfo8+ @@ -2879,10 +2874,10 @@ Defines the personalized lock information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| -------- | -------------------------------- | ------------ | -| lockType | [PersoLockType](#persolocktype8) | Personalized lock type.| -| password | string | Password. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| lockType | [PersoLockType](#persolocktype8) | Yes | Personalized lock type.| +| password | string | Yes | Password. | ## IccAccountInfo7+ @@ -2892,15 +2887,15 @@ Defines the ICC account information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ---------- | ------- | ---------------- | -| simId | number | SIM card ID. | -| slotIndex | number | Card slot ID. | -| isEsim | boolean | Whether the SIM card is an eSim card.| -| isActive | boolean | Whether the card is activated. | -| iccId | string | ICCID number. | -| showName | string | SIM card display name. | -| showNumber | string | SIM card display number. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| simId | number | Yes | SIM card ID. | +| slotIndex | number | Yes | Card slot ID. | +| isEsim | boolean | Yes | Whether the SIM card is an eSim card.| +| isActive | boolean | Yes | Whether the card is activated. | +| iccId | string | Yes | ICCID number. | +| showName | string | Yes | SIM card display name. | +| showNumber | string | Yes | SIM card display number. | ## OperatorConfig8+ @@ -2910,10 +2905,10 @@ Defines the carrier configuration. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description| -| ----- | ------ | ---- | -| field | string | Field| -| value | string | Value | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| field | string | Yes | Field. | +| value | string | Yes | Value. | ## DiallingNumbersInfo8+ @@ -2923,12 +2918,12 @@ Defines the contact number information. **System capability**: SystemCapability.Telephony.CoreService -| Name | Type | Description | -| ------------ | ------ | -------- | -| alphaTag | string | Alpha tag. | -| number | string | Contact number. | -| recordNumber | number | Record number.| -| pin2 | string | PIN 2.| +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| alphaTag | string | Yes | Alpha tag. | +| number | string | Yes | Contact number. | +| recordNumber | number | Yes | Record number.| +| pin2 | string | Yes | PIN 2.| ## ContactType8+ @@ -2939,6 +2934,37 @@ Enumerates contact types. **System capability**: SystemCapability.Telephony.CoreService | Name | Value | Description | -| :-------------- | ---- | ---------- | +| -------------- | ---- | ---------- | | GENERAL_CONTACT | 1 | Common contact number.| | FIXED_DIALING | 2 | Fixed dialing number. | + +## OperatorConfigKey9+ + +Enumerates carrier configuration keys. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +| Name | Value | Description | +| ------------------------------------------------------- | ---------------------------------------------------- | -------------------- | +| KEY_VOICE_MAIL_NUMBER_STRING | "voice_mail_number_string" | Voice mailbox number. | +| KEY_IMS_SWITCH_ON_BY_DEFAULT_BOOL | "ims_switch_on_by_default_bool" | Fixed dialing number. | +| KEY_HIDE_IMS_SWITCH_BOOL | "hide_ims_switch_bool" | Whether to hide the IMS switch. | +| KEY_VOLTE_SUPPORTED_BOOL | "volte_supported_bool" | Whether to support VoLTE. | +| KEY_NR_MODE_SUPPORTED_LIST_INT_ARRAY | "nr_mode_supported_list_int_array" | List of supported NR modes. | +| KEY_VOLTE_PROVISIONING_SUPPORTED_BOOL | "volte_provisioning_supported_bool" | Whether to support VoLTE provisioning. | +| KEY_SS_OVER_UT_SUPPORTED_BOOL | "ss_over_ut_supported_bool" | Whether SS over UT is supported. | +| KEY_IMS_GBA_REQUIRED_BOOL | "ims_gba_required_bool" | Whether GBA is required for IMS. | +| KEY_UT_PROVISIONING_SUPPORTED_BOOL | "ut_provisioning_supported_bool" | Whether to support UT provisioning. | +| KEY_IMS_PREFER_FOR_EMERGENCY_BOOL | "ims_prefer_for_emergency_bool" | IMS preferences for emergency. | +| KEY_CALL_WAITING_SERVICE_CLASS_INT | "call_waiting_service_class_int" | Call waiting service. | +| KEY_CALL_TRANSFER_VISIBILITY_BOOL | "call_transfer_visibility_bool" | Call transfer visibility. | +| KEY_IMS_CALL_DISCONNECT_REASONINFO_MAPPING_STRING_ARRAY | "ims_call_disconnect_reasoninfo_mapping_string_array" | List of IMS call disconnection reasons.| +| KEY_FORCE_VOLTE_SWITCH_ON_BOOL | "force_volte_switch_on_bool" | Whether to forcibly turn on VoLTE. | +| KEY_ENABLE_OPERATOR_NAME_CUST_BOOL | "enable_operator_name_cust_bool" | Whether to display the carrier name.| +| KEY_OPERATOR_NAME_CUST_STRING | "operator_name_cust_string" | Carrier name. | +| KEY_SPN_DISPLAY_CONDITION_CUST_INT | "spn_display_condition_cust_int" | SPN display rule. | +| KEY_PNN_CUST_STRING_ARRAY | "pnn_cust_string_array" | PLMN name | +| KEY_OPL_CUST_STRING_ARRAY | "opl_cust_string_array" | PLMN information of the carrier. | +| KEY_EMERGENCY_CALL_STRING_ARRAY | "emergency_call_string_array" | Emergency call list. | diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md index 7d372978202503f6ed0a0517fa69f85ae5dfcf44..901e3b258b7aa73530935baa81a6366f7aa50e65 100644 --- a/en/application-dev/reference/apis/js-apis-sms.md +++ b/en/application-dev/reference/apis/js-apis-sms.md @@ -1,6 +1,6 @@ -# SMS +# @ohos.telephony.sms (SMS) -The SMS module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. +The **sms** module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages. >**NOTE** > @@ -870,7 +870,7 @@ promise.then(data => { ## sms.isImsSmsSupported8+ -isImsSmsSupported(callback: AsyncCallback): void +isImsSmsSupported(slotId: number, callback: AsyncCallback): void Checks whether SMS is supported on IMS. This API uses an asynchronous callback to return the result. @@ -882,12 +882,14 @@ Checks whether SMS is supported on IMS. This API uses an asynchronous callback t | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ---------- | +| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback<boolean> | Yes | Callback used to return the result.| **Example** ```js -sms.isImsSmsSupported((err, data) => { +let slotId = 0; +sms.isImsSmsSupported(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` @@ -895,7 +897,7 @@ sms.isImsSmsSupported((err, data) => { ## sms.isImsSmsSupported8+ -isImsSmsSupported(): Promise +isImsSmsSupported(slotId: number): Promise Checks whether SMS is supported on IMS. This API uses a promise to return the result. @@ -903,6 +905,12 @@ Checks whether SMS is supported on IMS. This API uses a promise to return the re **System capability**: SystemCapability.Telephony.SmsMms +**Parameters** + +| Name| Type | Mandatory | Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + **Return value** | Type | Description | @@ -912,7 +920,8 @@ Checks whether SMS is supported on IMS. This API uses a promise to return the re **Example** ```js -let promise = sms.isImsSmsSupported(); +let slotId = 0; +let promise = sms.isImsSmsSupported(slotId); promise.then(data => { console.log(`isImsSmsSupported success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -1116,19 +1125,19 @@ Defines an SMS message instance. **System capability**: SystemCapability.Telephony.SmsMms -| Name | Type | Description | -| ------------------------ | --------------------------------------- | ------------------------------------------------------------ | -| hasReplyPath | boolean | Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| -| isReplaceMessage | boolean | Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| -| isSmsStatusReportMessage | boolean | Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| -| messageClass | [ShortMessageClass](#shortmessageclass) | Enumerates SMS message types. | -| pdu | Array<number> | PDU in the SMS message. | -| protocolId | number | Protocol identifier used for delivering the SMS message. | -| scAddress | string | SMSC address. | -| scTimestamp | number | SMSC timestamp. | -| status | number | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| -| visibleMessageBody | string | SMS message body. | -| visibleRawAddress | string | Sender address. | +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| hasReplyPath | boolean | Yes |Whether the received SMS contains **TP-Reply-Path**. The default value is **false**.
**TP-Reply-Path**: The device returns a response based on the SMSC that sends the SMS message.| +| isReplaceMessage | boolean | Yes |Whether the received SMS message is a **replace short message**. The default value is **false**.
For details, see section 9.2.3.9 in **3GPP TS 23.040**.| +| isSmsStatusReportMessage | boolean | Yes |Whether the received SMS message is an SMS delivery status report. The default value is **false**.
**SMS-Status-Report**: a message sent from the SMSC to the mobile station to show the SMS message delivery status.| +| messageClass | [ShortMessageClass](#shortmessageclass) | Yes | SMS message type. | +| pdu | Array<number> | Yes | PDU in the SMS message. | +| protocolId | number | Yes | Protocol identifier used for delivering the SMS message. | +| scAddress | string | Yes | SMSC address. | +| scTimestamp | number | Yes | SMSC timestamp. | +| status | number | Yes | SMS message status sent by the SMSC in the **SMS-STATUS-REPORT** message.| +| visibleMessageBody | string | Yes | SMS message body. | +| visibleRawAddress | string | Yes | Sender address. | ## ShortMessageClass diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md index cd0995948cc8354d05845c7156abcdfdfb558bda..bd14137464ce195f5c61b9d6a53ce6ef79cd3f10 100644 --- a/en/application-dev/reference/apis/js-apis-socket.md +++ b/en/application-dev/reference/apis/js-apis-socket.md @@ -1,13 +1,13 @@ -# Socket Connection +# @ohos.net.socket (Socket Connection) ->![](public_sys-resources/icon-note.gif) **NOTE:** -> ->The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> +The **socket** module implements socket connection management and operation. + +> **NOTE**
+> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import socket from '@ohos.net.socket'; ``` @@ -19,16 +19,16 @@ Creates a **UDPSocket** object. **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | -| :--------------------------------- | :---------------------- | +| --------------------------------- | ---------------------- | | [UDPSocket](#udpsocket) | **UDPSocket** object.| **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); ``` @@ -43,7 +43,7 @@ bind\(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -56,7 +56,7 @@ Binds the IP address and port number. The port number can be specified or random **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { @@ -74,7 +74,7 @@ bind\(address: NetAddress\): Promise Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -85,15 +85,15 @@ Binds the IP address and port number. The port number can be specified or random | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| -**Return Value** +**Return value** | Type | Description | -| :-------------- | :----------------------------------------- | +| -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); let promise = udp.bind({address: '192.168.xx.xxx', port: 8080, family: 1}); promise .then(() => { @@ -112,7 +112,7 @@ Sends data over a UDPSocket connection. This API uses an asynchronous callback t Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -125,7 +125,7 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.send({ data:'Hello, server!', @@ -152,7 +152,7 @@ Sends data over a UDPSocket connection. This API uses a promise to return the re Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and port. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -162,15 +162,15 @@ Before sending data, call [UDPSocket.bind()](#bind) to bind the IP address and p | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | options | [UDPSendOptions](#udpsendoptions) | Yes | Parameters for sending data over the UDPSocket connection. For details, see [UDPSendOptions](#udpsendoptions).| -**Return Value** +**Return value** | Type | Description | -| :-------------- | :--------------------------------------------- | +| -------------- | --------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); let promise = udp.send({ data:'Hello, server!', @@ -194,7 +194,7 @@ close\(callback: AsyncCallback\): void Closes a UDPSocket connection. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -206,7 +206,7 @@ Closes a UDPSocket connection. This API uses an asynchronous callback to return **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.close(err => { if (err) { @@ -224,19 +224,19 @@ close\(\): Promise Closes a UDPSocket connection. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | -| :-------------- | :----------------------------------------- | +| -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); let promise = udp.close(); promise.then(() => { @@ -253,10 +253,10 @@ getState\(callback: AsyncCallback\): void Obtains the status of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -268,7 +268,7 @@ Obtains the status of the UDPSocket connection. This API uses an asynchronous ca **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { @@ -293,22 +293,22 @@ getState\(\): Promise Obtains the status of the UDPSocket connection. This API uses a promise to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | -| :----------------------------------------------- | :----------------------------------------- | +| ----------------------------------------------- | ----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { @@ -332,10 +332,10 @@ setExtraOptions\(options: UDPExtraOptions, callback: AsyncCallback\): voi Sets other properties of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -349,7 +349,7 @@ Sets other properties of the UDPSocket connection. This API uses an asynchronous **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}, err=> { if (err) { @@ -380,10 +380,10 @@ setExtraOptions\(options: UDPExtraOptions\): Promise Sets other properties of the UDPSocket connection. This API uses a promise to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -393,15 +393,15 @@ Sets other properties of the UDPSocket connection. This API uses a promise to re | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | options | [UDPExtraOptions](#udpextraoptions) | Yes | Other properties of the UDPSocket connection. For details, see [UDPExtraOptions](#udpextraoptions).| -**Return Value** +**Return value** | Type | Description | -| :-------------- | :--------------------------------------------------- | +| -------------- | --------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); let promise = udp.bind({address:'192.168.xx.xxx', port:xxxx, family:1}); promise.then(() => { @@ -436,12 +436,12 @@ Enables listening for message receiving events of the UDPSocket connection. This | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | -| type | string | Yes | Event type.
**message**: message receiving event| +| type | string | Yes | Type of the event to subscribe to.
**message**: message receiving event| | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.on('message', value => { console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); @@ -455,7 +455,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So Disables listening for message receiving events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -464,18 +464,18 @@ Disables listening for message receiving events of the UDPSocket connection. Thi | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | -| type | string | Yes | Event type.
**message**: message receiving event| +| type | string | Yes | Type of the event to subscribe to.
**message**: message receiving event| | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); let callback = value =>{ console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } udp.on('message', callback); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. udp.off('message', callback); udp.off('message'); ``` @@ -493,12 +493,12 @@ Enables listening for data packet message events or close events of the UDPSocke | Name | Type | Mandatory| Description | | -------- | ---------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type.
- **listening**: data packet message event
- **close**: close event| +| type | string | Yes | Type of the event to subscribe to.

- **listening**: data packet message event
- **close**: close event| | callback | Callback\ | Yes | Callback used to return the result. | **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.on('listening', () => { console.log("on listening success"); @@ -515,7 +515,7 @@ off\(type: 'listening' | 'close', callback?: Callback\): void Disables listening for data packet message events or close events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -524,25 +524,25 @@ Disables listening for data packet message events or close events of the UDPSock | Name | Type | Mandatory| Description | | -------- | ---------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type.
- **listening**: data packet message event
- **close**: close event| +| type | string | Yes | Type of the event to subscribe to.
- **listening**: data packet message event
- **close**: close event| | callback | Callback\ | No | Callback used to return the result. | **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); let callback1 = () =>{ console.log("on listening, success"); } udp.on('listening', callback1); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. udp.off('listening', callback1); udp.off('listening'); let callback2 = () =>{ console.log("on close, success"); } udp.on('close', callback2); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. udp.off('close', callback2); udp.off('close'); ``` @@ -560,13 +560,13 @@ Enables listening for error events of the UDPSocket connection. This API uses an | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------ | -| type | string | Yes | Event type.
**error**: error event| +| type | string | Yes | Type of the event to subscribe to.
**error**: error event| | callback | ErrorCallback | Yes | Callback used to return the result. | **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); udp.on('error', err => { console.log("on error, err:" + JSON.stringify(err)) @@ -580,7 +580,7 @@ off\(type: 'error', callback?: ErrorCallback\): void Disables listening for error events of the UDPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -589,18 +589,18 @@ Disables listening for error events of the UDPSocket connection. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------ | -| type | string | Yes | Event type.
**error**: error event| +| type | string | Yes | Type of the event to subscribe to.
**error**: error event| | callback | ErrorCallback | No | Callback used to return the result. | **Example** -``` +```js let udp = socket.constructUDPSocketInstance(); let callback = err =>{ console.log("on error, err:" + JSON.stringify(err)); } udp.on('error', callback); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. udp.off('error', callback); udp.off('error'); ``` @@ -626,7 +626,7 @@ Defines the parameters for sending data over the UDPSocket connection. | Name | Type | Mandatory| Description | | ------- | ---------------------------------- | ---- | -------------- | -| data | string \| ArrayBuffer7+ | Yes | Data to send. | +| data | string \| ArrayBuffer7+ | Yes | Data to send. | | address | [NetAddress](#netaddress) | Yes | Destination address.| ## UDPExtraOptions @@ -645,7 +645,7 @@ Defines other properties of the UDPSocket connection. ## SocketStateBase -Defines the status of the UDPSocket connection. +Defines the status of the socket connection. **System capability**: SystemCapability.Communication.NetStack @@ -657,7 +657,7 @@ Defines the status of the UDPSocket connection. ## SocketRemoteInfo -Defines information about the UDPSocket connection. +Defines information about the socket connection. **System capability**: SystemCapability.Communication.NetStack @@ -676,15 +676,15 @@ Creates a **TCPSocket** object. **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | - | :--------------------------------- | :---------------------- | + | --------------------------------- | ---------------------- | | [TCPSocket](#tcpsocket) | **TCPSocket** object.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); ``` @@ -699,7 +699,7 @@ bind\(address: NetAddress, callback: AsyncCallback\): void Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -713,7 +713,7 @@ Binds the IP address and port number. The port number can be specified or random **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { if (err) { @@ -731,7 +731,7 @@ bind\(address: NetAddress\): Promise Binds the IP address and port number. The port number can be specified or randomly allocated by the system. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -741,15 +741,15 @@ Binds the IP address and port number. The port number can be specified or random | ------- | ---------------------------------- | ---- | ------------------------------------------------------ | | address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| -**Return Value** +**Return value** | Type | Description | -| :-------------- | :------------------------------------------------------- | +| -------------- | ------------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); promise.then(() => { @@ -766,7 +766,7 @@ connect\(options: TCPConnectOptions, callback: AsyncCallback\): void Sets up a connection to the specified IP address and port number. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -779,7 +779,7 @@ Sets up a connection to the specified IP address and port number. This API uses **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}, err => { if (err) { @@ -797,7 +797,7 @@ connect\(options: TCPConnectOptions\): Promise Sets up a connection to the specified IP address and port number. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -807,15 +807,15 @@ Sets up a connection to the specified IP address and port number. This API uses | ------- | ---------------------------------------- | ---- | ------------------------------------------------------------ | | options | [TCPConnectOptions](#tcpconnectoptions) | Yes | TCPSocket connection parameters. For details, see [TCPConnectOptions](#tcpconnectoptions).| -**Return Value** +**Return value** | Type | Description | -| :-------------- | :--------------------------------------------------------- | +| -------------- | --------------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise.then(() => { @@ -832,10 +832,10 @@ send\(options: TCPSendOptions, callback: AsyncCallback\): void Sends data over a TCPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -848,7 +848,7 @@ Sends data over a TCPSocket connection. This API uses an asynchronous callback t **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise.then(() => { @@ -874,10 +874,10 @@ send\(options: TCPSendOptions\): Promise Sends data over a TCPSocket connection. This API uses a promise to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -887,15 +887,15 @@ Sends data over a TCPSocket connection. This API uses a promise to return the re | ------- | --------------------------------------- | ---- | ------------------------------------------------------------ | | options | [TCPSendOptions](#tcpsendoptions) | Yes | Parameters for sending data over the TCPSocket connection. For details, see [TCPSendOptions](#tcpsendoptions).| -**Return Value** +**Return value** | Type | Description | -| :-------------- | :------------------------------------------------- | +| -------------- | ------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise1.then(() => { @@ -920,7 +920,7 @@ close\(callback: AsyncCallback\): void Closes a TCPSocket connection. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -933,7 +933,7 @@ Closes a TCPSocket connection. This API uses an asynchronous callback to return **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); tcp.close(err => { if (err) { @@ -951,19 +951,19 @@ close\(\): Promise Closes a TCPSocket connection. This API uses a promise to return the result. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | -| :-------------- | :----------------------------------------- | +| -------------- | ----------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.close(); promise.then(() => { @@ -978,12 +978,12 @@ promise.then(() => { getRemoteAddress\(callback: AsyncCallback\): void -Obtains the remote address of a TCPSocket connection. This API uses an asynchronous callback to return the result. +Obtains the remote address of a socket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -995,7 +995,7 @@ Obtains the remote address of a TCPSocket connection. This API uses an asynchron **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise.then(() => { @@ -1017,24 +1017,24 @@ promise.then(() => { getRemoteAddress\(\): Promise -Obtains the remote address of a TCPSocket connection. This API uses a promise to return the result. +Obtains the remote address of a socket connection. This API uses a promise to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | -| :------------------------------------------ | :------------------------------------------ | +| ------------------------------------------ | ------------------------------------------ | | Promise<[NetAddress](#netaddress)> | Promise used to return the result.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise1 = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise1.then(() => { @@ -1057,10 +1057,10 @@ getState\(callback: AsyncCallback\): void Obtains the status of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -1073,7 +1073,7 @@ Obtains the status of the TCPSocket connection. This API uses an asynchronous ca **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise.then(() => { @@ -1097,23 +1097,23 @@ getState\(\): Promise Obtains the status of the TCPSocket connection. This API uses a promise to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack -**Return Value** +**Return value** | Type | Description | -| :----------------------------------------------- | :----------------------------------------- | +| ----------------------------------------------- | ----------------------------------------- | | Promise<[SocketStateBase](#socketstatebase)> | Promise used to return the result.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise.then(() => { @@ -1136,10 +1136,10 @@ setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): voi Sets other properties of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -1152,7 +1152,7 @@ Sets other properties of the TCPSocket connection. This API uses an asynchronous **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise.then(() => { @@ -1185,10 +1185,10 @@ setExtraOptions\(options: TCPExtraOptions\): Promise Sets other properties of the TCPSocket connection. This API uses a promise to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>This API can be called only after [bind](#bind) or [connect](#connect) is successfully called. -**Required permission**: ohos.permission.INTERNET +**Required permissions**: ohos.permission.INTERNET **System capability**: SystemCapability.Communication.NetStack @@ -1198,16 +1198,16 @@ Sets other properties of the TCPSocket connection. This API uses a promise to re | ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | | options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| -**Return Value** +**Return value** | Type | Description | -| :-------------- | :--------------------------------------------------- | +| -------------- | --------------------------------------------------- | | Promise\ | Promise used to return the result.| **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let promise = tcp.connect({ address: {address: '192.168.xx.xxx', port: xxxx, family: 1} , timeout: 6000}); promise.then(() => { @@ -1245,12 +1245,12 @@ Enables listening for message receiving events of the TCPSocket connection. This | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | -| type | string | Yes | Event type.
**message**: message receiving event| +| type | string | Yes | Type of the event to subscribe to.
**message**: message receiving event| | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | Yes | Callback used to return the result. | **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); tcp.on('message', value => { console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo) @@ -1264,7 +1264,7 @@ off\(type: 'message', callback?: Callback<\{message: ArrayBuffer, remoteInfo: So Disables listening for message receiving events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1273,18 +1273,18 @@ Disables listening for message receiving events of the TCPSocket connection. Thi | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ----------------------------------------- | -| type | string | Yes | Event type.
**message**: message receiving event| +| type | string | Yes | Type of the event to subscribe to.
**message**: message receiving event| | callback | Callback<{message: ArrayBuffer, remoteInfo: [SocketRemoteInfo](#socketremoteinfo)}> | No | Callback used to return the result. | **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let callback = value =>{ console.log("on message, message:" + value.message + ", remoteInfo:" + value.remoteInfo); } tcp.on('message', callback); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. tcp.off('message', callback); tcp.off('message'); ``` @@ -1302,13 +1302,13 @@ Enables listening for connection or close events of the TCPSocket connection. Th | Name | Type | Mandatory| Description | | -------- | ---------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type.
- **connect**: connection event
- **close**: close event| +| type | string | Yes | Type of the event to subscribe to.

- **connect**: connection event
- **close**: close event| | callback | Callback\ | Yes | Callback used to return the result. | **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); tcp.on('connect', () => { console.log("on connect success") @@ -1325,7 +1325,7 @@ off\(type: 'connect' | 'close', callback?: Callback\): void Disables listening for connection or close events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1334,25 +1334,25 @@ Disables listening for connection or close events of the TCPSocket connection. T | Name | Type | Mandatory| Description | | -------- | ---------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type.
- **connect**: connection event
- **close**: close event| +| type | string | Yes | Type of the event to subscribe to.

- **connect**: connection event
- **close**: close event| | callback | Callback\ | No | Callback used to return the result. | **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let callback1 = () =>{ console.log("on connect success"); } tcp.on('connect', callback1); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. tcp.off('connect', callback1); tcp.off('connect'); let callback2 = () =>{ console.log("on close success"); } tcp.on('close', callback2); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. tcp.off('close', callback2); tcp.off('close'); ``` @@ -1370,12 +1370,12 @@ Enables listening for error events of the TCPSocket connection. This API uses an | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------ | -| type | string | Yes | Event type.
**error**: error event| +| type | string | Yes | Type of the event to subscribe to.
**error**: error event| | callback | ErrorCallback | Yes | Callback used to return the result. | **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); tcp.on('error', err => { console.log("on error, err:" + JSON.stringify(err)) @@ -1389,7 +1389,7 @@ off\(type: 'error', callback?: ErrorCallback\): void Disables listening for error events of the TCPSocket connection. This API uses an asynchronous callback to return the result. ->![](public_sys-resources/icon-note.gif) **NOTE:** +>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events. **System capability**: SystemCapability.Communication.NetStack @@ -1398,18 +1398,18 @@ Disables listening for error events of the TCPSocket connection. This API uses a | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | ------------------------------------ | -| type | string | Yes | Event type.
**error**: error event| +| type | string | Yes | Type of the event to subscribe to.
**error**: error event| | callback | ErrorCallback | No | Callback used to return the result. | **Example** -``` +```js let tcp = socket.constructTCPSocketInstance(); let callback = err =>{ console.log("on error, err:" + JSON.stringify(err)); } tcp.on('error', callback); -// You can pass the callback of the on function to cancel listening for a certain type of callback. If you do not pass the callback, you will cancel listening for all callbacks. +// You can pass the **callback** of the **on** method to cancel listening for a certain type of callback. If you do not pass the **callback**, you will cancel listening for all callbacks. tcp.off('error', callback); tcp.off('error'); ``` @@ -1434,7 +1434,7 @@ Defines the parameters for sending data over the TCPSocket connection. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| data | string\| ArrayBuffer7+ | Yes | Data to send. | +| data | string\| ArrayBuffer7+ | Yes | Data to send. | | encoding | string | No | Character encoding format. The options are as follows: **UTF-8**, **UTF-16BE**, **UTF-16LE**, **UTF-16**, **US-AECII**, and **ISO-8859-1**. The default value is **UTF-8**.| ## TCPExtraOptions @@ -1453,3 +1453,1080 @@ Defines other properties of the TCPSocket connection. | sendBufferSize | number | No | Size of the send buffer, in bytes. | | reuseAddress | boolean | No | Whether to reuse addresses. The default value is **false**. | | socketTimeout | number | No | Timeout duration of the TCPSocket connection, in ms. | + +## socket.constructTLSSocketInstance9+ + +constructTLSSocketInstance(): TLSSocket + +Creates a **TLSSocket** object. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| --------------------------------- | ---------------------- | +| [TLSSocket](#tlssocket9) | **TLSSocket** object.| + +**Example** + +```js +let tls = socket.constructTLSSocketInstance(); +``` + +## TLSSocket9+ + +Defines a TLSSocket connection. Before invoking TLSSocket APIs, you need to call [socket.constructTLSSocketInstance](#socketconstructtlssocketinstance9) to create a **TLSSocket** object. + +### bind9+ + +bind\(address: NetAddress, callback: AsyncCallback\): void + +Binds the IP address and port number. 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 | +| -------- | ---------------------------------- | ---- | ------------------------------------------------------ | +| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the result of binding the local IP address and port number is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2303198 | Address already in use. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +``` + +### bind9+ + +bind\(address: NetAddress\): Promise + +Binds the IP address and port number. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.INTERNET + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------- | ---- | ------------------------------------------------------ | +| address | [NetAddress](#netaddress) | Yes | Destination address. For details, see [NetAddress](#netaddress).| + +**Return value** + +| Type | Description | +| -------------- | ------------------------------------------------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------- | +| 401 | Parameter error. | +| 201 | Permission denied. | +| 2303198 | Address already in use. | +| 2300002 | System internal error. | + +**Example** + +```js +let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}); +promise.then(() => { + console.log('bind success'); +}).catch(err => { + console.log('bind fail'); +}); +``` + +### getState9+ + +getState\(callback: AsyncCallback\): void + +Obtains the status of the TLSSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------ | ---- | ---------- | +| callback | AsyncCallback\<[SocketStateBase](#socketstatebase)> | Yes | Callback used to return the result. If the operation is successful, the status of the TLSSocket connection is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303188 | Socket operation on non-socket.| +| 2300002 | System internal error. | + +**Example** + +```js +let promise = tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +tls.getState((err, data) => { + if (err) { + console.log('getState fail'); + return; + } + console.log('getState success:' + JSON.stringify(data)); +}); +``` + +### getState9+ + +getState\(\): Promise + +Obtains the status of the TLSSocket connection. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ----------------------------------------- | +| Promise\<[SocketStateBase](#socketstatebase)> | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303188 | Socket operation on non-socket.| +| 2300002 | System internal error. | + +**Example** + +```js +tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +let promise = tls.getState(); +promise.then(() => { + console.log('getState success'); +}).catch(err => { + console.log('getState fail'); +}); +``` + +### setExtraOptions9+ + +setExtraOptions\(options: TCPExtraOptions, callback: AsyncCallback\): void + +Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the result of setting other properties of the TCPSocket connection is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 401 | Parameter error. | +| 2303188 | Socket operation on non-socket.| +| 2300002 | System internal error. | + +**Example** + +```js +tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); + +tls.setExtraOptions({ + keepAlive: true, + OOBInline: true, + TCPNoDelay: true, + socketLinger: { on:true, linger:10 }, + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: true, + socketTimeout: 3000, +},err => { + if (err) { + console.log('setExtraOptions fail'); + return; + } + console.log('setExtraOptions success'); +}); +``` + +### setExtraOptions9+ + +setExtraOptions\(options: TCPExtraOptions\): Promise + +Sets other properties of the TCPSocket connection after successful binding of the local IP address and port number of the TLSSocket connection. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------------------- | ---- | ------------------------------------------------------------ | +| options | [TCPExtraOptions](#tcpextraoptions) | Yes | Other properties of the TCPSocket connection. For details, see [TCPExtraOptions](#tcpextraoptions).| + +**Return value** + +| Type | Description | +| -------------- | --------------------------------------------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 401 | Parameter error. | +| 2303188 | Socket operation on non-socket.| +| 2300002 | System internal error. | + +**Example** + +```js +tls.bind({address: '192.168.xx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +let promise = tls.setExtraOptions({ + keepAlive: true, + OOBInline: true, + TCPNoDelay: true, + socketLinger: { on:true, linger:10 }, + receiveBufferSize: 1000, + sendBufferSize: 1000, + reuseAddress: true, + socketTimeout: 3000, +}); +promise.then(() => { + console.log('setExtraOptions success'); +}).catch(err => { + console.log('setExtraOptions fail'); +}); +``` + +### connect9+ + +connect(options: TLSConnectOptions, callback: AsyncCallback\): void + +Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. 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. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ---------------------------------------| ----| --------------- | +| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the TLSSocket connection.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 401 | Parameter error. | +| 2303104 | Interrupted system call. | +| 2303109 | Bad file number. | +| 2303111 | Resource temporarily unavailable try again. | +| 2303113 | System permission denied. | +| 2303188 | Socket operation on non-socket. | +| 2303191 | Protocol wrong type for socket. | +| 2303198 | Address already in use. | +| 2303199 | Cannot assign requested address. | +| 2303210 | Connection timed out. | +| 2303501 | SSL is null. | +| 2303502 | Error in tls reading. | +| 2303503 | Error in tls writing | +| 2303505 | Error occurred in the tls system call. | +| 2303506 | Error clearing tls connection. | +| 2300002 | System internal error. | + +**Example** + +```js +let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +let options = { + ALPNProtocols: ["spdy/1", "http/1.1"], + address: { + address: "192.168.xx.xxx", + port: xxxx, + family: 1, + }, + secureOptions: { + key: "xxxx", + cert: "xxxx", + ca: ["xxxx"], + passwd: "xxxx", + protocols: [socket.Protocol.TLSv12], + useRemoteCipherPrefer: true, + signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", + cipherSuite: "AES256-SHA256", + }, +}; +tlsTwoWay.connect(options, (err, data) => { + console.error(err); + console.log(data); +}); + +let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication +tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +let oneWayOptions = { + address: { + address: "192.168.xxx.xxx", + port: xxxx, + family: 1, + }, + secureOptions: { + ca: ["xxxx","xxxx"], + cipherSuite: "AES256-SHA256", + }, +}; +tlsOneWay.connect(oneWayOptions, (err, data) => { + console.error(err); + console.log(data); +}); +``` + +### connect9+ + +connect(options: TLSConnectOptions): Promise\ + +Sets up a TLSSocket connection, and creates and initializes a TLS session after successful binding of the local IP address and port number of the TLSSocket connection. During this process, a TLS/SSL handshake is performed between the application and the server to implement data transmission. Both two-way and one-way authentication modes are supported. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | --------------------------------------| ----| --------------- | +| options | [TLSConnectOptions](#tlsconnectoptions9) | Yes | Parameters required for the connection.| + +**Return value** + +| Type | Description | +| ------------------------------------------- | ----------------------------- | +| Promise\ | Promise used to return the result. If the operation is successful, no value is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 401 | Parameter error. | +| 2303104 | Interrupted system call. | +| 2303109 | Bad file number. | +| 2303111 | Resource temporarily unavailable try again. | +| 2303113 | System permission denied. | +| 2303188 | Socket operation on non-socket. | +| 2303191 | Protocol wrong type for socket. | +| 2303198 | Address already in use. | +| 2303199 | Cannot assign requested address. | +| 2303210 | Connection timed out. | +| 2303501 | SSL is null. | +| 2303502 | Error in tls reading. | +| 2303503 | Error in tls writing | +| 2303505 | Error occurred in the tls system call. | +| 2303506 | Error clearing tls connection. | +| 2300002 | System internal error. | + +**Example** + +```js +let tlsTwoWay = socket.constructTLSSocketInstance(); // Two way authentication +tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +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: [socket.Protocol.TLSv12], + useRemoteCipherPrefer: true, + signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", + cipherSuite: "AES256-SHA256", + }, +}; +tlsTwoWay.connect(options).then(data => { + console.log(data); +}).catch(err => { + console.error(err); +}); + +let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication +tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => { + if (err) { + console.log('bind fail'); + return; + } + console.log('bind success'); +}); +let oneWayOptions = { + address: { + address: "192.168.xxx.xxx", + port: xxxx, + family: 1, + }, + secureOptions: { + ca: ["xxxx","xxxx"], + cipherSuite: "AES256-SHA256", + }, +}; +tlsOneWay.connect(oneWayOptions).then(data => { + console.log(data); +}).catch(err => { + console.error(err); +}); +``` + +### getRemoteAddress9+ + +getRemoteAddress\(callback: AsyncCallback\): void + +Obtains the remote address of a TLSSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------- | ---- | ---------- | +| callback | AsyncCallback\<[NetAddress](#netaddress)> | Yes | Callback used to return the result. If the operation is successful, the remote address is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2303188 | Socket operation on non-socket.| +| 2300002 | System internal error. | + +**Example** + +```js +tls.getRemoteAddress((err, data) => { + if (err) { + console.log('getRemoteAddress fail'); + return; + } + console.log('getRemoteAddress success:' + JSON.stringify(data)); +}); +``` + +### getRemoteAddress9+ + +getRemoteAddress\(\): Promise\ + +Obtains the remote address of a TLSSocket connection. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ------------------------------------------ | ------------------------------------------ | +| Promise\<[NetAddress](#netaddress)> | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303188 | Socket operation on non-socket.| +| 2300002 | System internal error. | + +**Example** + +```js +let promise = tls.getRemoteAddress(); +promise.then(() => { + console.log('getRemoteAddress success'); +}).catch(err => { + console.log('getRemoteAddress fail'); +}); +``` + +### getCertificate9+ + +getCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void + +Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation is successful, the local certificate is returned. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2303504 | Error looking up x509. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getCertificate((err, data) => { + if (err) { + console.log("getCertificate callback error = " + err); + } else { + console.log("getCertificate callback = " + data); + } +}); +``` + +### getCertificate9+ + +getCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> + +Obtains the local digital certificate after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2303504 | Error looking up x509. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getCertificate().then(data => { + console.log(data); +}).catch(err => { + console.error(err); +}); +``` + +### getRemoteCertificate9+ + +getRemoteCertificate(callback: AsyncCallback\<[X509CertRawData](#x509certrawdata9)>): void + +Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\<[X509CertRawData](#x509certrawdata9)> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getRemoteCertificate((err, data) => { + if (err) { + console.log("getRemoteCertificate callback error = " + err); + } else { + console.log("getRemoteCertificate callback = " + data); + } +}); +``` + +### getRemoteCertificate9+ + +getRemoteCertificate():Promise\<[X509CertRawData](#x509certrawdata9)> + +Obtains the digital certificate of the server after a TLSSocket connection is established. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\<[X509CertRawData](#x509certrawdata9)> | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getRemoteCertificate().then(data => { + console.log(data); +}).catch(err => { + console.error(err); +}); +``` + +### getProtocol9+ + +getProtocol(callback: AsyncCallback\): void + +Obtains the communication protocol version after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ----------------------------- | +| 2303501 | SSL is null. | +| 2303505 | Error occurred in the tls system call. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getProtocol((err, data) => { + if (err) { + console.log("getProtocol callback error = " + err); + } else { + console.log("getProtocol callback = " + data); + } +}); +``` + +### getProtocol9+ + +getProtocol():Promise\ + +Obtains the communication protocol version after a TLSSocket connection is established. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2303505 | Error occurred in the tls system call. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getProtocol().then(data => { + console.log(data); +}).catch(err => { + console.error(err); +}); +``` + +### getCipherSuite9+ + +getCipherSuite(callback: AsyncCallback\>): void + +Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description| +| -------- | ----------------------------------------| ---- | ---------------| +| callback | AsyncCallback\> | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2303502 | Error in tls reading. | +| 2303505 | Error occurred in the tls system call. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getCipherSuite((err, data) => { + if (err) { + console.log("getCipherSuite callback error = " + err); + } else { + console.log("getCipherSuite callback = " + data); + } +}); +``` + +### getCipherSuite9+ + +getCipherSuite(): Promise\> + +Obtains the cipher suite negotiated by both communication parties after a TLSSocket connection is established. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ---------------------- | --------------------- | +| Promise\> | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2303502 | Error in tls reading. | +| 2303505 | Error occurred in the tls system call. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getCipherSuite().then(data => { + console.log(data); +}).catch(err => { + console.error(err); +}); +``` + +### getSignatureAlgorithms9+ + +getSignatureAlgorithms(callback: AsyncCallback\>): void + +Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------| ---- | ---------------| +| callback | AsyncCallback\> | Yes | Callback used to return the result. | + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getSignatureAlgorithms((err, data) => { + if (err) { + console.log("getSignatureAlgorithms callback error = " + err); + } else { + console.log("getSignatureAlgorithms callback = " + data); + } +}); +``` + +### getSignatureAlgorithms9+ + +getSignatureAlgorithms(): Promise\> + +Obtains the signing algorithm negotiated by both communication parties after a TLSSocket connection is established. This API is applicable to two-way authentication. It uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| ---------------------- | -------------------- | +| Promise\> | Promise used to return the result.| + +**Error codes** + +| ID| Error Message | +| ------- | ------------------------------ | +| 2303501 | SSL is null. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.getSignatureAlgorithms().then(data => { + console.log(data); +}).catch(err => { + console.error(err); +}); +``` + +### send9+ + +send(data: string, callback: AsyncCallback\): void + +Sends a message to the server after a TLSSocket connection is established. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------| ---- | ---------------| +| data | string | Yes | Data content of the message to send. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 401 | Parameter error. | +| 2303501 | SSL is null. | +| 2303503 | Error in tls writing | +| 2303505 | Error occurred in the tls system call. | +| 2303506 | Error clearing tls connection. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.send("xxxx", (err) => { + if (err) { + console.log("send callback error = " + err); + } else { + console.log("send success"); + } +}); +``` + +### send9+ + +send(data: string): Promise\ + +Sends a message to the server after a TLSSocket connection is established. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------| ---- | ---------------| +| data | string | Yes | Data content of the message to send. | + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 401 | Parameter error. | +| 2303501 | SSL is null. | +| 2303503 | Error in tls writing | +| 2303505 | Error occurred in the tls system call. | +| 2303506 | Error clearing tls connection. | +| 2300002 | System internal error. | + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Example** + +```js +tls.send("xxxx").then(() =>{ + console.log("send success"); +}).catch(err => { + console.error(err); +}); +``` + +### close9+ + +close(callback: AsyncCallback\): void + +Closes a TLSSocket connection. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -----------------------------| ---- | ---------------| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 2303501 | SSL is null. | +| 2303505 | Error occurred in the tls system call. | +| 2303506 | Error clearing tls connection. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.close((err) => { + if (err) { + console.log("close callback error = " + err); + } else { + console.log("close success"); + } +}); +``` + +### close9+ + +close(): Promise\ + +Closes a TLSSocket connection. This API uses a promise to return the result. + +**System capability**: SystemCapability.Communication.NetStack + +**Return value** + +| Type | Description | +| -------------- | -------------------- | +| Promise\ | Promise used to return the result. If the operation fails, an error message is returned.| + +**Error codes** + +| ID| Error Message | +| ------- | -------------------------------------------- | +| 2303501 | SSL is null. | +| 2303505 | Error occurred in the tls system call. | +| 2303506 | Error clearing tls connection. | +| 2300002 | System internal error. | + +**Example** + +```js +tls.close().then(() =>{ + console.log("close success"); +}).catch(err => { + console.error(err); +}); +``` + +## TLSConnectOptions9+ + +Defines TLS connection options. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------- | --- |-------------- | +| address | [NetAddress](#netaddress) | Yes | Gateway address. | +| secureOptions | [TLSSecureOptions](#tlssecureoptions9) | Yes| TLS security options.| +| ALPNProtocols | Array\ | Yes| Application Layer Protocol Negotiation (ALPN) protocols. | + +## TLSSecureOptions9+ + +Defines TLS security options. The CA certificate is mandatory, and other parameters are optional. When **cert** (local certificate) and **key** (private key) are not empty, the two-way authentication mode is enabled. If **cert** or **key** is empty, one-way authentication is enabled. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Type | Mandatory| Description | +| --------------------- | ------------------------------------------------------ | --- |----------------------------------- | +| ca | string \| Array\ | Yes| CA certificate of the server, which is used to authenticate the digital certificate of the server.| +| cert | string | No| Digital certificate of the local client. | +| key | string | No| Private key of the local digital certificate. | +| passwd | string | No| Password for reading the private key. | +| protocols | [Protocol](#protocol9) \|Array\<[Protocol](#protocol9)> | No| TLS protocol version. | +| useRemoteCipherPrefer | boolean | No| Whether to use the remote cipher suite preferentially. | +| signatureAlgorithms | string | No| Signing algorithm used during communication. | +| cipherSuite | string | No| Cipher suite used during communication. | + +## Protocol9+ + +Enumerates TLS protocol versions. + +**System capability**: SystemCapability.Communication.NetStack + +| Name | Value | Description | +| --------- | --------- |------------------ | +| TLSv12 | "TLSv1.2" | TLSv1.2.| +| TLSv13 | "TLSv1.3" | TLSv1.3.| + +## X509CertRawData9+ + +Defines the certificate raw data. + +**System capability**: SystemCapability.Communication.NetStack + +| Type | Description | +| --------------------------------------------------------------------- | --------------------- | +|[cryptoFramework.EncodingBlob](js-apis-cryptoFramework.md#datablob) | Data and encoding format of the certificate.| diff --git a/en/application-dev/reference/apis/js-apis-stack.md b/en/application-dev/reference/apis/js-apis-stack.md index 479550783c54d87accf6436cf6556e1b33a12ccc..ff8551cad86f3f4c448e08d267548657305c5c9d 100644 --- a/en/application-dev/reference/apis/js-apis-stack.md +++ b/en/application-dev/reference/apis/js-apis-stack.md @@ -1,7 +1,6 @@ -# Linear Container Stack +# @ohos.util.Stack (Linear Container Stack) > **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. **Stack** is implemented based on the array data structure. It follows the principle Last Out First In (LOFI) and supports data insertion and removal at one end. @@ -19,9 +18,6 @@ This topic uses the following to identify the use of generics: import Stack from '@ohos.util.Stack'; ``` - - - ## Stack ### Attributes @@ -43,7 +39,7 @@ A constructor used to create a **Stack** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -53,11 +49,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let stack = new Stack(); -try { - let stack2 = Stack(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -83,7 +74,7 @@ Adds an element at the top of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -99,11 +90,6 @@ let b = [1, 2, 3]; let result2 = stack.push(b); let c = {name : "Dylon", age : "13"}; let result3 = stack.push(c); -try { - stack.push.bind({}, "b")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### pop @@ -122,7 +108,7 @@ Removes the top element from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -138,11 +124,6 @@ stack.push(5); stack.push(2); stack.push(4); let result = stack.pop(); -try { - stack.pop.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### peek @@ -161,7 +142,7 @@ Obtains the top element of this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -176,11 +157,6 @@ stack.push(4); stack.push(5); stack.push(2); let result = stack.peek(); -try { - stack.peek.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### locate @@ -205,7 +181,7 @@ Obtains the index of the first occurrence of the specified element in this conta **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -220,16 +196,11 @@ stack.push(4); stack.push(5); stack.push(2); let result = stack.locate(2); -try { - stack.locate.bind({}, 2)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value: T, index?: number, stack?: Stack<T>) => void, +forEach(callbackFn: (value: T, index?: number, stack?: Stack<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -240,7 +211,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -253,7 +224,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -270,13 +241,6 @@ stack.push(4); stack.forEach((value, index) => { console.log("value:" + value, index); }); -try { - stack.forEach.bind({}, (value, index) => { - console.log("value:" + value, index); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### isEmpty @@ -295,7 +259,7 @@ Checks whether this container is empty (contains no elements). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -310,11 +274,6 @@ stack.push(4); stack.push(5); stack.push(4); let result = stack.isEmpty(); -try { - stack.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### [Symbol.iterator] @@ -333,7 +292,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -359,9 +318,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - stack[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-stationary.md b/en/application-dev/reference/apis/js-apis-stationary.md new file mode 100644 index 0000000000000000000000000000000000000000..ceae25ac4c711e8dd3664520290fda7b897c9ae9 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-stationary.md @@ -0,0 +1,130 @@ +# @ohos.stationary (Device Status Awareness Framework) + +The **stationary** module provides APIs to report the device status, including absolute still and relative still. + +> **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 stationary from '@ohos.stationary' +``` + +## ActivityResponse + +Defines the response interface to receive the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +### Attributes + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| state | [ActivityState](#activitystate) | Yes| No| New device status.| + +## ActivityType + +Enumerates the device status types. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name| Description| +| -------- | -------- | +| still | Absolutely still.| +| relativeStill | Relatively still.| + +## ActivityEvent + +Enumerates the device status events. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Event indicating entering device status. | +| EXIT | 2 | Event indicating exiting device status.| +| ENTER_EXIT | 3 | Event indicating entering and exiting device status.| + +## ActivityState + +Enumerates the device statuses. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +| Name | Value | Description | +| ------------------------------ | ---- | ---------------------------------------- | +| ENTER | 1 | Entering device status. | +| EXIT | 2 | Exiting device status.| + +## stationary.on('still' | 'relativeStill') + +on(activity: ActivityType, event: ActivityEvent, reportLatencyNs: number, callback: Callback<ActivityResponse>): void + +Subscribes to the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| event | [ActivityEvent](#activityevent) | Yes | Event type. | +| reportLatencyNs | number | Yes | Event reporting period. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | Yes | Callback used to receive reported data. | + +**Example** + +```js +var reportLatencyNs = 100; +stationary.on('still', stationary.ActivityEvent.ENTER, reportLatencyNs, (data) => { + console.log('data='+ JSON.stringify(data)); +}) +``` + +## stationary.once('still' | 'relativeStill') + +once(activity: ActivityType, callback: Callback<ActivityResponse>): void + +Obtains the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | Yes | Callback used to receive reported data. | + +**Example** + +```js +stationary.once('still', (data) => { + console.log("data="+ JSON.stringify(data)); +}) +``` + +## stationary.off('still' | 'relativeStill') + +off(activity: ActivityType, event: ActivityEvent, callback?: Callback<ActivityResponse>): void + +Unsubscribes from the device status. + +**System capability**: SystemCapability.Msdp.DeviceStatus.Stationary + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------------- | -------------------------------------------------- | ---- | ---------------------------- | +| activity | [ActivityType](#activitytype) | Yes | Device status type. | +| event | [ActivityEvent](#activityevent) | Yes | Event type. | +| callback | Callback<[ActivityResponse](#activityresponse)\> | No | Callback used to receive reported data. | + +**Example** + +```js +stationary.off('still', stationary.ActivityEvent.ENTER); +``` 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 d646fd424d8f7fa6c431a388879e9cf63678a632..c54d9d4b01fec93df43f92f47eab8aaae951fb4e 100644 --- a/en/application-dev/reference/apis/js-apis-storage-statistics.md +++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md @@ -1,11 +1,10 @@ -# App Storage Statistics +# @ohos.storageStatistics (App Storage Statistics) The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data. -> **NOTE**
+> **NOTE** > -> - The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> - API version 9 is a canary version for trial use. The APIs of this version may be unstable. +> 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 diff --git a/en/application-dev/reference/apis/js-apis-system-app.md b/en/application-dev/reference/apis/js-apis-system-app.md index e0cf8d10a1e79872dc6d59a908281610fd01ba23..b48e4a8f6233b11ffdef0361280dba6322c9f959 100644 --- a/en/application-dev/reference/apis/js-apis-system-app.md +++ b/en/application-dev/reference/apis/js-apis-system-app.md @@ -1,6 +1,6 @@ -# Application Context +# @system.app (Application Context) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** > - The APIs of this module are no longer maintained since API version 7. You are advised to use the new APIs. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -9,8 +9,8 @@ ## Modules to Import -``` -import app from '@system.app'; +```ts +import app from '@system.app' ``` @@ -20,7 +20,9 @@ getInfo(): AppResponse Obtains the declared information in the **config.json** file of an application. -> **Note: ** [`@ohos.bundle`](js-apis-Bundle.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.bundle](js-apis-Bundle.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Lite @@ -32,13 +34,13 @@ Obtains the declared information in the **config.json** file of an application. **Example** - ``` - export default { - getInfo(){ - var info = app.getInfo(); - console.log(JSON.stringify(info)); - } + ```ts +export default { + getInfo() { + let info = app.getInfo() + console.log(JSON.stringify(info)) } +} ``` ## app.terminate @@ -47,17 +49,20 @@ terminate(): void Terminates the current ability. -> **Note: ** [`@ohos.ability.featureAbility`](js-apis-featureAbility.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.ability.featureAbility](js-apis-ability-featureAbility.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Lite **Example** - ``` - export default { - terminate(){ - app.terminate(); - }} + ```ts +export default { + terminate() { + app.terminate() + } +} ``` ## app.requestFullWindow @@ -67,7 +72,9 @@ Requests the application to run in full window. You can call this API when the F This is a system API and cannot be called by third-party applications. -> **Note: ** [`@ohos.window`](js-apis-window.md) is recommended from API version 7. +> **NOTE** +> +> You are advised to use [@ohos.window](js-apis-window.md) since API version 7. **System capability**: SystemCapability.ArkUI.ArkUI.Full @@ -78,13 +85,14 @@ This is a system API and cannot be called by third-party applications. **Example** - ``` - export default { - requestFullWindow(){ - app.requestFullWindow({ - duration: 200}); - } + ```ts +export default { + requestFullWindow() { + app.requestFullWindow({ + duration: 200 + }) } +} ``` ## app.setImageCacheCount7+ @@ -102,19 +110,19 @@ Sets the maximum number of decoded images that can be cached in the memory to sp **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageCacheCount(100) // Set the maximum number of decoded images that can be cached in the memory to 100. + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## app.setImageRawDataCacheSize7+ @@ -132,20 +140,20 @@ Sets the maximum size (in bytes) of the image data cached in the memory before d **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageRawDataCacheSize(104857600) - // Set the upper limit of the memory for caching image data before decoding to 100 MB. (100 x 1024 x 1024 B =104857600 B = 100 MB). - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageRawDataCacheSize(104857600) + // Set the upper limit of the memory for caching image data before decoding to 100 MB. (100 x 1024 x 1024 B =104857600 B = 100 MB). + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## app.setImageFileCacheSize7+ @@ -163,20 +171,20 @@ Sets the maximum size of the image file cache (in bytes) to speed up the loading **Example** - ``` - // app.ets - import app from '@system.app'; - - export default { - onCreate() { - app.setImageFileCacheSize(209715200) - // Set the upper limit of the image file cache to 200 MB. (200 x 1024 x 1024 B= 209715200 B = 200 MB). - console.info('Application onCreate') - }, - onDestroy() { - console.info('Application onDestroy') - }, - } + ```ts +// app.ets +import app from '@system.app' + +export default { + onCreate() { + app.setImageFileCacheSize(209715200) + // Set the upper limit of the image file cache to 200 MB. (200 x 1024 x 1024 B= 209715200 B = 200 MB). + console.info('Application onCreate') + }, + onDestroy() { + console.info('Application onDestroy') + }, +} ``` ## AppResponse @@ -213,4 +221,4 @@ Defines the options of the **RequestFullWindow** API. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| duration | number | Yes| Number of animation options.| +| duration | number | Yes| Duration of an animation, in milliseconds.| diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md index 7b577c8ee81c733cdb1aa1f2ccfcced87829f304..d673a500027654075ff330c916cd22add25abaf6 100644 --- a/en/application-dev/reference/apis/js-apis-system-battery.md +++ b/en/application-dev/reference/apis/js-apis-system-battery.md @@ -1,9 +1,10 @@ -# Battery Level +# @system.battery (Battery Information) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. -> -> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **battery** module allows you to query the charging status and remaining power of a device. + +> **NOTE** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead. +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -16,40 +17,46 @@ import battery from '@system.battery'; ## battery.getStatus -getStatus(Object): void +getStatus(options?: GetStatusOptions): void; Obtains the current charging state and battery level. **System capability**: SystemCapability.PowerManager.BatteryManager.Core -**Parameter** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the check result is obtained | -| fail | Function | No | Called when the check result fails to be obtained | -| complete | Function | No | Called when the execution is complete | - -The following value will be returned when the check result is obtained. - -| Name | Type | Description | -| -------- | -------- | -------- | -| charging | boolean | Whether the battery is being charged | -| level | number | Current battery level, which ranges from 0.00 to 1.00. | +| options | [GetStatusOptions](#getstatusoptions) | No| Object that contains the API calling result.| **Example** ```js -export default { - getStatus() { - battery.getStatus({ - success: function(data) { - console.log('success get battery level:' + data.level); - }, - fail: function(data, code) { - console.log('fail to get battery level code:' + code + ', data: ' + data); - }, - }); - }, -} -``` \ No newline at end of file +battery.getStatus({ + success: function(data) { + console.log('success get battery level:' + data.level); + }, + fail: function(data, code) { + console.error('fail to get battery level code:' + code + ', data: ' + data); + } +}); +``` + +## GetStatusOptions + +Object that contains the API calling result. + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BatteryResponse](#batteryresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BatteryResponse](#batteryresponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## BatteryResponse + +Defines a response that returns the charging status and remaining power of the device. + +| Name| Type| Description| +| -------- | -------- | -------- | +| charging | boolean | Whether the battery is being charged.| +| level | number | Current battery level, which ranges from **0.00** to **1.00**.| diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md index 71e9b7072d03d8c25297cfd2c8f3c97c295097eb..939e7d7021bc8f93ad7359004de58f525feeee05 100644 --- a/en/application-dev/reference/apis/js-apis-system-brightness.md +++ b/en/application-dev/reference/apis/js-apis-system-brightness.md @@ -1,8 +1,9 @@ -# Screen Brightness +# @system.brightness (Screen Brightness) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +The **brightness** module provides APIs for querying and adjusting the screen brightness and mode. + +> **NOTE** > - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead. -> > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -16,7 +17,7 @@ import brightness from '@system.brightness'; ## brightness.getValue -getValue(Object): void +getValue(options?: GetBrightnessOptions): void Obtains the current screen brightness. @@ -24,39 +25,27 @@ Obtains the current screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete | - -The following values will be returned when the operation is successful. - -| Name | Type | Description | -| -------- | -------- | -------- | -| value | number | Screen brightness, which ranges from 1 to 255. | +| options | [GetBrightnessOptions](#getbrightnessoptions) | No | Options for obtaining the screen brightness.| **Example** -```js -export default { - getValue() { - brightness.getValue({ - success: function(data){ - console.log('success get brightness value:' + data.value); - }, - fail: function(data, code) { - console.log('get brightness fail, code: ' + code + ', data: ' + data); + ```js + brightness.getValue({ + success: function(data) { + console.log('success get brightness value:' + data.value); }, - }); - }, -} -``` + fail: function(data, code) { + console.error('get brightness fail, code: ' + code + ', data: ' + data); + } + }); + ``` ## brightness.setValue -setValue(Object): void +etValue(options?: SetBrightnessOptions): void Sets the screen brightness. @@ -64,35 +53,28 @@ Sets the screen brightness. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | number | Yes | Screen brightness. The value is an integer ranging from 1 to 255.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used. | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetBrightnessOptions](#setbrightnessoptions) | No | Options for setting the screen brightness.| **Example** -```js -export default { - setValue() { - brightness.setValue({ - value: 100, - success: function(){ - console.log('handling set brightness success.'); - }, - fail: function(data, code){ - console.log('handling set brightness value fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` + ```js + brightness.setValue({ + value: 100, + success: function() { + console.log('handling set brightness success.'); + }, + fail: function(data, code) { + console.error('handling set brightness value fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.getMode -getMode(Object): void +getMode(options?: GetBrightnessModeOptions: void Obtains the screen brightness adjustment mode. @@ -100,75 +82,57 @@ Obtains the screen brightness adjustment mode. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete | - -The following values will be returned when the operation is successful. - -| Name | Type | Description | -| -------- | -------- | -------- | -| mode | number | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | +| options | [GetBrightnessModeOptions](#getbrightnessmodeoptions) | No| Options for obtaining the screen brightness mode.| **Example** -```js -export default { - getMode() { - brightness.getMode({ - success: function(data){ - console.log('success get mode:' + data.mode); - }, - fail: function(data, code){ - console.log('handling get mode fail, code:' + code + ', data: ' + data); + ```js + brightness.getMode({ + success: function(data) { + console.log('success get mode:' + data.mode); }, - }); - }, -} -``` + fail: function(data, code){ + console.error('handling get mode fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.setMode -setMode(Object): void +setMode(options?: SetBrightnessModeOptions): void Sets the screen brightness adjustment mode. **System capability**: SystemCapability.PowerManager.DisplayPowerManager **Parameters** - -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mode | number | Yes | The value can be **0** or **1**.
- **0**: The screen brightness is manually adjusted.
- **1**: The screen brightness is automatically adjusted. | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetBrightnessModeOptions](#setbrightnessmodeoptions) | No | Options for setting the screen brightness mode.| **Example** -```js -export default { - setMode() { - brightness.setMode({ - mode: 1, - success: function(){ - console.log('handling set mode success.'); - }, - fail: function(data, code){ - console.log('handling set mode fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` + ```js + brightness.setMode({ + mode: 1, + success: function() { + console.log('handling set mode success.'); + }, + fail: function(data, code) { + console.error('handling set mode fail, code:' + code + ', data: ' + data); + } + }); + ``` ## brightness.setKeepScreenOn -setKeepScreenOn(Object): void +setKeepScreenOn(options?: SetKeepScreenOnOptions): void + +>This API is no longer maintained since API version 7. It is recommended that you use [window.setKeepScreenOn](js-apis-window.md#setkeepscreenon) instead. Sets whether to always keep the screen on. Call this API in **onShow()**. @@ -176,27 +140,88 @@ Sets whether to always keep the screen on. Call this API in **onShow()**. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| keepScreenOn | boolean | Yes | Whether to always keep the screen on | -| success | Function | No | Called when the execution is successful. | -| fail | Function | No | Called when the operation fails. | -| complete | Function | No | Called when the execution is complete. | +| options | [SetKeepScreenOnOptions](#setkeepscreenonoptions) | No| Options for setting the screen to be steady on.| **Example** -```js -export default { - setKeepScreenOn() { - brightness.setKeepScreenOn({ - keepScreenOn: true, - success: function () { - console.log('handling set keep screen on success.') - }, - fail: function (data, code) { - console.log('handling set keep screen on fail, code:' + code + ', data: ' + data); - }, - }); - }, -} -``` \ No newline at end of file + ```js + brightness.setKeepScreenOn({ + keepScreenOn: true, + success: function () { + console.log('handling set keep screen on success.'); + }, + fail: function (data, code) { + console.error('handling set keep screen on fail, code:' + code + ', data: ' + data); + } + }); + ``` +## GetBrightnessOptions + +Defines the options for obtaining the screen brightness. + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessResponse](#brightnessresponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessResponse](#brightnessresponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## SetBrightnessOptions + +Defines the options for setting the screen brightness. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| value | number | Yes | Screen brightness. The value is an integer ranging from **1** to **255**.
- If the value is less than or equal to **0**, value **1** will be used.
- If the value is greater than **255**, value **255** will be used.
- If the value contains decimals, the integral part of the value will be used. For example, if value **8.1** is set, value **8** will be used.| +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## BrightnessResponse + +Defines a response that returns the screen brightness. + +| Parameter| Type | Description| +| -------- | -------- | -------- | +| value | number | Screen brightness. The value ranges from 1 to 255.| + +## GetBrightnessModeOptions + +Defines the options for obtaining the screen brightness mode. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | +| success | (data: [BrightnessModeResponse](#brightnessmoderesponse)) => void | No | Called when API call is successful. **data** is a return value of the [BrightnessModeResponse](#brightnessmoderesponse) type.| +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code. | +| complete | () => void | No | Called when API call is complete. | + +## SetBrightnessModeOptions + +Defines the options for setting the screen brightness mode. + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ------------------------------------------------------ | +| mode | number | Yes | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| +| complete | () => void | No | Called when API call is complete. | + +## BrightnessModeResponse + +Defines a response that returns the screen brightness mode. + +| Name| Type | Description| +| -------- | -------- | -------- | +| mode | number | The value **0** indicates the manual adjustment mode, and the value **1** indicates the automatic adjustment mode.| + +## SetKeepScreenOnOptions + +Defines the options for setting the screen to be steady on. + +| Name | Type | Mandatory| Description | +| ------------ | ------------------------------------ | ---- | ------------------------------------------------------ | +| keepScreenOn | boolean | Yes | The value **true** means to keep the screen steady on, and the value **false** indicates the opposite. | +| success | () => void | No | Called when API call is successful. | +| fail | (data: string, code: number) => void | No | Called when API call has failed. **data** indicates the error information, and **code** indicates the error code.| +| complete | () => void | No | Called when API call is complete. | diff --git a/en/application-dev/reference/apis/js-apis-system-capability.md b/en/application-dev/reference/apis/js-apis-system-capability.md new file mode 100644 index 0000000000000000000000000000000000000000..7949bae9880af5a8e428e62440595a4a6e990da7 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-capability.md @@ -0,0 +1,79 @@ +# @ohos.systemCapability (SystemCapability) + +System capability (SysCap) refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. This module provides APIs for querying the set of system capabilities. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. + + +## Modules to Import + +```ts +import systemcapability from '@ohos.systemCapability' +``` + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(callback: AsyncCallback): void; + +Queries system capabilities. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Developtools.Syscap + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback | Yes| Callback invoked to return the result.| + + +**Example** + +```ts +try { + systemcapability.querySystemCapabilities(function (err, data) { + if (err == undefined) { + console.log("get system capabilities:" + data) + } else { + console.log(" get system capabilities err:" + err.code) + }}); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +## systemcapability.querySystemCapabilities + +querySystemCapabilities(): Promise<string> + +Queries system capabilities. This API uses a promise to return the result. + +**System capability**: SystemCapability.Startup.SystemInfo + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<string> | Promise used to return the result.| + +**Example** + +```ts +try { + var p = systemcapability.querySystemCapabilities(); + p.then(function (value) { + console.log("get system capabilities: " + value); + }).catch(function (err) { + console.log("get system capabilities error: " + err.code); + }); +}catch(e){ + console.log("get unexpected error: " + e); +} +``` + + +> **NOTE** +> - The system capabilities returned by the preceding APIs are in the form of an encoded numeric string. 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 6812d87828d55851d375eadba9dab6b2de55560a..dddb6a685f00a8a5a1829e489d43af4a198bdffa 100644 --- a/en/application-dev/reference/apis/js-apis-system-cipher.md +++ b/en/application-dev/reference/apis/js-apis-system-cipher.md @@ -1,6 +1,6 @@ -# Encryption Algorithm +# @system.cipher (Cipher Algorithm) -> **NOTE**
+> **NOTE** > > The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -31,7 +31,7 @@ Defines the input parameters of **cipher.rsa()**. | 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.| +| 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. | diff --git a/en/application-dev/reference/apis/js-apis-system-date-time.md b/en/application-dev/reference/apis/js-apis-system-date-time.md new file mode 100644 index 0000000000000000000000000000000000000000..90c915b32ee35f9d09f6fe0453c962b985f914f1 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-date-time.md @@ -0,0 +1,665 @@ +# @ohos.systemDateTime + +The **systemDateTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import systemDateTime from '@ohos.systemDateTime'; +``` + +## systemDateTime.setTime + +setTime(time : number, callback : AsyncCallback<void>) : void + +Sets the system time. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ---------------- | +| time | number | Yes | Timestamp to set, in milliseconds. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +// Set the system time to 2021-01-20 02:36:25. +let time = 1611081385000; +try { + systemDateTime.setTime(time, (error) => { + if (error) { + console.info(`Failed to set time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting time`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setTime + +setTime(time : number) : Promise<void> + +Sets the system time. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| time | number | Yes | Timestamp to set, in milliseconds.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +// Set the system time to 2021-01-20 02:36:25. +let time = 1611081385000; +try { + systemDateTime.setTime(time).then(() => { + console.info(`Succeeded in setting time.`); + }).catch((error) => { + console.info(`Failed to set time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void + +Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | ------------------ | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | + +**Example** + +```js +try { + systemDateTime.getCurrentTime(true, (error, time) => { + if (error) { + console.info(`Failed to get currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------- | ---- | ---------------------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time elapsed since the Unix epoch. | + +**Example** + +```js +try { + systemDateTime.getCurrentTime((error, time) => { + if (error) { + console.info(`Failed to get currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getCurrentTime + +getCurrentTime(isNano?: boolean): Promise<number> + +Obtains the time elapsed since the Unix epoch. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| --------------------- | --------------------------- | +| Promise<number> | Promise used to return the time elapsed since the Unix epoch.| + +**Example** + +```js +try { + systemDateTime.getCurrentTime().then((time) => { + console.info(`Succeeded in getting currentTime : ${time}`); + }).catch((error) => { + console.info(`Failed to get currentTime. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------- | ---- | -------------------------- | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime(true, (error, time) => { + if (error) { + console.info(`Failed to get real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +getRealActiveTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | --------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime((error, time) => { + if (error) { + console.info(`Failed to get real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealActiveTime + +getRealActiveTime(isNano?: boolean): Promise<number> + +Obtains the time elapsed since system startup, excluding the deep sleep time. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| -------------- | -------------------------------- | +| Promise<number> | Promise used to return the time elapsed since system startup, excluding the deep sleep time.| + +**Example** + +```js +try { + systemDateTime.getRealActiveTime().then((time) => { + console.info(`Succeeded in getting real active time : ${time}`); + }).catch((error) => { + console.info(`Failed to get real active time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealTime + +getRealTime(isNano: boolean, callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, including the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------- | ---- | ------------------------------- | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + +```js +try { + systemDateTime.getRealTime(true, (error, time) => { + if (error) { + console.info(`Failed to get real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealTime + +getRealTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since system startup, including the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------- | ---- | --------------------------- | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + +```js +try { + systemDateTime.getRealTime((error, time) => { + if (error) { + console.info(`Failed to get real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getRealTime + +getRealTime(isNano?: boolean): Promise<number> + +Obtains the time elapsed since system startup, including the deep sleep time. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------- | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: The time to return is in nanoseconds.
- **false**: The time to return is in milliseconds.| + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------- | +| Promise<number> | Promise used to return the time elapsed since system startup, including the deep sleep time.| + +**Example** + +```js +try { + systemDateTime.getRealTime().then((time) => { + console.info(`Succeeded in getting real time : ${time}`); + }).catch((error) => { + console.info(`Failed to get real time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setDate + +setDate(date: Date, callback: AsyncCallback<void>): void + +Sets the system date. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | --------------------- | +| date | Date | Yes | Target date to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +let date = new Date(); +try { + systemDateTime.setDate(date, (error) => { + if (error) { + console.info(`Failed to set date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting date.`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setDate + +setDate(date: Date): Promise<void> + +Sets the system date. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------- | +| date | Date | Yes | Target date to set.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +let date = new Date(); +try { + systemDateTime.setDate(date).then(() => { + console.info(`Succeeded in setting date.`); + }).catch((error) => { + console.info(`Failed to set date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getDate + +getDate(callback: AsyncCallback<Date>): void + +Obtains the current system date. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------- | ---- | --------------------- | +| callback | AsyncCallback<Date> | Yes | Callback used to return the current system date.| + +**Example** + +```js +try { + systemDateTime.getDate((error, date) => { + if (error) { + console.info(`Failed to get date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting date : ${date}`);; + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getDate + +getDate(): Promise<Date> + +Obtains the current system date. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------------------- | +| Promise<Date> | Promise used to return the current system date.| + +**Example** + +```js +try { + systemDateTime.getDate().then((date) => { + console.info(`Succeeded in getting date : ${date}`); + }).catch((error) => { + console.info(`Failed to get date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setTimezone + +setTimezone(timezone: string, callback: AsyncCallback<void>): void + +Sets the system time zone. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | -------------------------- | +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones). | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** + +```js +try { + systemDateTime.setTimezone('Asia/Shanghai', (error) => { + if (error) { + console.info(`Failed to set timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting timezone.`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.setTimezone + +setTimezone(timezone: string): Promise<void> + +Sets the system time zone. This API uses a promise to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Return value** + +| Type | Description | +| ------------------- | -------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +try { + systemDateTime.setTimezone('Asia/Shanghai').then(() => { + console.info(`Succeeded in setting timezone.`); + }).catch((error) => { + console.info(`Failed to set timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getTimezone + +getTimezone(callback: AsyncCallback<string>): void + +Obtains the system time zone. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------- | ---- | ------------------------ | +| callback | AsyncCallback<string> | Yes | Callback used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Example** + +```js +try { + systemDateTime.getTimezone((error, data) => { + if (error) { + console.info(`Failed to get timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in get timezone : ${data}`);; + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} +``` + +## systemDateTime.getTimezone + +getTimezone(): Promise<string> + +Obtains the system time zone. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------- | +| Promise<string> | Promise used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| + +**Example** + +```js +try { + systemDateTime.getTimezone().then((data) => { + console.info(`Succeeded in getting timezone: ${data}`); + }).catch((error) => { + console.info(`Failed to get timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} +``` + +## Supported System Time Zones + +The following table lists the supported system time zones and the respective offset (unit: h) between each time zone and time zone 0. + +| Time Zone | Offset | +| ------------------------------ | --------------------- | +| Antarctica/McMurdo | 12 | +| America/Argentina/Buenos_Aires | -3 | +| Australia/Sydney | 10 | +| America/Noronha | -2 | +| America/St_Johns | -3 | +| Africa/Kinshasa | 1 | +| America/Santiago | -3 | +| Asia/Shanghai | 8 | +| Asia/Nicosia | 3 | +| Europe/Berlin | 2 | +| America/Guayaquil | -5 | +| Europe/Madrid | 2 | +| Pacific/Pohnpei | 11 | +| America/Godthab | -2 | +| Asia/Jakarta | 7 | +| Pacific/Tarawa | 12 | +| Asia/Almaty | 6 | +| Pacific/Majuro | 12 | +| Asia/Ulaanbaatar | 8 | +| America/Mexico_City | -5 | +| Asia/Kuala_Lumpur | 8 | +| Pacific/Auckland | 12 | +| Pacific/Tahiti | -10 | +| Pacific/Port_Moresby | 10 | +| Asia/Gaza | 3 | +| Europe/Lisbon | 1 | +| Europe/Moscow | 3 | +| Europe/Kiev | 3 | +| Pacific/Wake | 12 | +| America/New_York | -4 | +| Asia/Tashkent | 5 | diff --git a/en/application-dev/reference/apis/js-apis-system-device.md b/en/application-dev/reference/apis/js-apis-system-device.md index c5b92831958ea79cb7b868fbf549974cdf39a669..6da9ae481fe8ef4aeb440090f478fb1069596882 100644 --- a/en/application-dev/reference/apis/js-apis-system-device.md +++ b/en/application-dev/reference/apis/js-apis-system-device.md @@ -1,61 +1,61 @@ -# Device Information +# @system.device -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.deviceInfo`](js-apis-device-info.md) instead. +The **device** module provides APIs for checking information about the current device. + +> **NOTE** +> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [@ohos.deviceInfo](js-apis-device-info.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import - ``` import device from '@system.device'; ``` - ## device.getInfo getInfo(Object): void Obtains the device information. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE** +> > Do not call **device.getInfo** before the **onShow** event of the home page. -**System capability**: SystemCapability.Startup.SysInfo +**System capability**: SystemCapability.Startup.SystemInfo **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| success | Function | No | Called when the device information is obtained | -| fail | Function | No | Called when the device information fails to be obtained | -| complete | Function | No | Called when the execution is complete | +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| -The following values will be returned when the device information is obtained. +**Return value of success()** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| brand | string | Brand | -| manufacturer | string | Manufacturer | -| model | string | Model | -| product | string | Product number | -| language4+ | string | System language | -| region4+ | string | System region | -| windowWidth | number | Window width | -| windowHeight | number | Window height | -| screenDensity4+ | number | Screen density | -| screenShape4+ | string | Screen shape. The options are as follows:
- rect: rectangle screen
- circle: circle screen | -| apiVersion4+ | number | API version | -| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions. | -| deviceType4+ | string | Device type | - -The following error code will be returned if the device information fails to be obtained. - -| Error Code | Description | +| brand | string | Brand.| +| manufacturer | string | Manufacturer.| +| model | string | Model. | +| product | string | Product number.| +| language4+ | string | System language.| +| region4+ | string | System region.| +| windowWidth | number | Window width.| +| windowHeight | number | Window height.| +| screenDensity4+ | number | Screen density.| +| screenShape4+ | string | Screen shape. The options are as follows:
- **rect**: rectangle screen
- **circle**: circle screen| +| apiVersion4+ | number | API version.| +| releaseType4+ | string | Release type. The value includes both the release type and the API version, for example, Beta1.
Available release types are as follows:
- **Canary**: For the same API version, different canary releases are compatible with each other, but not compatible with those of the **beta** and **release** type.
- **Beta**: For the same API version, different beta releases are compatible with each other, but not compatible with those of the **release** type.
- **Release**: Releases of this type are compatible with the latest five API versions.| +| deviceType4+ | string | Device type.| + +**Return value of fail()** + +| Error Code| Description| | -------- | -------- | -| 200 | The returned result contains information that cannot be obtained. | +| 200 | The returned result contains information that cannot be obtained.| **Example** @@ -72,4 +72,4 @@ export default { }); }, } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-location.md b/en/application-dev/reference/apis/js-apis-system-location.md index ab53fb2d188b7b929c591a67c33cec12984e063c..fd4fba8512b1cdecae82339ef31a4b293f022aef 100644 --- a/en/application-dev/reference/apis/js-apis-system-location.md +++ b/en/application-dev/reference/apis/js-apis-system-location.md @@ -1,8 +1,7 @@ # Geographic Location -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.geolocation`](js-apis-geolocation.md) instead. -> +> **NOTE** +> - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.geolocation`](js-apis-geolocation.md). > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -31,7 +30,7 @@ Obtains the geographic location. | Parameter | Type | Mandatory | Description | | -------- | -------- | -------- | -------- | -| timeout | number | No | Timeout duration, in milliseconds. The default value is **30000**.
The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.
The value is a 32-digit positive integer. If the value set is less than or equal to **0**, the default value will be used. | +| timeout | number | No | Timeout duration, in milliseconds. The default value is **30000**.
The timeout duration is necessary in case the request to obtain the geographic location is rejected for the lack of the required permission, weak positioning signal, or incorrect location settings. After the timeout duration expires, the fail function will be called.
The value is a 32-digit positive integer. If the value set is less than or equal to **0**, the default value will be used. | | coordType | string | No | Coordinate system type. Available types can be obtained by **getSupportedCoordTypes**. The default type is **wgs84**. | | success | Function | No | Called when the operation is successful. | | fail | Function | No | Called when the operation fails. | @@ -208,4 +207,4 @@ export default { var types = geolocation.getSupportedCoordTypes(); }, } -``` \ No newline at end of file +``` diff --git a/en/application-dev/reference/apis/js-apis-system-notification.md b/en/application-dev/reference/apis/js-apis-system-notification.md index 0a46cec929810e8f485a66b26445f1e3042b7672..608bb4d3d3ee2ec6d4c48e7d9b7a4abd01e52c2e 100644 --- a/en/application-dev/reference/apis/js-apis-system-notification.md +++ b/en/application-dev/reference/apis/js-apis-system-notification.md @@ -1,7 +1,6 @@ -# Notification +# @system.notification > **NOTE** -> > - The APIs of this module are no longer maintained since API version 7. You are advised to use [`@ohos.notification`](js-apis-notification.md). > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -18,22 +17,22 @@ import notification from '@system.notification'; **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| ----------- | --- | ---- | ---------------------------------------------- | ---- | ------------------------- | -| bundleName | Yes | Yes | string | Yes | Name of the application bundle to which the notification will be redirected after being clicked. | -| abilityName | Yes | Yes | string | Yes | Name of the application ability to which the notification will be redirected after being clicked.| -| uri | Yes | Yes | string | No | URI of the page to be redirected to. | +| Name | Type | Readable | Writable | Mandatory| Description | +| ----------- | ---------------------------------------------- | ---- | ------------------------- | ------------------------- | ------------------------- | +| bundleName | string | Yes | Yes | Yes | Name of the application bundle to which the notification will be redirected after being clicked. | +| abilityName | string | Yes | Yes | Yes | Name of the application ability to which the notification will be redirected after being clicked.| +| uri | string | Yes | Yes | No | URI of the page to be redirected to. | ## ShowNotificationOptions **System capability**: SystemCapability.Notification.Notification -| Name | Readable| Writable| Type | Mandatory| Description | -| ------------- | --- | ---- | ---------------------------------------------- | ---- | ------------------------- | -| contentTitle | Yes | Yes | string | No | Notification title. | -| contentText | Yes | Yes | string | No | Notification content. | -| clickAction | Yes | Yes | ActionResult | No | Action triggered when the notification is clicked. | +| Name | Type | Readable | Writable | Mandatory| Description | +| ------------- | ---------------------------------------------- | ---- | ------------------------- | ------------------------- | ------------------------- | +| contentTitle | string | Yes | Yes | No | Notification title. | +| contentText | string | Yes | Yes | No | Notification content. | +| clickAction | ActionResult | Yes | Yes | No | Action triggered when the notification is clicked. | ## notification.show diff --git a/en/application-dev/reference/apis/js-apis-system-package.md b/en/application-dev/reference/apis/js-apis-system-package.md index c6453ec28f1dca4749d8f8c91414a609af161466..3dec0fa1e2fd325479ac688443e67500d60f570b 100644 --- a/en/application-dev/reference/apis/js-apis-system-package.md +++ b/en/application-dev/reference/apis/js-apis-system-package.md @@ -1,9 +1,9 @@ -# Application Management +# @system.package (Bundle Management) -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** +> **NOTE** > -> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.bundle`](js-apis-Bundle.md) instead. +> - This module is deprecated since API version 9. You are advised to use [@ohos.bundle.bundleManager](js-apis-bundleManager.md) instead. > > - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,11 +12,12 @@ ``` -import pkg from '@system.package'; +import package from '@system.package'; ``` -## package.hasInstalled +## package.hasInstalled(deprecated) +> This API is deprecated since API version 9. You are advised to use [@ohos.bundle.bundleManager](js-apis-bundleManager.md) instead. hasInstalled(Object): void @@ -26,35 +27,57 @@ Checks whether an application exists, or whether a native application has been i **System capability**: SystemCapability.BundleManager.BundleFramework -**Parameter** +**Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| bundleName | string | Yes | Application bundle name | -| success | Function | No | Called when the check result is obtained | -| fail | Function | No | Called when the check result fails to be obtained | -| complete | Function | No | Called when the execution is complete | +|options | [CheckPackageHasInstalledOptions](#checkpackagehasinstalledoptions) | Yes| Options.| -The following value will be returned when the check result is obtained. +**Return value** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| result | boolean | Whether the application exists, or whether the native application has been installed | +| result | boolean | The value **true** means that the application exists or the native application has been installed, and **false** means the opposite.| **Example** -``` -export default { - hasInstalled() { - pkg.hasInstalled({ - bundleName: 'com.example.bundlename', - success: function(data) { - console.log('package has installed: ' + data); - }, - fail: function(data, code) { - console.log('query package fail, code: ' + code + ', data: ' + data); - }, - }); +``` ts +export default { + hasInstalled() { + package.hasInstalled({ + bundleName: 'com.example.bundlename', + success: function(data) { + console.log('package has installed: ' + data); + }, + fail: function(data, code) { + console.log('query package fail, code: ' + code + ', data: ' + data); + }, + }); }, } -``` \ No newline at end of file +``` + +## CheckPackageHasInstalledResponse + +> This API is deprecated since API version 9. + +Checks whether a bundle has been installed. + +**System capability**: SystemCapability.BundleManager.BundleFramework + +| Name| Type| Description| +| --- | --- | ---- | +| result | boolean | The value **true** means that the bundle has been installed, and **false** means the opposite.| + +## CheckPackageHasInstalledOptions + +> This API is deprecated since API version 9. + +Defines the options used for checking whether a bundle has been installed. + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| bundleName | string | Yes| Bundle name.| +| success | Function | No| Called when API call is successful.| +| fail | Function | No| Called when API call has failed.| +| complete | Function | No| Called when API call is complete.| diff --git a/en/application-dev/reference/apis/js-apis-system-parameter.md b/en/application-dev/reference/apis/js-apis-system-parameter.md index 6ccbc31664329e94861a503f1995682f104c6d79..ab3ae31887d1a2c55eb94c0164573834321e96c0 100644 --- a/en/application-dev/reference/apis/js-apis-system-parameter.md +++ b/en/application-dev/reference/apis/js-apis-system-parameter.md @@ -1,11 +1,10 @@ -# SystemParameter +# @ohos.systemParameter -The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs of this module to describe the service status and change the service behavior. The basic operation primitives are get and set. You can obtain the values of system parameters through getters and modify the values through setters. +The **SystemParameter** module provides system services with easy access to key-value pairs. You can use the APIs provided by this module to describe the service status and change the service behavior. The basic operation primitives are get and set. You can obtain the values of system parameters through getters and modify the values through setters. For details about the system parameter design principles and definitions, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). > **NOTE** -> > - The APIs of this module are no longer maintained since API version 9. It is recommended that you use [@ohos.systemParameterV9](js-apis-system-parameterV9.md) instead. > - The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > - The APIs provided by this module are system APIs. @@ -54,7 +53,7 @@ try { get(key: string, callback: AsyncCallback<string>): void -Obtains the value of the system parameter with the specified key. This API uses an asynchronous callback to return the result. +Obtains the value of the system parameter with the specified key. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Startup.SystemInfo @@ -164,9 +163,9 @@ Sets a value for the system parameter with the specified key. | value | string | Yes| Value of the system parameter to set.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and DAC rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). + **Example** @@ -195,9 +194,8 @@ Sets a value for the system parameter with the specified key. This API uses an a | callback | AsyncCallback<void> | Yes| Callback used to return the result.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and discretionary access control (DAC) rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). **Example** @@ -236,9 +234,8 @@ Sets a value for the system parameter with the specified key. This API uses a pr | Promise<void> | Promise used to return the execution result.| > **NOTE** -> > - This API can be used only for setting parameters of system applications. -> - SELinux and discretionary access control (DAC) rules must be configured for authorized system applications. For details, see [Service Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). +> - SELinux and Discretionary Access Control (DAC) rules must be configured for authorized system applications. For details about how to configure SELinux and DAC rules, see [Parameter Management](../../../device-dev/subsystems/subsys-boot-init-sysparam.md). **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-request.md b/en/application-dev/reference/apis/js-apis-system-request.md index 18b94b676942abb856fa9bd709c1898a6f98588d..a2b939bf7d0983a25202fe11b7c5dd4ddd9d3665 100644 --- a/en/application-dev/reference/apis/js-apis-system-request.md +++ b/en/application-dev/reference/apis/js-apis-system-request.md @@ -1,9 +1,11 @@ -# Uploading and Downloading +# @system.request -> ![icon-note.gif](public_sys-resources/icon-note.gif) **Note:** -> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.request`](js-apis-request.md) instead. +The **system.request** module provides applications with basic upload and download capabilities. + +> **NOTE** +> - The APIs of this module are deprecated since API version 9. You are advised to use [`@ohos.request`](js-apis-request.md) instead. > -> - The initial APIs of this module are supported since API version 4. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -13,179 +15,245 @@ import request from '@system.request'; ``` -## Required Permissions +## request.upload -ohos.permission.INTERNET. +upload(options: UploadRequestOptions): void +Uploads a file. This API returns no value. -## request.upload +**System capability**: SystemCapability.MiscServices.Upload -upload(Object): void +**Parameters** -Uploads files. + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [UploadRequestOptions](#uploadrequestoptions) | Yes| Upload configurations.| -**Parameters** +**Example** -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| url | string | Yes | URL of the upload server. | -| header | Object | No | Request header. | -| method | string | No | Request methods available: **POST** and **PUT**. The default value is **POST**. | -| files | Array<File> | Yes | List of files to upload, which is submitted through **multipart/form-data**. | -| data | Array<RequestData> | No | Form data in the request body. | -| success | Function | No | Called when the download task is complete. | -| fail | Function | No | Called when downloading fails or the task does not exist. | -| complete | Function | No | Called when the execution is complete. | + ```js + let uploadRequestOptions = { + url: 'http://www.path.com', + method: 'POST', + files: [{ filename: "test", name: "test", uri: "internal://cache/test.jpg", type: "jpg" }], + data: [{ name: "name123", value: "123" }], + success: function(data) { + console.info(' upload success, code:' + JSON.stringify(data)); + }, + fail: function(data, code) { + console.info(' upload fail data: ' + data + 'code: ' + code); + }, + complete: function (){ + console.info(' upload complete'); + } + } + try { + request.upload(uploadRequestOptions); + console.info('upload start '); + } catch(err) { + console.info(' upload err:' + err); + } + ``` -**Table 1** File -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| filename | string | No | File name in the header when **multipart** is used. | -| name | string | No | Name of a form item when **multipart** is used. The default value is **file**. | -| uri | string | Yes | Local storage path of a file. | -| type | string | No | Type of the file content. By default, the type is obtained based on the suffix of the file name or URI. | +## UploadRequestOptions -**Table 2** RequestData +**System capability**: SystemCapability.MiscServices.Upload -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| name | string | Yes | Name of the form element | -| value | string | Yes | Value of the form element | -When the files are successfully uploaded, the following values will be returned. + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | url | string | Yes| URL of the upload server.| + | data | Array<[RequestData](#requestdata)> | No| Form data in the request body.| + | files | Array<[RequestFile](#requestfile)> | Yes| List of files to upload, which is submitted through **multipart/form-data**.| + | header | Object | No| Request header.| + | method | string | No| Request method, which can be **'POST'** or **'PUT'**. The default value is **POST**.| + | success | Function | No| Called when API call is successful.| + | fail | Function | No| Called when API call has failed.| + | complete | Function | No| Called when API call is complete.| -| Name | Type | Description | -| -------- | -------- | -------- | -| code | number | HTTP status code returned by the server. | -| data | string | Content returned by the server. The value type is determined by the type in the returned headers. | -| headers | Object | Headers returned by the server. | +**success parameter** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | data | [UploadResponse](#uploadresponse) | Yes| Information returned when the upload task is successful.| -When the files fail to be uploaded, an HTTP status code is returned in **code** of **data**. +**fail parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | data | any | Yes| Header information returned when the upload task fails.| + | code | number | Yes| HTTP status code returned when the upload task fails.| -**Example** -``` -export default { - upLoad() { - request.upload({ - url: 'http://www.path.com', - files: [ - { - uri: 'internal://cache/path/to/file.txt', - name: 'file', - filename: 'file.txt', - }, - ], - data:[ - { - name: 'name1', - value: 'value', - }, - ], - success: function(data) { - console.log('upload success, code:' + data.code); - }, - fail: function() { - console.log('upload fail'); - }, - }); - } -} -``` +## UploadResponse -## request.download +**System capability**: SystemCapability.MiscServices.Upload -download(Object): void + | Name| Type| Description| + | -------- | -------- | -------- | + | code | number | HTTP status code returned by the server.| + | data | string | Content returned by the server. The value type is determined by the type in the returned headers.| + | headers | Object | Headers returned by the server.| -Downloads files. -**Parameters** +## RequestFile + +**System capability**: SystemCapability.MiscServices.Upload + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | filename | string | No| File name in the header when **multipart** is used.| + | name | string | No| Name of a form item when **multipart** is used. The default value is **file**.| + | uri | string | Yes| Local path for storing files.| + | type | string | No| Type of the file content. By default, the type is obtained based on the extension of the file name or URI.| + + +## RequestData + +**System capability**: SystemCapability.MiscServices.Upload -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| url | string | Yes | Resource URL. | -| header | Object | No | Request header. | -| description | string | No | Download description. The default value is the file name. | -| filename | string | No | Name of the file to download. The value is obtained from the current request or resource URL by default. | -| success | Function | No | Called when the download task is complete. | -| fail | Function | No | Called when downloading fails or the task does not exist. | -| complete | Function | No | Called when the execution is complete. | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | name | string | Yes| Name of the form element.| + | value | string | Yes| Value of the form element.| -Return values of the **success** callback -| Name | Type | Description | -| -------- | -------- | -------- | -| token | string | Download token, which is used to obtain the download status. | -One of the following error codes will be returned if the operation fails. +## request.download + +download(options: DownloadRequestOptions): void + +Downloads a file. This API returns no value. + +**System capability**: SystemCapability.MiscServices.Download + +**Parameters** -| Error Code | Description | -| -------- | -------- | -| 400 | Download task failed | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [DownloadRequestOptions](#downloadrequestoptions) | Yes| Download configurations.| **Example** -``` -export default { - downLoad() { - request.download({ - url: 'http://www.path.com', - success: function(data) { - console.log('call success callback success: ' + data.token); - }, - fail: function(data, code) { - console.log('handling fail'); - }, - }); + ```js + let downloadRequestOptions = { + url: 'http://www.path.com', + filename: 'requestSystenTest', + header: '', + description: 'this is requeSystem download response', + success: function(data) { + console.info(' download success, code:' + JSON.stringify(data)); + }, + fail: function(data, code) { + console.info(' download fail data: ' + data + 'code: ' + code); + }, + complete: function (){ + console.info(' download complete'); + } } -} -``` + try { + request.download(downloadRequestOptions); + console.info('download start '); + } catch(err) { + console.info(' download err:' + err); + } + ``` -## request.onDownloadComplete +## DownloadRequestOptions -onDownloadComplete(Object): void +**System capability**: SystemCapability.MiscServices.Download -Listens to download task status. + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | url | string | Yes| Resource URL.| + | filename | string | No| Name of the file to download. The value is obtained from the current request or resource URL by default.| + | header | Object | No| Request header.| + | description | string | No| Download description. The default value is the file name.| + | success | Function | No| Called when API call is successful.| + | fail | Function | No| Called when API call has failed.| + | complete | Function | No| Called when API call is complete.| -**Parameters** +**success parameter** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | data | [DownloadResponse](#downloadresponse) | Yes| Information returned when the download task is successful.| + +**fail parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | data | any | Yes| Header information returned when the download task fails.| + | code | number | Yes| HTTP status code returned when the download task fails.| + +## DownloadResponse + +**System capability**: SystemCapability.MiscServices.Download + + | Name| Type| Description| + | -------- | -------- | -------- | + | token | string | Download token, which is used to obtain the download status| + + +## request.onDownloadComplete -| Name | Type | Mandatory | Description | -| -------- | -------- | -------- | -------- | -| token | string | Yes | Token of the result returned by the download method | -| success | Function | No | Called when the download task is complete. | -| fail | Function | No | Called when downloading fails or the task does not exist. | -| complete | Function | No | Called when the execution is complete. | +onDownloadComplete(options: OnDownloadCompleteOptions): void -Return values of the **success** callback +Listens for download task status. This API returns no value. -| Name | Type | Description | -| -------- | -------- | -------- | -| uri | string | URI of the download file | +**System capability**: SystemCapability.MiscServices.Download -One of the following error codes will be returned if the listening fails. +**Parameters** -| Error Code | Description | -| -------- | -------- | -| 400 | Download task failed | -| 401 | Download task not exist | + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | options | [OnDownloadCompleteOptions](#ondownloadcompleteoptions) | Yes| Configurations of the download task.| **Example** -``` -export default { - onDownloadComplete() { - request.onDownloadComplete({ - token: 'token-index', - success: function(data) { - console.log('download success, uri:' + data.uri); - }, - fail: function(data, code) { - console.log('download fail'); - }, - }); + ```js + let onDownloadCompleteOptions = { + token: 'token-index', + success: function(data) { + console.info(' download success, code:' + JSON.stringify(data)); + }, + fail: function(data, code) { + console.info(' download fail data: ' + data + 'code: ' + code); + }, + complete: function (){ + console.info(' download complete'); + } } -} -``` \ No newline at end of file + request.onDownloadComplete(onDownloadCompleteOptions); + ``` + + +## OnDownloadCompleteOptions + +**System capability**: SystemCapability.MiscServices.Download + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | token | string | Yes| Result token returned by the download API.| + | success | Function | No| Called when API call is successful.| + | fail | Function | No| Called when API call has failed.| + | complete | Function | No| Called when API call is complete.| + +**success parameter** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | data | [OnDownloadCompleteResponse](#ondownloadcompleteresponse) | Yes| Information returned when the download task is successful.| + +**fail parameters** + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | data | any | Yes| Header information returned when the download task fails.| + | code | number | Yes| HTTP status code returned when the download task fails.| + + +## OnDownloadCompleteResponse + +**System capability**: SystemCapability.MiscServices.Download + + | Name| Type| Description| + | -------- | -------- | -------- | + | uri | string | URI of the download file.| diff --git a/en/application-dev/reference/apis/js-apis-system-router.md b/en/application-dev/reference/apis/js-apis-system-router.md index 60e999026e58bb6510a24540609f9c6bc44aa55d..1d47c8883ae8d3cc4be49d19845ce1b3e3d5bb2a 100644 --- a/en/application-dev/reference/apis/js-apis-system-router.md +++ b/en/application-dev/reference/apis/js-apis-system-router.md @@ -1,4 +1,4 @@ -# Page Routing +# @system.router The **Router** module provides APIs to access pages through URIs. @@ -43,8 +43,8 @@ export default { data1: 'message', data2: { data3: [123, 456, 789] - }, - }, + } + } }); } } @@ -67,7 +67,8 @@ export default { } ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > The page routing stack supports a maximum of 32 pages. @@ -94,8 +95,8 @@ export default { router.replace({ uri: 'pages/detail/detail', params: { - data1: 'message', - }, + data1: 'message' + } }); } } @@ -135,7 +136,7 @@ Returns to the previous page or a specified page. export default { indexPushPage() { router.push({ - uri: 'pages/detail/detail', + uri: 'pages/detail/detail' }); } } @@ -147,7 +148,7 @@ export default { export default { detailPushPage() { router.push({ - uri: 'pages/mall/mall', + uri: 'pages/mall/mall' }); } } @@ -183,7 +184,8 @@ export default { } ``` -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** +> **NOTE** +> > In the example, the **uri** field indicates the page route, which is specified by the **pages** list in the **config.json** file. ## router.getParams @@ -237,7 +239,7 @@ Obtains the number of pages in the current stack. ```js export default { getLength() { - var size = router.getLength(); + let size = router.getLength(); console.log('pages stack size = ' + size); } } @@ -262,7 +264,7 @@ Obtains state information about the current page. ```js export default { getState() { - var page = router.getState(); + let page = router.getState(); console.log('current index = ' + page.index); console.log('current name = ' + page.name); console.log('current path = ' + page.path); @@ -296,7 +298,7 @@ export default { }, cancel: function() { console.log('cancel'); - }, + } }); } } @@ -327,7 +329,7 @@ export default { }, cancel: function() { console.log('cancel'); - }, + } }); } } @@ -339,10 +341,10 @@ Defines the page routing parameters. **System capability**: SystemCapability.ArkUI.ArkUI.Lite -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| uri | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| -| params | Object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of 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.| +| Name | Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| uri | string | Yes | URI of the target page, in either of the following formats:
1. Absolute path, which is provided by the **pages** list in the **config.json** file. Example:
- pages/index/index
- pages/detail/detail
2. Specific path. If the URI is a slash (/), the home page is displayed.| +| params | object | No | Data that needs to be passed to the target page during redirection. The target page can use **router.getParams()** to obtain the passed parameters, for example, **this.keyValue** (**keyValue** is the value of 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.| ## BackRouterOptions @@ -351,10 +353,10 @@ Defines the parameters for routing back. **System capability**: The items in the table below require different system capabilities. For details, see the table. -| Name | Type | Mandatory | Description | -| ------ | ------ | ---- | ---------------------------------------- | -| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| -| params | Object | No | Data that needs to be passed to the target page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| +| Name | Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------------------------ | +| uri | string | No | URI of the page to return to. If the specified page does not exist in the page stack, the application does not respond. If this parameter is not set, the application returns to the previous page.
**System capability**: SystemCapability.ArkUI.ArkUI.Full| +| params | object | No | Data that needs to be passed to the target page during redirection.
**System capability**: SystemCapability.ArkUI.ArkUI.Lite| ## RouterState diff --git a/en/application-dev/reference/apis/js-apis-system-sensor.md b/en/application-dev/reference/apis/js-apis-system-sensor.md index 7df5f6675bb53168935ada36ca1d0675e49da978..30bfc60e3339b8102fbe6f4a6c5fc1202015da11 100644 --- a/en/application-dev/reference/apis/js-apis-system-sensor.md +++ b/en/application-dev/reference/apis/js-apis-system-sensor.md @@ -1,4 +1,4 @@ -# Sensor +# @system.sensor (Sensor) The **Sensor** module provides APIs for querying the sensor list, subscribing to or unsubscribing from sensor data, and executing control commands. @@ -21,9 +21,9 @@ import sensor from '@system.sensor'; ## Error Codes -| Error Code | Description | -| ---------- | ---------------------------------------- | -| 900 | The current device does not support the corresponding sensor. | +| Error Code | Description | +| ---- | -------------- | +| 900 | The current device does not support the corresponding sensor.| ## sensor.subscribeAccelerometer @@ -37,19 +37,19 @@ Subscribes to data changes of the acceleration sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the acceleration sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Execution frequency of the callback for returning the acceleration sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the acceleration sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | --------------------------- | -| x | number | Acceleration on the x-axis. | -| y | number | Acceleration on the y-axis. | -| z | number | Acceleration on the z-axis. | +| Name | Type | Description | +| ---- | ------ | ------- | +| x | number | Acceleration on the x-axis.| +| y | number | Acceleration on the y-axis.| +| z | number | Acceleration on the z-axis.| **Example** @@ -68,7 +68,6 @@ sensor.subscribeAccelerometer({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeAccelerometer @@ -97,16 +96,16 @@ Subscribes to data changes of the compass sensor. If this API is called multiple **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the compass sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | --------------- | +| success | Function | Yes | Called when the compass sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------------------------------ | -| direction | number | Direction of the device, in degrees. | +| Name | Type | Description | +| --------- | ------ | ---------- | +| direction | number | Direction of the device, in degrees.| **Example** @@ -122,7 +121,6 @@ sensor.subscribeCompass({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeCompass @@ -149,16 +147,16 @@ Subscribes to data changes of the proximity sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the proximity sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ----------------- | +| success | Function | Yes | Called when the proximity sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | ---------------------------------------- | -| distance | number | Distance between a visible object and the device screen. | +| Name | Type | Description | +| -------- | ------ | --------------------- | +| distance | number | Distance between a visible object and the device screen.| **Example** @@ -174,7 +172,6 @@ sensor.subscribeProximity({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeProximity @@ -201,16 +198,16 @@ Subscribes to data changes of the ambient light sensor. If this API is called mu **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the ambient light sensor data changes | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | --------------- | +| success | Function | Yes | Called when the ambient light sensor data changes| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ------------------------ | -| intensity | number | Light intensity, in lux. | +| Name | Type | Description | +| --------- | ------ | ------------ | +| intensity | number | Light intensity, in lux.| **Example** @@ -226,7 +223,6 @@ sensor.subscribeLight({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeLight @@ -255,16 +251,16 @@ Subscribes to data changes of the step counter sensor. If this API is called mul **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the step counter sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ---------------- | +| success | Function | Yes | Called when the step counter sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------ | ---------------------------------------- | -| steps | number | Number of counted steps after the sensor is restarted.
| +| Name | Type | Description | +| ----- | ------ | --------------------- | +| steps | number | Number of counted steps after the sensor is restarted.
| **Example** @@ -280,7 +276,6 @@ sensor.subscribeStepCounter({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeStepCounter @@ -310,16 +305,16 @@ Subscribes to data changes of the barometer sensor. If this API is called multip **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the barometer sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ---------------- | +| success | Function | Yes | Called when the barometer sensor data changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| -------- | ------ | -------------------- | -| pressure | number | Pressure, in pascal. | +| Name | Type | Description | +| -------- | ------ | ----------- | +| pressure | number | Pressure, in pascal.| **Example** @@ -335,7 +330,6 @@ sensor.subscribeBarometer({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. @@ -366,16 +360,16 @@ Subscribes to data changes of the heart rate sensor. If this API is called multi **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | ---------------------------------------- | -| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ------------------------- | +| success | Function | Yes | Called when the heart rate sensor data changes. This callback is invoked every five seconds.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| --------- | ------ | ----------- | -| heartRate | number | Heart rate. | +| Name | Type | Description | +| --------- | ------ | ---- | +| heartRate | number | Heart rate.| **Example** @@ -391,7 +385,6 @@ sensor.subscribeHeartRate({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. @@ -421,16 +414,16 @@ Subscribes to changes of the wearing state of a wearable device. If this API is **Parameters** -| Name | Type | Mandatory | Description | -| ------- | -------- | --------- | -------------------------------------- | -| success | Function | Yes | Called when the wearing state changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| ------- | -------- | ---- | ------------- | +| success | Function | Yes | Called when the wearing state changes.| +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------------------------------------ | -| value | boolean | Whether the wearable device is worn. | +| Name | Type | Description | +| ----- | ------- | ------ | +| value | boolean | Whether the wearable device is worn.| **Example** @@ -446,7 +439,6 @@ sensor.subscribeOnBodyState({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeOnBodyState @@ -473,17 +465,17 @@ Obtains the wearing state of a wearable device. **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | -------------------------------------- | -| success | Function | No | Callback upon success. | -| fail | Function | No | Callback upon failure. | -| complete | Function | No | Called when the execution is complete. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ------------ | +| success | Function | No | Callback upon success.| +| fail | Function | No | Callback upon failure.| +| complete | Function | No | Called when the execution is complete.| Return values of the success callback -| Name | Type | Description | -| ----- | ------- | ------------------------------------ | -| value | boolean | Whether the wearable device is worn. | +| Name | Type | Description | +| ----- | ------- | ------ | +| value | boolean | Whether the wearable device is worn.| **Example** @@ -510,18 +502,18 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the device orientation sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the device orientation sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the device orientation sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | +| Name | Type | Description | | ----- | ------ | ---------------------------------------- | -| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth. | -| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth. | -| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth. | +| alpha | number | Rotation angle around the Z axis when the X/Y axis of the device coincides with the X/Y axis of the earth.| +| beta | number | Rotation angle around the X axis when the Y/Z axis of the device coincides with the Y/Z axis of the earth.| +| gamma | number | Rotation angle around the Y axis when the X/Z axis of the device coincides with the X/Z axis of the earth.| **Example** @@ -540,7 +532,6 @@ sensor.subscribeDeviceOrientation({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeDeviceOrientation6+ @@ -571,19 +562,19 @@ If this API is called multiple times for the same application, the last call tak **Parameters** -| Name | Type | Mandatory | Description | -| -------- | -------- | --------- | ---------------------------------------- | -| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios. | -| success | Function | Yes | Called when the gyroscope sensor data changes. | -| fail | Function | No | Callback upon failure. | +| Name | Type | Mandatory | Description | +| -------- | -------- | ---- | ---------------------------------------- | +| interval | string | Yes | Interval at which the callback is invoked to return the gyroscope sensor data.
The default value is **normal**. The options are as follows:
- **game**: called at an interval of 20 ms, which is applicable to gaming scenarios.
- **ui**: called at an interval of 60 ms, which is applicable to UI updating scenarios.
- **normal**: called at an interval of 200 ms, which is applicable to power-saving scenarios.| +| success | Function | Yes | Called when the gyroscope sensor data changes. | +| fail | Function | No | Callback upon failure. | Return values of the success callback -| Name | Type | Description | -| ---- | ------ | ---------------------------------------- | -| x | number | Rotation angular velocity of the X axis. | -| y | number | Rotation angular velocity of the Y axis. | -| z | number | Rotation angular velocity of the Z axis. | +| Name | Type | Description | +| ---- | ------ | --------- | +| x | number | Rotation angular velocity of the X axis.| +| y | number | Rotation angular velocity of the Y axis.| +| z | number | Rotation angular velocity of the Z axis.| **Example** @@ -602,7 +593,6 @@ sensor.subscribeGyroscope({ ``` > **NOTE** -> > To reduce performance overhead, you are advised to unsubscribe from the sensor data in the **onDestory** callback. ## sensor.unsubscribeGyroscope6+ diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index 5247364504e7c8dce7897166b9d85c92a6b4ae8f..a1876af97b532bf208eb405ee9c7c22edda6919f 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,4 +1,4 @@ -# System Time and Time Zone +# @ohos.systemTime The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. @@ -12,7 +12,7 @@ The **systemTime** module provides system time and time zone features. You can u import systemTime from '@ohos.systemTime'; ``` -## systemTime.setTime +## systemTime.setTime(deprecated) setTime(time : number, callback : AsyncCallback<void>) : void @@ -34,16 +34,20 @@ Sets the system time. This API uses an asynchronous callback to return the resul ```js // Set the system time to 2021-01-20 02:36:25. let time = 1611081385000; -systemTime.setTime(time, (error, data) => { - if (error) { - console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); -}); +try { + systemTime.setTime(time, (error) => { + if (error) { + console.info(`Failed to setting time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting time`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setTime +## systemTime.setTime(deprecated) setTime(time : number) : Promise<void> @@ -70,19 +74,27 @@ Sets the system time. This API uses a promise to return the result. ```js // Set the system time to 2021-01-20 02:36:25. let time = 1611081385000; -systemTime.setTime(time).then((data) => { - console.log(`Succeeded in setting systemTime. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to set systemTime. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.setTime(time).then(() => { + console.info(`Succeeded in setting time.`); + }).catch((error) => { + console.info(`Failed to setting time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -95,21 +107,29 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal **Example** ```js -systemTime.getCurrentTime(true, (error, data) => { - if (error) { - console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getCurrentTime(true, (error, time) => { + if (error) { + console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) getCurrentTime(callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. 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 [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime-1). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -121,21 +141,29 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal **Example** ```js -systemTime.getCurrentTime((error, data) => { - if (error) { - console.error(`Succeeded in getting systemTime. Data:` + JSON.stringify(error)); - return; - } - console.log(`Failed to get systemTime. Cause:` + JSON.stringify(data)); -}); +try { + systemTime.getCurrentTime((error, time) => { + if (error) { + console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting currentTime : ${time}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getCurrentTime8+ +## systemTime.getCurrentTime(deprecated) getCurrentTime(isNano?: boolean): Promise<number> Obtains the time elapsed since the Unix epoch. 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 [systemDateTime.getCurrentTime](./js-apis-system-date-time.md#systemdatetimegetcurrenttime-2). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -153,19 +181,27 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return **Example** ```js -systemTime.getCurrentTime().then((data) => { - console.log(`Succeeded in getting systemTime. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get systemTime. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getCurrentTime().then((time) => { + console.info(`Succeeded in getting currentTime : ${time}`); + }).catch((error) => { + console.info(`Failed to getting currentTime. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get currentTime. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, excluding the deep sleep time. 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 [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -178,21 +214,29 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th **Example** ```js -systemTime.getRealActiveTime(true, (error, data) => { - if (error) { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealActiveTime(true, (error, time) => { + if (error) { + console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) getRealActiveTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, excluding the deep sleep time. 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 [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime-1). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -204,21 +248,29 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th **Example** ```js -systemTime.getRealActiveTime((error, data) => { - if (error) { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealActiveTime((error, time) => { + if (error) { + console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real active time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealActiveTime8+ +## systemTime.getRealActiveTime(deprecated) getRealActiveTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system startup, excluding the deep sleep time. 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 [systemDateTime.getRealActiveTime](./js-apis-system-date-time.md#systemdatetimegetrealactivetime-2). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -236,19 +288,27 @@ Obtains the time elapsed since system startup, excluding the deep sleep time. Th **Example** ```js -systemTime.getRealActiveTime().then((data) => { - console.log(`Succeeded in getting real active time. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get real active time. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getRealActiveTime().then((time) => { + console.info(`Succeeded in getting real active time : ${time}`); + }).catch((error) => { + console.info(`Failed to getting real active time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real active time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) getRealTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, including the deep sleep time. 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 [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -261,21 +321,29 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th **Example** ```js -systemTime.getRealTime(true, (error, data) => { - if (error) { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealTime(true, (error, time) => { + if (error) { + console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) getRealTime(callback: AsyncCallback<number>): void Obtains the time elapsed since system startup, including the deep sleep time. 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 [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime-1). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -287,28 +355,36 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th **Example** ```js -systemTime.getRealTime((error, data) => { - if (error) { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getRealTime((error, time) => { + if (error) { + console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in getting real time : ${time}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getRealTime8+ +## systemTime.getRealTime(deprecated) getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system startup, including the deep sleep time. 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 [systemDateTime.getRealTime](./js-apis-system-date-time.md#systemdatetimegetrealtime-2). + **System capability**: SystemCapability.MiscServices.Time **Parameters** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------- | -| isNano | boolean | No | Whether the time to return is in nanoseconds.<
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds (ns).
- **false**: in milliseconds (ms).| **Return value** @@ -319,14 +395,18 @@ Obtains the time elapsed since system startup, including the deep sleep time. Th **Example** ```js -systemTime.getRealTime().then((data) => { - console.log(`Succeeded in getting real time. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get real time. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getRealTime().then((time) => { + console.info(`Succeeded in getting real time : ${time}`); + }).catch((error) => { + console.info(`Failed to getting real time. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get real time. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setDate +## systemTime.setDate(deprecated) setDate(date: Date, callback: AsyncCallback<void>): void @@ -346,17 +426,21 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Example** ```js -let data = new Date(); -systemTime.setDate(data,(error, data) => { - if (error) { - console.error('Failed to set system date. Cause:' + JSON.stringify(error)); - return; -} - console.info('Succeeded in setting system date. Data:' + JSON.stringify(data)); -}); +let date = new Date(); +try { + systemTime.setDate(date, (error) => { + if (error) { + console.info(`Failed to setting date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting date.`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setDate +## systemTime.setDate(deprecated) setDate(date: Date): Promise<void> @@ -381,20 +465,28 @@ Sets the system date. This API uses a promise to return the result. **Example** ```js -let data = new Date(); -systemTime.setDate(data).then((value) => { - console.log(`Succeeded in setting system date. Data:` + JSON.stringify(value)); -}).catch((error) => { - console.error(`Failed to set system date. Cause:` + JSON.stringify(error)); -}); +let date = new Date(); +try { + systemTime.setDate(date).then(() => { + console.info(`Succeeded in setting date.`); + }).catch((error) => { + console.info(`Failed to setting date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getDate8+ +## systemTime.getDate(deprecated) getDate(callback: AsyncCallback<Date>): void Obtains the current system date. 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 [systemDateTime.getDate](./js-apis-system-date-time.md#systemdatetimegetdate). + **System capability**: SystemCapability.MiscServices.Time **Parameters** @@ -406,21 +498,29 @@ Obtains the current system date. This API uses an asynchronous callback to retur **Example** ```js -systemTime.getDate((error, data) => { - if (error) { - console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getDate((error, date) => { + if (error) { + console.info(`Failed to get date. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in get date : ${date}`);; + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getDate8+ +## systemTime.getDate(deprecated) getDate(): Promise<Date> Obtains the current system date. 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 [systemDateTime.getDate](./js-apis-system-date-time.md#systemdatetimegetdate-1). + **System capability**: SystemCapability.MiscServices.Time **Return value** @@ -432,14 +532,18 @@ Obtains the current system date. This API uses a promise to return the result. **Example** ```js -systemTime.getDate().then((data) => { - console.log(`Succeeded in getting system date. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get system date. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getDate().then((date) => { + console.info(`Succeeded in getting date : ${date}`); + }).catch((error) => { + console.info(`Failed to getting date. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get date. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setTimezone +## systemTime.setTimezone(deprecated) setTimezone(timezone: string, callback: AsyncCallback<void>): void @@ -453,22 +557,26 @@ Sets the system time zone. This API uses an asynchronous callback to return the | Name | Type | Mandatory| Description | | -------- | ------------- | ---- | -------------------------- | -| timezone | string | Yes | System time zone to set. | +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones). | | callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -systemTime.setTimezone('Asia/Shanghai', (error, data) => { - if (error) { - console.error('Failed to set system time zone. Cause:' + JSON.stringify(error)); - return; - } - console.info('Succeeded in setting system time zone. Data:' + JSON.stringify(data)); -}); +try { + systemTime.setTimezone('Asia/Shanghai', (error) => { + if (error) { + console.info(`Failed to setting timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in setting timezone.`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.setTimezone +## systemTime.setTimezone(deprecated) setTimezone(timezone: string): Promise<void> @@ -482,7 +590,7 @@ Sets the system time zone. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------- | -| timezone | string | Yes | System time zone to set.| +| timezone | string | Yes | System time zone to set. For details, see [Supported System Time Zones](#supported-system-time-zones).| **Return value** @@ -493,59 +601,117 @@ Sets the system time zone. This API uses a promise to return the result. **Example** ```js -systemTime.setTimezone('Asia/Shanghai').then((data) => { - console.log(`Succeeded in setting system time zone. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to set system time zone. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.setTimezone('Asia/Shanghai').then(() => { + console.info(`Succeeded in setting timezone.`); + }).catch((error) => { + console.info(`Failed to setting timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to set timezone. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getTimezone8+ +## systemTime.getTimezone(deprecated) getTimezone(callback: AsyncCallback<string>): void Obtains the system time zone. 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 [systemDateTime.getTimezone](./js-apis-system-date-time.md#systemdatetimegettimezone). + **System capability**: SystemCapability.MiscServices.Time **Parameters** | Name | Type | Mandatory| Description | | -------- | --------- | ---- | ------------------------ | -| callback | AsyncCallback<string> | Yes | Callback used to return the system time zone.| +| callback | AsyncCallback<string> | Yes | Callback used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| **Example** ```js -systemTime.getTimezone((error, data) => { - if (error) { - console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); - return; - } - console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); -}); +try { + systemTime.getTimezone((error, data) => { + if (error) { + console.info(`Failed to get timezone. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in get timezone : ${data}`);; + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} ``` -## systemTime.getTimezone8+ +## systemTime.getTimezone(deprecated) getTimezone(): Promise<string> Obtains the system time zone. 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 [systemDateTime.getTimezone](./js-apis-system-date-time.md#systemdatetimegettimezone-1). + **System capability**: SystemCapability.MiscServices.Time **Return value** | Type | Description | | --------------------- | ------------------------------------- | -| Promise<string> | Promise used to return the system time zone.| +| Promise<string> | Promise used to return the system time zone. For details, see [Supported System Time Zones](#supported-system-time-zones).| **Example** ```js -systemTime.getTimezone().then((data) => { - console.log(`Succeeded in getting system time zone. Data:` + JSON.stringify(data)); -}).catch((error) => { - console.error(`Failed to get system time zone. Cause:` + JSON.stringify(error)); -}); +try { + systemTime.getTimezone().then((data) => { + console.info(`Succeeded in getting timezone: ${data}`); + }).catch((error) => { + console.info(`Failed to getting timezone. message:${error.message}, code:${error.code}`); + }); +} catch(e) { + console.info(`Failed to get timezone. message:${e.message}, code:${e.code}`); +} ``` + +## Supported System Time Zones + +The following table lists the supported system time zones and the respective offset (unit: h) between each time zone and time zone 0. + +| Time Zone | Offset | +| ------------------------------ | --------------------- | +| Antarctica/McMurdo | 12 | +| America/Argentina/Buenos_Aires | -3 | +| Australia/Sydney | 10 | +| America/Noronha | -2 | +| America/St_Johns | -3 | +| Africa/Kinshasa | 1 | +| America/Santiago | -3 | +| Asia/Shanghai | 8 | +| Asia/Nicosia | 3 | +| Europe/Berlin | 2 | +| America/Guayaquil | -5 | +| Europe/Madrid | 2 | +| Pacific/Pohnpei | 11 | +| America/Godthab | -2 | +| Asia/Jakarta | 7 | +| Pacific/Tarawa | 12 | +| Asia/Almaty | 6 | +| Pacific/Majuro | 12 | +| Asia/Ulaanbaatar | 8 | +| America/Mexico_City | -5 | +| Asia/Kuala_Lumpur | 8 | +| Pacific/Auckland | 12 | +| Pacific/Tahiti | -10 | +| Pacific/Port_Moresby | 10 | +| Asia/Gaza | 3 | +| Europe/Lisbon | 1 | +| Europe/Moscow | 3 | +| Europe/Kiev | 3 | +| Pacific/Wake | 12 | +| America/New_York | -4 | +| Asia/Tashkent | 5 | diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md index b7880eebd39edf24bec47aafaece182f6a1ef5c2..fb1f95ce2d8c5003377120d9d28f29f4415d3117 100644 --- a/en/application-dev/reference/apis/js-apis-system-timer.md +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -1,337 +1,409 @@ -# System Timer +# @ohos.systemTimer The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services. > **NOTE** ->- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs of this module are system APIs and cannot be called by third-party applications. +> +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> - The APIs provided by this module are system APIs. ## Modules to Import -``` +```js import systemTimer from '@ohos.systemTimer'; ``` +## Constants + +Provides the constants that define the supported timer types. + +**System capability**: SystemCapability.MiscServices.Time + +| Name | Type | Value | Description | +| ------------------- | ------ | ---- | ---------------------------- | +| TIMER_TYPE_REALTIME | number | 1 | CPU time type. (The start time of the timer cannot be later than the current system time.) | +| TIMER_TYPE_WAKEUP | number | 2 | Wakeup type. | +| TIMER_TYPE_EXACT | number | 4 | Exact type. | +| TIMER_TYPE_IDLE | number | 8 | Idle type (not supported currently).| + + ## TimerOptions + +Defines the initialization options for **createTimer**. + +**System capability**: SystemCapability.MiscServices.Time + +| Name | Type | Mandatory| Description | +| --------- | --------------------------------------------- | ---- | ------------------------------------------------------------ | +| type | number | Yes | Timer type.
**1**: CPU time type. (The start time of the timer cannot be later than the current system time.)
**2**: wakeup type.
**4**: exact type.
**8**: idle type (not supported currently).| +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**.| +| wantAgent | [WantAgent](js-apis-app-ability-wantAgent.md) | No | **WantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.)| +| callback | number | Yes | Callback used to return the timer ID. | -## systemTime.createTimer + +## systemTimer.createTimer createTimer(options: TimerOptions, callback: AsyncCallback<number>): void Creates a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------| ---- | --------------------------------------------------------------------------- | -| options | [TimerOptions](#timeroptions) | Yes | Timer options. | - -**Return value** - -| Type | Description | -| ------------------------- | ------------------------------------------------------------ | -| syncCallback<number>| Callback used to return the timer ID. | +| Name | Type | Mandatory| Description | +| -------- | ----------------------------- | ---- | ------------------------------------------------------------ | +| options | [TimerOptions](#timeroptions) | Yes | Timer initialization options, including the timer type, whether the timer is a repeating timer, interval, and **WantAgent** options.| +| callback | AsyncCallback<number> | Yes | Callback used to return the timer ID. | **Example** - ```js +```js export default { systemTimer () { - var options = { + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat: false + }; + try { + systemTimer.createTimer(options, (error) => { + if (error) { + console.info(`Failed to create timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in creating timer.`); + }); + } catch(e) { + console.info(`Failed to create timer. message:${e.message}, code:${e.code}`); } - systemTimer.createTimer(options, (error, data) => { - if (error) { - console.error(`failed to systemTime.createTimer ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.createTimer success data : ` + JSON.stringify(data)); - }); } } - ``` - +``` -## systemTime.createTimer +## systemTimer.createTimer createTimer(options: TimerOptions): Promise<number> Creates a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ---------------------------------| ---- | --------------------------------------------------------------------------- | -| options | [TimerOptions](#timeroptions) | Yes | Timer options. | +| Name | Type | Mandatory| Description | +| ------- | ----------------------------- | ---- | ------------------------------------------------------------ | +| options | [TimerOptions](#timeroptions) | Yes | Timer initialization options, including the timer type, whether the timer is a repeating timer, interval, and **WantAgent** options.| **Return value** -| Type | Description | -| --------------------- | ------------------------------------------------------------ | -| Promise<number> | Promise used to return the timer ID. | +| Type | Description | +| --------------------- | ----------------------------- | +| Promise<number> | Promise used to return the timer ID.| **Example** - ```js +```js export default { systemTimer () { - var options = { + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false + }; + try { + systemTimer.createTimer(options).then(() => { + console.info(`Succeeded in creating timer.`); + }).catch((error) => { + console.info(`Failed to create timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to create timer. message:${e.message}, code:${e.code}`); } - systemTimer.createTimer(options).then((data) => { - console.log(`systemTime.createTimer success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.createTimer because ` + JSON.stringify(error)); - }); } } - ``` - +``` -## systemTime.startTimer +## systemTimer.startTimer startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void Starts a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | -| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | - +| Name | Type | Mandatory| Description | +| ----------- | ---------------------- | ---- | ------------------------------ | +| timer | number | Yes | ID of the timer. | +| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js +```js export default { - systemTimer () { - var options = { + async systemTimer () { + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) - let triggerTime = new Date().getTime() - triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime, (error, data) => { - if (error) { - console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); - }); + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + try { + systemTimer.startTimer(timerId, triggerTime, (error) => { + if (error) { + console.info(`Failed to start timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in starting timer.`); + }); + } catch(e) { + console.info(`Failed to start timer. message:${e.message}, code:${e.code}`); + } } } - ``` +``` -## systemTime.startTimer +## systemTimer.startTimer startTimer(timer: number, triggerTime: number): Promise<void> Starts a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name | Type | Mandatory| Description | -| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | | triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------ | +| timer | number | Yes | ID of the timer. | +| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise that returns no value.| **Example** - ```js +```js export default { - systemTimer (){ - var options = { + async systemTimer (){ + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) - let triggerTime = new Date().getTime() + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() triggerTime += 3000 - systemTimer.startTimer(timerId, triggerTime).then((data) => { - console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); - }); + try { + systemTimer.startTimer(timerId, triggerTime).then(() => { + console.info(`Succeeded in starting timer.`); + }).catch((error) => { + console.info(`Failed to start timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to start timer. message:${e.message}, code:${e.code}`); + } } } - ``` - +``` -## systemTime.stopTimer +## systemTimer.stopTimer stopTimer(timer: number, callback: AsyncCallback<void>): void Stops a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------ | +| timer | number | Yes | ID of the timer.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js +```js export default { - systemTimer () { - var options = { + async systemTimer () { + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) - let triggerTime = new Date().getTime() + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) - systemTimer.stoptTimer(timerId, (error, data) => { - if (error) { - console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); - }); - } + try { + systemTimer.stopTimer(timerId, (error) => { + if (error) { + console.info(`Failed to stop timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in stopping timer.`); + }); + } catch(e) { + console.info(`Failed to stop timer. message:${e.message}, code:${e.code}`); + } + } } - ``` - +``` -## systemTime.stopTimer +## systemTimer.stopTimer stopTimer(timer: number): Promise<void> Stops a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| timer | number | Yes | ID of the timer.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise that returns no value.| **Example** - ```js +```js export default { - systemTimer (){ - var options = { + async systemTimer (){ + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) - let triggerTime = new Date().getTime() + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) - systemTimer.stoptTimer(timerId).then((data) => { - console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); - }); + try { + systemTimer.stopTimer(timerId).then(() => { + console.info(`Succeeded in stopping timer.`); + }).catch((error) => { + console.info(`Failed to stop timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to stop timer. message:${e.message}, code:${e.code}`); + } } } - ``` - +``` -## systemTime.destroyTimer +## systemTimer.destroyTimer destroyTimer(timer: number, callback: AsyncCallback<void>): void Destroys a timer. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------ | +| timer | number | Yes | ID of the timer.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** - ```js +```js export default { - systemTimer () { - var options = { + async systemTimer () { + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) - let triggerTime = new Date().getTime() + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) - systemTimer.destroyTimer(timerId, (error, data) => { - if (error) { - console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); - return; - } - console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); - }); + try { + systemTimer.destroyTimer(timerId, (error) => { + if (error) { + console.info(`Failed to destroy timer. message:${error.message}, code:${error.code}`); + return; + } + console.info(`Succeeded in destroying timer.`); + }); + } catch(e) { + console.info(`Failed to destroying timer. message:${e.message}, code:${e.code}`); + } } } - ``` - +``` -## systemTime.destroyTimer +## systemTimer.destroyTimer destroyTimer(timer: number): Promise<void> Destroys a timer. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.MiscServices.Time **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------ | +| timer | number | Yes | ID of the timer.| + +**Return value** + +| Type | Description | +| -------------- | ------------------------- | +| Promise\ | Promise that returns no value.| **Example** - ```js +```js export default { - systemTimer (){ - var options = { + async systemTimer (){ + let options = { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.createTimer(options) - let triggerTime = new Date().getTime() + let timerId = await systemTimer.createTimer(options) + let triggerTime = new Date().getTime() triggerTime += 3000 systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) - systemTimer.destroyTimer(timerId, 10000).then((data) => { - console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); - }); + try { + systemTimer.destroyTimer(timerId).then(() => { + console.info(`Succeeded in destroying timer.`); + }).catch((error) => { + console.info(`Failed to destroy timer. message:${error.message}, code:${error.code}`); + }); + } catch(e) { + console.info(`Failed to destroying timer. message:${e.message}, code:${e.code}`); + } } } - ``` - - ## TimerOptions - -Defines the initialization options for **createTimer**. - -**System capability**: SystemCapability.MiscServices.Time - -| Name | Type | Mandatory| Description | -| -------- | ------------------| ---- | ------------------------------------------------------------------------------------------------------------------------- | -| type | number | Yes | **const TIMER_TYPE_REALTIME**: sets the timer to the CPU time type. (When the set time is later than the timer startup time, the timer expires.) If it is not specified, the timer is of the wall-time type.
**const TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**const TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**const TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported). | -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | -| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.) | -| callback | number | Yes | Callback used to return the timer ID. | +``` diff --git a/en/application-dev/reference/apis/js-apis-system-vibrate.md b/en/application-dev/reference/apis/js-apis-system-vibrate.md index 86f474bce1a013f32bb351bfc6a0a44b658cbba5..90dc19e2ffb0c8817f7cc2096dc792d252f8996f 100644 --- a/en/application-dev/reference/apis/js-apis-system-vibrate.md +++ b/en/application-dev/reference/apis/js-apis-system-vibrate.md @@ -1,6 +1,7 @@ -# Vibrator +# @system.vibrator (Vibrator) -The **Vibrate** module provides APIs for controlling LED lights and vibrators. You can use the APIs to query the LED light list, turn on and off the LED light, query the vibrator list, query the vibrator effect, and trigger and turn off the vibrator. + +The **Vibrator** module provides APIs for controlling LED lights and vibrators. You can use the APIs to query the LED light list, turn on and off the LED light, query the vibrator list, query the vibrator effect, and trigger and turn off the vibrator. Misc devices refer to LED lights and vibrators on devices. LED lights are mainly used for indication (for example, indicating the charging state) and blinking (such as tri-colored lights). Vibrators are mainly used in scenarios such as the alarm clock, power-on/off, and incoming call vibration. diff --git a/en/application-dev/reference/apis/js-apis-tagSession.md b/en/application-dev/reference/apis/js-apis-tagSession.md index e6073f2dca4b101454fbdf14dd9bdd406a8eaade..3138f52c7089ba4a53809711c442b79f6a1aa1aa 100644 --- a/en/application-dev/reference/apis/js-apis-tagSession.md +++ b/en/application-dev/reference/apis/js-apis-tagSession.md @@ -1,8 +1,9 @@ -# NFC Tag Session +# tagSession The **tagSession** module provides common APIs for establishing connections and transferring data. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## **Modules to Import** @@ -15,17 +16,15 @@ import tag from '@ohos.nfc.tag'; Provides common APIs for establishing connections and transferring data. **tagSession** is the base class of all [NFC tag technologies](js-apis-nfctech.md). -A child class instance is required to access the following interfaces. You can use **get**XX**Tag()** to obtain a child class instance. +A child class instance is required to access the following interfaces. You can use **get**XXX() to obtain a child class instance. The specific API varies with the NFC tag technology in use. For details, see [NFC Tags](js-apis-nfcTag.md). -### tagSession.connectTag - -connectTag(): boolean; +### tagSession.getTagInfo -Connects to this tag. +getTagInfo(): tag.TagInfo -Call this API to set up a connection before reading data from or writing data to a tag. +Obtains the **tagInfo** object provided by the NFC service when the tag is dispatched. **Required permissions**: ohos.permission.NFC_TAG @@ -35,23 +34,25 @@ Call this API to set up a connection before reading data from or writing data to | **Type**| **Description** | | ------------------ | --------------------------| -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| +| TagInfo | **Taginfo** object obtained.| **Example** ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isNfcConnected = tag.getXXXTag(taginfo).connectTag(); -console.log("isNfcConnected:" +isNfcConnected); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let tagInfo = tag.getIsoDep(tagInfo).getTagInfo(); +console.log("tag tagInfo: " + tagInfo); ``` -### tagSession.reset() +### tagSession.connectTag -reset(): void +connectTag(): boolean; -Resets the connection to this tag and restores the default timeout duration for writing data to the tag. +Connects to this tag. Call this API to set up a connection before reading data from or writing data to a tag. **Required permissions**: ohos.permission.NFC_TAG @@ -68,9 +69,32 @@ Resets the connection to this tag and restores the default timeout duration for ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let reset = tag.getXXXTag(taginfo).reset(); -console.log("reset:" +reset); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let connectStatus = tag.getIsoDep(tagInfo).connectTag(); +console.log("connectStatus: " + connectStatus); +``` + +### tagSession.reset() + +reset(): void + +Resets the connection to this tag. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +tag.getIsoDep(tagInfo).reset(); ``` ### tagSession.isTagConnected @@ -94,16 +118,18 @@ Checks whether the tag is connected. ```js import tag from '@ohos.nfc.tag'; -// tagInfo is an object given by the NFC service when a tag is dispatched. -let isTagConnected = tag.getXXXTag(taginfo).isTagConnected(); -console.log("isTagConnected:" +isTagConnected); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let isTagConnected = tag.getIsoDep(tagInfo).isTagConnected(); +console.log("isTagConnected: " + isTagConnected); ``` ### tagSession.getMaxSendLength getMaxSendLength(): number -Obtains the maximum length of the data that can be sent to the tag. +Obtains the maximum length of the data that can be sent to this tag. **Required permissions**: ohos.permission.NFC_TAG @@ -113,14 +139,167 @@ Obtains the maximum length of the data that can be sent to the tag. | **Type**| **Description** | | ------------------ | --------------------------| -| number | Maximum data length obtained.| +| number | Maximum data length obtained. The value cannot be a negative number.| + +**Example** +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let maxSendLen = tag.getIsoDep(tagInfo).getMaxSendLength(); +console.log("tag maxSendLen: " + maxSendLen); +``` + +### tagSession.getSendDataTimeout + +getSendDataTimeout(): number + +Obtains the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| number | Timeout period obtained, in milliseconds. The value cannot be a negative number.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let sendDataTimeout = tag.getIsoDep(tagInfo).getSendDataTimeout(); +console.log("tag sendDataTimeout: " + sendDataTimeout); +``` + +### tagSession.setSendDataTimeout + +setSendDataTimeout(timeout: number): boolean + +Sets the timeout period for sending data to this tag, in milliseconds. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| timeout | number | Yes| Timeout period to set, in milliseconds. The value cannot be a negative number.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| boolean | Returns **true** if the timeout period is set successfully; returns **false** otherwise.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +let timeoutMs = 700; // Change it as required. +let setStatus = tag.getIsoDep(tagInfo).setSendDataTimeout(timeoutMs); +console.log("tag setSendDataTimeout setStatus: " + setStatus); +``` + +### tagSession.sendData + +sendData(data: number[]): Promise + +Sends data to this tag. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Return value** + +| **Type**| **Description** | +| ------------------ | --------------------------| +| Promise | Promise used to return the response from the tag. The response consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| + +**Example** + +```js +import tag from '@ohos.nfc.tag'; + +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData).then((response) => { + console.log("tagSession sendData Promise response: " + response); +}).catch((err)=> { + console.log("tagSession sendData Promise err: " + err); +}); +``` + +### tagSession.sendData + +sendData(data: number[], callback: AsyncCallback): void + +Sends data to this tag. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.NFC_TAG + +**System capability**: SystemCapability.Communication.NFC.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------------------- | +| data | number[] | Yes| Data to send. The data consists of hexadecimal numbers ranging from **0x00** to **0xFF**.| +| callback | AsyncCallback | Yes| Callback invoked to return the response from the tag. The response consists of hexadecimal numbers 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 mazSendLen = tag.getXXXTag(taginfo).getMaxSendLength(); -console.log("mazSendLen:" +mazSendLen); +// tagInfo is an object provided by the NFC service when a tag is dispatched. +// getXXX can be getIsoDep, getNdef, getMifareClassic, or any other getter for NFC tags. + +// Connect to the tag if it is not connected. +if (!tag.getIsoDep(tagInfo).isTagConnected()) { + if (!tag.getIsoDep(tagInfo).connectTag()) { + console.log("tagSession connectTag failed."); + return; + } +} + +let cmdData = [0x01, 0x02, 0x03, 0x04]; // Change it as required. +tag.getIsoDep(tagInfo).sendData(cmdData, (err, response)=> { + if (err) { + console.log("tagSession sendData AsyncCallback err: " + err); + } else { + console.log("tagSession sendData AsyncCallback response: " + response); + } +}); ``` 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 a8ea022b24881bd1def701d3c59433270b0da762..f1c9ad362175bd709d27bc4c7aec0059b413221e 100644 --- a/en/application-dev/reference/apis/js-apis-telephony-data.md +++ b/en/application-dev/reference/apis/js-apis-telephony-data.md @@ -1,6 +1,6 @@ -# Cellular Data +# @ohos.telephony.data (Cellular Data) -The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. +The **data** module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled. >**NOTE** > @@ -18,8 +18,6 @@ getDefaultCellularDataSlotId(callback: AsyncCallback\): void Obtains the default slot of the SIM card used for mobile data. This API uses an asynchronous callback to return the result. -**Required permission**: ohos.permission.GET_NETWORK_INFO - **System capability**: SystemCapability.Telephony.CellularData **Parameters** @@ -42,8 +40,6 @@ getDefaultCellularDataSlotId(): Promise\ Obtains the default slot of the SIM card used for mobile data. This API uses a promise to return the result. -**Required permission**: ohos.permission.GET_NETWORK_INFO - **System capability**: SystemCapability.Telephony.CellularData **Return value** @@ -63,14 +59,12 @@ promise.then((data) => { }); ``` -## data.getDefaultCellularDataSlotIdSync +## data.getDefaultCellularDataSlotIdSync9+ getDefaultCellularDataSlotIdSync(): number Obtains the default SIM card used for mobile data synchronously. -**Required permission**: ohos.permission.GET_NETWORK_INFO - **System capability**: SystemCapability.Telephony.CellularData **Return value** @@ -85,7 +79,6 @@ Obtains the default SIM card used for mobile data synchronously. console.log("Result: "+ data.getDefaultCellularDataSlotIdSync()) ``` - ## data.setDefaultCellularDataSlotId setDefaultCellularDataSlotId(slotId: number, callback: AsyncCallback\): void @@ -102,8 +95,8 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| -| callback | AsyncCallback\ | Yes | Callback used to return the result. | +| slotId | number | Yes | SIM card slot ID.
**0**: card slot 1
**1**: card slot 2
**-1**: Clears the default configuration.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -129,13 +122,13 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------------------------------------ | -| slotId | number | Yes | SIM card slot ID.
- **0**: card slot 1
- **1**: card slot 2
- **-1**: clearing the default configuration| +| slotId | number | Yes | SIM card slot ID.
**0**: card slot 1
**1**: card slot 2
**-1**: Clears the default configuration.| **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise<\void\> | Promise used to return the result. | +| Type | Description | +| --------------- | ------------------------------- | +| Promise\ | Promise used to return the result.| **Example** @@ -199,7 +192,7 @@ promise.then((data) => { getCellularDataState(callback: AsyncCallback\): void -Obtains the connection status of the PS domain. This API uses an asynchronous callback to return the result. +Obtains the connection status of the packet switched (PS) domain. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CellularData @@ -256,7 +249,7 @@ Checks whether the cellular data service is enabled. This API uses an asynchrono | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------------------------------------------------------ | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: The cellular data service is enabled.
- **false**: The cellular data service is disabled.| +| callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: The cellular data service is enabled.
**false**: The cellular data service is disabled.| **Example** @@ -280,7 +273,7 @@ Checks whether the cellular data service is enabled. This API uses a promise to | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
- **true**: The cellular data service is enabled.
- **false**: The cellular data service is disabled.| +| Promise\ | Promise used to return the result.
**true**: The cellular data service is enabled.
**false**: The cellular data service is disabled.| **Example** @@ -297,7 +290,7 @@ promise.then((data) => { isCellularDataRoamingEnabled(slotId: number, callback: AsyncCallback\): void -Checks whether the cellular data roaming service is enabled. This API uses an asynchronous callback to return the result. +Checks whether roaming is enabled for the cellular data service. This API uses an asynchronous callback to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -308,7 +301,7 @@ Checks whether the cellular data roaming service is enabled. This API uses an as | Name | Type | Mandatory| Description | | -------- | ------------------------ | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
**0**: card slot 1
**1**: card slot 2 | -| callback | AsyncCallback\ | Yes | Callback used to return the result.
- **true**: The cellular data roaming service is enabled.
- **false**: The cellular data roaming service is disabled. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.
**true**: Roaming is enabled for the cellular data service.
**false**: Roaming is disabled for the cellular data service.| **Example** @@ -322,7 +315,7 @@ data.isCellularDataRoamingEnabled(0, (err, data) => { isCellularDataRoamingEnabled(slotId: number): Promise\ -Checks whether the cellular data roaming service is enabled. This API uses a promise to return the result. +Checks whether roaming is enabled for the cellular data service. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -338,7 +331,7 @@ Checks whether the cellular data roaming service is enabled. This API uses a pro | Type | Description | | ------------------ | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result.
- **true**: The cellular data roaming service is enabled.
- **false**: The cellular data roaming service is disabled.| +| Promise\ | Promise used to return the result.
**true**: Roaming is enabled for the cellular data service.
**false**: Roaming is disabled for the cellular data service.| **Example** @@ -585,7 +578,6 @@ promise.then((data) => { }); ``` - ## DataFlowType Defines the cellular data flow type. @@ -602,14 +594,14 @@ Defines the cellular data flow type. ## DataConnectState -Describes the connection status of a cellular data connection. +Describes the connection status of a cellular data link. **System capability**: SystemCapability.Telephony.CellularData | Name | Value | Description | | ----------------------- | ---- | -------------------------- | -| DATA_STATE_UNKNOWN | -1 | The status of the cellular data connection is unknown. | -| DATA_STATE_DISCONNECTED | 0 | The cellular data connection is disconnected. | -| DATA_STATE_CONNECTING | 1 | The cellular data connection is being established.| -| DATA_STATE_CONNECTED | 2 | The cellular data connection is established. | -| DATA_STATE_SUSPENDED | 3 | The cellular data connection is suspended. | +| DATA_STATE_UNKNOWN | -1 | The status of the cellular data link is unknown. | +| DATA_STATE_DISCONNECTED | 0 | The cellular data link is disconnected. | +| DATA_STATE_CONNECTING | 1 | The cellular data link is being connected.| +| DATA_STATE_CONNECTED | 2 | The cellular data link is connected. | +| DATA_STATE_SUSPENDED | 3 | The cellular data link is suspended. | diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md index b7b7e08a0a6a5a82a8813aad1f9d2010ff899a50..514e7062cd649d8bf5b92261bceeb7cbed870166 100644 --- a/en/application-dev/reference/apis/js-apis-thermal.md +++ b/en/application-dev/reference/apis/js-apis-thermal.md @@ -1,11 +1,9 @@ -# Thermal Manager +# @ohos.thermal (Thermal Management) -> **NOTE** -> -> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. - -This module provides thermal level-related callback and query APIs to obtain the information required for thermal control. +The **thermal** module provides thermal level-related callback and query APIs to obtain the information required for thermal control. +> **NOTE**
+> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -13,78 +11,168 @@ This module provides thermal level-related callback and query APIs to obtain the import thermal from '@ohos.thermal'; ``` +## thermal.registerThermalLevelCallback9+ -## ThermalLevel +registerThermalLevelCallback(callback: Callback<ThermalLevel>): void -Represents the thermal level. +Subscribes to thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager -| Name | Default Value | Description | -| ---------- | ---- | ---------------------------------------- | -| COOL | 0 | The device is cool, and services are not restricted.| -| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.| -| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.| -| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.| -| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.| -| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.| -| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------ | +| callback | Callback<ThermalLevel> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + thermal.registerThermalLevelCallback(level => { + console.info('thermal level is: ' + level); + }); + console.info('register thermal level callback success.'); +} catch(err) { + console.error('register thermal level callback failed, err: ' + err); +} +``` + +## thermal.unregisterThermalLevelCallback9+ + +unregisterThermalLevelCallback(callback?: Callback\): void + +Unsubscribes from thermal level changes. + +**System capability:** SystemCapability.PowerManager.ThermalManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------------------------- | +| callback | Callback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** +```js +try { + thermal.unregisterThermalLevelCallback(() => { + console.info('unsubscribe thermal level success.'); + }); + console.info('unregister thermal level callback success.'); +} catch(err) { + console.error('unregister thermal level callback failed, err: ' + err); +} +``` + +## thermal.getLevel9+ + +getLevel(): ThermalLevel + +Obtains the current thermal level. + +**System capability:** SystemCapability.PowerManager.ThermalManager + +**Return value** + +| Type | Description | +| ------------ | ------------ | +| ThermalLevel | Thermal level obtained.| + +**Error codes** + +For details about the error codes, see [Thermal Manager Error Codes](../errorcodes/errorcode-thermal.md). + +| Code | Error Message | +|---------|---------| +| 4800101 | Operation failed. Cannot connect to service.| + +**Example** + +```js +try { + var level = thermal.getLevel(); + console.info('thermal level is: ' + level); +} catch(err) { + console.error('get thermal level failed, err: ' + err); +} +``` -## thermal.subscribeThermalLevel +## thermal.subscribeThermalLevel(deprecated) subscribeThermalLevel(callback: AsyncCallback<ThermalLevel>): void +> This API is deprecated since API version 9. You are advised to use [thermal.registerThermalLevelCallback](#thermalregisterthermallevelcallback9) instead. + Subscribes to thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | --------------------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to obtain the return value.
The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<ThermalLevel> | Yes | Callback used to return the result. The return value contains only one parameter, that is, thermal level. If an alarm is generated, you can use `// @ts-ignore` to suppress the alarm.| **Example** ```js -var lev = 0; -thermal.subscribeThermalLevel((lev) => { - console.info("Thermal level is: " + lev); -}) +thermal.subscribeThermalLevel((level) => { + console.info('thermal level is: ' + level); +}); ``` -## thermal.unsubscribeThermalLevel +## thermal.unsubscribeThermalLevel(deprecated) unsubscribeThermalLevel(callback?: AsyncCallback\): void +> This API is deprecated since API version 9. You are advised to use [thermal.unregisterThermalLevelCallback](#thermalunregisterthermallevelcallback9) instead. + Unsubscribes from thermal level changes. **System capability:** SystemCapability.PowerManager.ThermalManager **Parameters** -| Name | Type | Mandatory | Description | -| -------- | ------------------------- | ---- | --------------------- | -| callback | AsyncCallback<void> | No | Callback without a return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------- | +| callback | AsyncCallback<void> | No | Callback used to return the result. No value is returned. If this parameter is not set, this API unsubscribes from all callbacks.| **Example** ```js thermal.unsubscribeThermalLevel(() => { - console.info("Unsubscribe completed."); + console.info('unsubscribe thermal level success.'); }); ``` -## thermal.getThermalLevel +## thermal.getThermalLevel(deprecated) getThermalLevel(): ThermalLevel +> This API is deprecated since API version 9. You are advised to use [thermal.getLevel](#thermalgetlevel9) instead. + Obtains the current thermal level. **System capability:** SystemCapability.PowerManager.ThermalManager -**Return value**: +**Return value** | Type | Description | | ------------ | ------ | @@ -93,6 +181,22 @@ Obtains the current thermal level. **Example** ```js -var lev = thermal.getThermalLevel(); -console.info("Thermal level is: " + lev); +var level = thermal.getThermalLevel(); +console.info('thermal level is: ' + level); ``` + +## ThermalLevel + +Represents the thermal level. + +**System capability:** SystemCapability.PowerManager.ThermalManager + +| Name | Value | Description | +| ---------- | ---- | ------------------------------------------------------------ | +| COOL | 0 | The device is cool, and services are not restricted. | +| NORMAL | 1 | The device is operational but is not cool. You need to pay attention to its heating.| +| WARM | 2 | The device is warm. You need to stop or delay some imperceptible services.| +| HOT | 3 | The device is heating up. You need to stop all imperceptible services and downgrade or reduce the load of other services.| +| OVERHEATED | 4 | The device is overheated. You need to stop all imperceptible services and downgrade or reduce the load of major services.| +| WARNING | 5 | The device is overheated and is about to enter the emergency state. You need to stop all imperceptible services and downgrade major services to the maximum extent.| +| EMERGENCY | 6 | The device has entered the emergency state. You need to stop all services except those for the emergency help purposes.| diff --git a/en/application-dev/reference/apis/js-apis-timer.md b/en/application-dev/reference/apis/js-apis-timer.md index cf8ca596bd72517835c6bd277c0bf29ebf2b7213..f1fabcf335ead87b35304549ac60efd765f9ff42 100644 --- a/en/application-dev/reference/apis/js-apis-timer.md +++ b/en/application-dev/reference/apis/js-apis-timer.md @@ -8,7 +8,7 @@ The **Timer** module provides basic timer capabilities. You can use the APIs of ## setTimeout -setTimeout(handler[,delay[,…args]]): number +setTimeout(handler: Function | string, delay?: number, ...arguments: any[]): number Sets a timer for the system to call a function after the timer goes off. @@ -18,9 +18,9 @@ Sets a timer for the system to call a function after the timer goes off. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| handler | Function | Yes| Function to be called after the timer goes off.| +| handler | Function \| string | Yes| Function to be called after the timer goes off.| | delay | number | No| Number of milliseconds delayed before the execution. If this parameter is left empty, the default value **0** is used, which means that the execution starts immediately or as soon as possible.| -| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| +| ...arguments | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| **Return value** @@ -71,7 +71,7 @@ Cancels the timer created via **setTimeout()**. ## setInterval -setInterval(handler[, delay[, ...args]]): number +setInterval(handler: Function | string, delay: number, ...arguments: any[]): number Sets a repeating timer for the system to repeatedly call a function at a fixed interval. @@ -81,9 +81,9 @@ Sets a repeating timer for the system to repeatedly call a function at a fixed i | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| handler | Function | Yes| Function to be called repeatedly.| -| delay | number | No| Number of milliseconds delayed before the execution.| -| ...args | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| +| handler | Function \| string | Yes| Function to be called repeatedly.| +| delay | number | Yes| Number of milliseconds delayed before the execution.| +| ...arguments | Array<any> | No| Additional parameters to pass to the handler after the timer goes off.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md index 05a6e52c9d6f1e402dc9a7e3d8d4a19c9a117ec3..ae49b428e00c4c22ed126ecc539290a692b69696 100644 --- a/en/application-dev/reference/apis/js-apis-touchevent.md +++ b/en/application-dev/reference/apis/js-apis-touchevent.md @@ -1,6 +1,6 @@ -# Touch Event +# @ohos.multimodalInput.touchEvent (Touch Event) -Represents touch events reported by an input device. +The **touchEvent** module provides touch events reported by an input device. > **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. @@ -15,37 +15,37 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| CANCEL | number | Yes| No| Cancellation of the touch action.| -| DOWN | number | Yes| No| Pressing of touch.| -| MOVE | number | Yes| No| Moving of touch.| -| UP | number | Yes| No| Lifting of touch.| +| Name | Value | Description | +| ------ | ----- | ----------- | +| CANCEL | 0 | Cancellation of the touch action.| +| DOWN | 1 | Pressing of touch. | +| MOVE | 2 | Moving of touch. | +| UP | 3 | Lifting of touch. | ## ToolType **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| FINGER | number | Yes| No| Finger| -| PEN | number | Yes| No| Pen| -| RUBBER | number | Yes| No| Eraser| -| BRUSH | number | Yes| No| Brush| -| PENCIL | number | Yes| No| Pencil| -| AIRBRUSH | number | Yes| No| Air brush| -| MOUSE | number | Yes| No| Mouse| -| LENS | number | Yes| No| Lens| +| Name | Value | Description | +| ---- | ----- | ----------- | +| FINGER | 0 | Finger| +| PEN | 1 | Pen| +| RUBBER | 2 | Eraser| +| BRUSH | 3 | Brush| +| PENCIL | 4 | Pencil| +| AIRBRUSH | 5 | Air brush| +| MOUSE | 6 | Mouse| +| LENS | 7 | Lens| ## SourceType **System capability**: SystemCapability.MultimodalInput.Input.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| TOUCH_SCREEN | number | Yes| No| Touchscreen| -| PEN | number | Yes| No| Stylus| -| TOUCH_PAD | number | Yes| No| Touchpad| +| Name | Value | Description | +| ---- | ----- | ----------- | +| TOUCH_SCREEN | 0 | Touchscreen| +| PEN | 1 | Stylus | +| TOUCH_PAD | 2 | Touchpad | ## Touch @@ -70,7 +70,7 @@ import {Action,ToolType,SourceType,Touch,TouchEvent} from '@ohos.multimodalInput | toolHeight | number | Yes| No| Height of the tool area.| | rawX | number | Yes| No| X coordinate of the input device.| | rawY | number | Yes| No| Y coordinate of the input device.| -| toolType | number | Yes| No| Tool type.| +| toolType | ToolType | Yes| No| Tool type.| ## TouchEvent diff --git a/en/application-dev/reference/apis/js-apis-treemap.md b/en/application-dev/reference/apis/js-apis-treemap.md index e2a41d26819c96d3ef4321bfaf9a0e9f058300c9..eb874f0abd94f72f56f0e1e13a23883e1ae14ce8 100644 --- a/en/application-dev/reference/apis/js-apis-treemap.md +++ b/en/application-dev/reference/apis/js-apis-treemap.md @@ -1,7 +1,6 @@ -# Nonlinear Container TreeMap +# @ohos.util.TreeMap (Nonlinear Container TreeMap) > **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. **TreeMap** stores key-value (KV) pairs. Each key must be unique and have only one value. @@ -49,7 +48,7 @@ A constructor used to create a **TreeMap** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -59,11 +58,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeMap = new TreeMap(); -try { - let treeMap2 = TreeMap(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -83,7 +77,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -94,11 +88,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const treeMap = new TreeMap(); let result = treeMap.isEmpty(); -try { - treeMap.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -124,7 +113,7 @@ Checks whether this container has the specified key. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -137,11 +126,6 @@ let treeMap = new TreeMap(); let result = treeMap.hasKey("squirrel"); treeMap.set("squirrel", 123); let result1 = treeMap.hasKey("squirrel"); -try { - treeMap.hasKey.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -167,7 +151,7 @@ Checks whether this container has the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -180,11 +164,6 @@ let treeMap = new TreeMap(); let result = treeMap.hasValue(123); treeMap.set("squirrel", 123); let result1 = treeMap.hasValue(123); -try { - treeMap.hasValue.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -210,7 +189,7 @@ Obtains the value of the specified key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -223,11 +202,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.get("sparrow"); -try { - treeMap.get.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -247,7 +221,7 @@ Obtains the first key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -260,11 +234,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getFirstKey(); -try { - treeMap.getFirstKey.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -284,7 +253,7 @@ Obtains the last key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -297,11 +266,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let result = treeMap.getLastKey(); -try { - treeMap.getLastKey.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -317,11 +281,11 @@ Adds all elements in a **TreeMap** instance to this container. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| map | TreeMap | Yes| **TreeMap** instance whose elements are to be added to the current container.| +| map | TreeMap | Yes| **TreeMap** object to be added to the container.| **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -334,12 +298,11 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); let map = new TreeMap(); -treeMap.setAll(map); -try { - treeMap.setAll.bind({}, map)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} +map.set("demo", 12); +map.setAll(treeMap); // Add all elements in the treeMap to the map. +map.forEach((value, key) => { + console.log("test" + value, key); // Print result: 12 demo, 356 sparrow, and 123 squirrel +}) ``` @@ -366,7 +329,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -377,11 +340,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeMap = new TreeMap(); treeMap.set("squirrel", 123); -try { - treeMap.set.bind({}, "squirrel", 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -407,7 +365,7 @@ Removes the element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -420,11 +378,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.remove("sparrow"); -try { - treeMap.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -450,7 +403,7 @@ Obtains the key that is placed in front of the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -464,11 +417,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getLowerKey("sparrow"); -try { - treeMap.getLowerKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -494,7 +442,7 @@ Obtains the key that is placed next to the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -508,11 +456,6 @@ treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.set("gander", 356); let result = treeMap.getHigherKey("sparrow"); -try { - treeMap.getHigherKey.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### replace @@ -538,7 +481,7 @@ Replaces an element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -550,11 +493,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er let treeMap = new TreeMap(); treeMap.set("sparrow", 123); let result = treeMap.replace("sparrow", 357); -try { - treeMap.replace.bind({}, "sparrow", 357)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -568,7 +506,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -581,11 +519,6 @@ let treeMap = new TreeMap(); treeMap.set("squirrel", 123); treeMap.set("sparrow", 356); treeMap.clear(); -try { - treeMap.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -605,7 +538,7 @@ Obtains an iterator that contains all the keys in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -623,11 +556,6 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeMap.keys.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -647,7 +575,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -665,17 +593,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeMap.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void +forEach(callbackFn: (value?: V, key?: K, map?: TreeMap) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -685,7 +608,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -697,7 +620,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -712,13 +635,6 @@ treeMap.set("gull", 357); treeMap.forEach((value, key) => { console.log("value:" + value, key); }); -try { - treeMap.forEach.bind({}, (value, key) => { - console.log("value:" + value, key); - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -738,7 +654,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -757,11 +673,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeMap.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -780,7 +691,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -807,9 +718,4 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeMap[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-treeset.md b/en/application-dev/reference/apis/js-apis-treeset.md index ef10035349bf185462f803ad967270e79b8cc93d..4aaaac1861ceffdfda3d7adc53b16181c42cc9c3 100644 --- a/en/application-dev/reference/apis/js-apis-treeset.md +++ b/en/application-dev/reference/apis/js-apis-treeset.md @@ -1,7 +1,6 @@ -# Nonlinear Container TreeSet +# @ohos.util.TreeSet (Nonlinear Container TreeSet) > **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. **TreeSet** is implemented based on **[TreeMap](js-apis-treemap.md)**. In **TreeSet**, only **value** objects are processed. **TreeSet** can be used to store values, each of which must be unique. @@ -46,7 +45,7 @@ A constructor used to create a **TreeSet** instance. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -56,11 +55,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeSet = new TreeSet(); -try { - let treeSet2 = TreeSet(); -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -80,7 +74,7 @@ Checks whether this container is empty (contains no element). **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -91,11 +85,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts const treeSet = new TreeSet(); let result = treeSet.isEmpty(); -try { - treeSet.isEmpty.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -121,7 +110,7 @@ Checks whether this container has the specified value. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -134,11 +123,6 @@ let treeSet = new TreeSet(); treeSet.has(123); treeSet.add(123); let result1 = treeSet.has(123); -try { - treeSet.has.bind({}, 123)(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -158,7 +142,7 @@ Obtains the value of the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -171,11 +155,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getFirstValue(); -try { - treeSet.getFirstValue.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -195,7 +174,7 @@ Obtains the value of the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -208,11 +187,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.getLastValue(); -try { - treeSet.getLastValue.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -238,7 +212,7 @@ Adds an element to this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -249,11 +223,6 @@ For details about the error codes, see [containers Error Codes](../errorcodes/er ```ts let treeSet = new TreeSet(); let result = treeSet.add("squirrel"); -try { - treeSet.add.bind({}, "squirrel")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -279,7 +248,7 @@ Removes the element with the specified key from this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -292,11 +261,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.remove("sparrow"); -try { - treeSet.remove.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -322,7 +286,7 @@ Obtains the value that is placed in front of the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -336,11 +300,6 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getLowerValue("sparrow"); -try { - treeSet.getLowerValue.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -366,7 +325,7 @@ Obtains the value that is placed next to the input key in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -380,11 +339,6 @@ treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.add("gander"); let result = treeSet.getHigherValue("sparrow"); -try { - treeSet.getHigherValue.bind({}, "sparrow")(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -404,7 +358,7 @@ Removes the first element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -417,11 +371,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popFirst(); -try { - treeSet.popFirst.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -441,7 +390,7 @@ Removes the last element in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -454,11 +403,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); let result = treeSet.popLast(); -try { - treeSet.popLast.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -472,7 +416,7 @@ Clears this container and sets its length to **0**. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -485,11 +429,6 @@ let treeSet = new TreeSet(); treeSet.add("squirrel"); treeSet.add("sparrow"); treeSet.clear(); -try { - treeSet.clear.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -509,7 +448,7 @@ Obtains an iterator that contains all the values in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -527,17 +466,12 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeSet.values.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` ### forEach -forEach(callbackfn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void +forEach(callbackFn: (value?: T, key?: T, set?: TreeSet<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -547,7 +481,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the elements in the container.| +| callbackFn | function | Yes| Callback invoked to traverse the elements in the container.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -559,7 +493,7 @@ callbackfn **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -574,13 +508,6 @@ treeSet.add("gull"); treeSet.forEach((value, key) => { console.log("value:" + value, key) }); -try { - treeSet.forEach.bind({}, (value, key) => { - console.log("value:" + value, key) - })(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -600,7 +527,7 @@ Obtains an iterator that contains all the elements in this container. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -619,11 +546,6 @@ while(temp != undefined) { console.log("value:" + temp[1]); temp = iter.next().value; } -try { - treeSet.entries.bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` @@ -643,7 +565,7 @@ Obtains an iterator, each item of which is a JavaScript object. **Error codes** -For details about the error codes, see [containers Error Codes](../errorcodes/errorcode-containers.md). +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). | ID| Error Message| | -------- | -------- | @@ -668,9 +590,4 @@ while(temp != undefined) { console.log("value:" + temp); temp = iter.next().value; } -try { - treeSet[Symbol.iterator].bind({})(); // bind() creates a new bound function that, when called, has its this keyword set to the provided value. It is used to test exception capture. -} catch(err) { - console.log(`${err.code} - ${err.name} - ${err.message}`); -} ``` diff --git a/en/application-dev/reference/apis/js-apis-uitest.md b/en/application-dev/reference/apis/js-apis-uitest.md index 6586d6f0a2c7fc5641a5b49411f67390859e3bfe..d4b84b0d938725bb069cc482b29ce94c9c3c3bd4 100644 --- a/en/application-dev/reference/apis/js-apis-uitest.md +++ b/en/application-dev/reference/apis/js-apis-uitest.md @@ -1,82 +1,161 @@ -# UiTest +# @ohos.uitest ->**NOTE**
The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **UiTest** module provides APIs that you can use to simulate UI actions during testing, such as clicks, double-clicks, long-clicks, and swipes. + +This module provides the following functions: + +- [On9+](#on9): provides UI component feature description APIs for component filtering and matching. +- [Component9+](#component9): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. +- [Driver9+](#driver9): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. +- [UiWindow9+](#uiwindow9): works as the entry class and provides APIs for obtaining window attributes, dragging windows, and adjusting window sizes. +- [By(deprecated)](#bydeprecated): provides UI component feature description APIs for component filtering and matching. This API is deprecated since API version 9. You are advised to use [On9+](#on9) instead. +- [UiComponent(deprecated)](#uicomponentdeprecated): represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. This API is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. +- [UiDriver(deprecated)](#uidriverdeprecated): works as the entry class and provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. This API is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. + +>**NOTE** > +>The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` -import {UiDriver,BY,MatchPattern} from '@ohos.uitest' +```js +import {UiComponent, UiDriver, Component, Driver, UiWindow, ON, BY, MatchPattern, DisplayRotation, ResizeDirection, WindowMode, PointerMatrix} from '@ohos.uitest'; ``` -## By +## MatchPattern -The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components.
-The API capabilities provided by the **By** class exhibit the following features:
1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component.
2. Provide multiple match patterns for component attributes.
3. Support absolute positioning and relative positioning for components. APIs such as [By.isBefore](#byisbefore) and [By.isAfter](#byisafter) can be used to specify the features of adjacent components to assist positioning.
All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode. +Enumerates the match patterns supported for component attributes. -```js -BY.text('123').type('button') -``` +**System capability**: SystemCapability.Test.UiTest -### By.text +| Name | Value | Description | +| ----------- | ---- | -------------- | +| EQUALS | 0 | Equal to the given value. | +| CONTAINS | 1 | Contains the given value. | +| STARTS_WITH | 2 | Starts with the given value.| +| ENDS_WITH | 3 | Ends with the given value.| -text(txt: string, pattern?: MatchPattern): By +## ResizeDirection9+ -Specifies the text attribute of the target component. Multiple match patterns are supported. +Enumerates the directions in which a window can be resized. **System capability**: SystemCapability.Test.UiTest -**Parameters** +| Name | Value | Description | +| ---------- | ---- | -------- | +| LEFT | 0 | Left. | +| RIGHT | 1 | Right. | +| UP | 2 | Up. | +| DOWN | 3 | Down. | +| LEFT_UP | 4 | Upper left.| +| LEFT_DOWN | 5 | Lower left.| +| RIGHT_UP | 6 | Upper right.| +| RIGHT_DOWN | 7 | Lower right.| -| Name | Type | Mandatory| Description | -| ------- | ------------ | ---- | ------------------------------------------------- | -| txt | string | Yes | Component text, used to match the target component. | -| pattern | MatchPattern | No | Match pattern. The default value is [EQUALS](#matchpattern).| +## Point9+ -**Return value** +Provides the coordinates of a point. -| Type| Description | -| ---- | -------------- | -| By | Returns the **By** object itself.| +**System capability**: SystemCapability.Test.UiTest -**Example** +| Name| Type | Readable| Writable| Description | +| ---- | ------ | ---- | ---- | ---------------- | +| X | number | Yes | No | X-coordinate of a point.| +| Y | number | Yes | No | Y-coordinate of a point.| + +## Rect9+ + +Provides bounds information of a component. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Type | Readable| Writable| Description | +| ------- | ------ | ---- | ---- | ------------------------- | +| leftX | number | Yes | No | X-coordinate of the upper left corner of the component bounds.| +| topY | number | Yes | No | Y-coordinate of the upper left corner of the component bounds.| +| rightX | number | Yes | No | X-coordinate of the lower right corner of the component bounds.| +| bottomY | number | Yes | No | Y-coordinate of the lower right corner of the component bounds.| + +## WindowMode9+ + +**System capability**: SystemCapability.Test.UiTest + +Enumerates the window modes. + +| Name | Value | Description | +| ---------- | ---- | ---------- | +| FULLSCREEN | 0 | Full-screen mode.| +| PRIMARY | 1 | Primary window mode. | +| SECONDARY | 2 | Secondary window mode.| +| FLOATING | 3 | Floating window mode.| + +## DisplayRotation9+ + +**System capability**: SystemCapability.Test.UiTest + +Describes the display rotation of the device. + +| Name | Value | Description | +| ------------ | ---- | ---------------------------------------- | +| ROTATION_0 | 0 | The device display is not rotated and is in its original vertical orientation. | +| ROTATION_90 | 1 | The device display rotates 90° clockwise and is in landscape orientation. | +| ROTATION_180 | 2 | The device display rotates 180° clockwise and is in reverse vertical orientation.| +| ROTATION_270 | 3 | The device display rotates 270° clockwise and is in reverse landscape orientation.| + +## WindowFilter9+ + +Provides the flag attributes of this window. + +**System capability**: SystemCapability.Test.UiTest + +| Name | Type | Readable| Writable| Description | +| ---------- | ------- | ---- | ---- | -------------------------- | +| bundleName | string | Yes | No | Bundle name of the application to which the window belongs. | +| title | string | Yes | No | Title of the window. | +| focused | boolean | Yes | No | Whether the window is in focused state. | +| actived | boolean | Yes | No | Whether the window is interacting with the user.| + +## On9+ + +Since API version 9, the UiTest framework provides a wide range of UI component feature description APIs in the **On** class to filter and match components. +The API capabilities provided by the **On** class exhibit the following features: 1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component.
2. Provide multiple match patterns for component attributes.
3. Support absolute positioning and relative positioning for components. APIs such as [ON.isBefore](#isbefore) and [ON.isAfter](#isafter) can be used to specify the features of adjacent components to assist positioning.
All APIs provided in the **On** class are synchronous. You are advised to use the static constructor **ON** to create an **On** object in chain mode. ```js -let by = BY.text('123') // Use the static constructor BY to create a By object and specify the text attribute of the target component. +ON.text('123').type('button'); ``` +### text9+ -### By.key - -key(key: string): By +text(txt: string, pattern?: MatchPattern): On -Specifies the key attribute of the target component. +Specifies the text attribute of the target component. Multiple match patterns are supported. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ----------------- | -| key | string | Yes | Component key.| +| Name | Type | Mandatory| Description | +| ------- | ----------------------------- | ---- | --------------------------------------------------- | +| txt | string | Yes | Component text, used to match the target component. | +| pattern | [MatchPattern](#matchpattern) | No | Match pattern. The default value is [EQUALS](#matchpattern).| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ---------------------------------- | +| [On](#on9) | **On** object that matches the text attribute of the target component.| **Example** ```js -let by = BY.key('123') // Use the static constructor BY to create a By object and specify the key attribute of the target component. +let on = ON.text('123'); // Use the static constructor ON to create an On object and specify the text attribute of the target component. ``` -### By.id +### id9+ -id(id: number): By +id(id: string): On Specifies the ID attribute of the target component. @@ -86,24 +165,24 @@ Specifies the ID attribute of the target component. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------- | -| id | number | Yes | Component ID.| +| id | string | Yes | Component ID.| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | -------------------------------- | +| [On](#on9) | **On** object that matches the ID attribute of the target component.| **Example** ```js -let by = BY.id(123) // Use the static constructor BY to create a By object and specify the id attribute of the target component. +let on = ON.id('123'); // Use the static constructor ON to create an On object and specify the ID attribute of the target component. ``` -### By.type +### type9+ -type(tp: string): By +type(tp: string): On Specifies the type attribute of the target component. @@ -117,46 +196,46 @@ Specifies the type attribute of the target component. **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ---------------------------------------- | +| [On](#on9) | **On** object that matches the type attribute of the target component.| **Example** ```js -let by = BY.type('button') // Use the static constructor BY to create a By object and specify the type attribute of the target component. +let on = ON.type('button'); // Use the static constructor ON to create an On object and specify the type attribute of the target component. ``` -### By.clickable +### clickable9+ -clickable(b?: bool): By +clickable(b?: boolean): On -Specifies the clickable attribute of the target component. +Specifies the clickable status attribute of the target component. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------------------- | -| b | bool | No | Clickable status of the target component. The default value is **true**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | No | Clickable status of the target component.
**true**: clickable.
**false**: not clickable.
Default value: **true**| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ------------------------------------------ | +| [On](#on9) | **On** object that matches the clickable status attribute of the target component.| **Example** ```js -let by = BY.clickable(true) // Use the static constructor BY to create a By object and specify the clickable status attribute of the target component. +let on = ON.clickable(true); // Use the static constructor ON to create an On object and specify the clickable status attribute of the target component. ``` -### By.longClickable9+ +### longClickable9+ -longClickable(b?: bool): By +longClickable(b?: boolean): On Specifies the long-clickable status attribute of the target component. @@ -164,26 +243,26 @@ Specifies the long-clickable status attribute of the target component. **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------------ | -| b | bool | No | Long-clickable status of the target component. The default value is **true**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | No | Long-clickable status of the target component.
**true**: long-clickable.
**false**: not long-clickable.
Default value: **true**| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ---------------------------------------------- | +| [On](#on9) | **On** object that matches the long-clickable status attribute of the target component.| **Example** ```js -let by = BY.longClickable(true) // Use the static constructor BY to create a By object and specify the long-clickable status attribute of the target component. +let on = ON.longClickable(true); // Use the static constructor ON to create an On object and specify the long-clickable status attribute of the target component. ``` -### By.scrollable +### scrollable9+ -scrollable(b?: bool): By +scrollable(b?: boolean): On Specifies the scrollable status attribute of the target component. @@ -191,25 +270,25 @@ Specifies the scrollable status attribute of the target component. **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------------------- | -| b | bool | No | Scrollable status of the target component. The default value is **true**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------------------------------- | +| b | boolean | No | Scrollable status of the target component.
**true**: scrollable.
**false**: not scrollable.
Default value: **true**| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ------------------------------------------ | +| [On](#on9) | **On** object that matches the scrollable status attribute of the target component.| **Example** ```js -let by = BY.scrollable(true) // Use the static constructor BY to create a By object and specify the scrollable status attribute of the target component. +let on = ON.scrollable(true); // Use the static constructor ON to create an On object and specify the scrollable status attribute of the target component. ``` -### By.enabled +### enabled9+ -enabled(b?: bool): By +enabled(b?: boolean): On Specifies the enabled status attribute of the target component. @@ -217,25 +296,25 @@ Specifies the enabled status attribute of the target component. **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------ | -| b | bool | No | Enabled status of the target component. The default value is **true**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------------------- | +| b | boolean | No | Enabled status of the target component.
**true**: enabled.
**false**: disabled.
Default value: **true**| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ---------------------------------------- | +| [On](#on9) | **On** object that matches the enabled status attribute of the target component.| **Example** ```js -let by = BY.enabled(true) // Use the static constructor BY to create a By object and specify the enabled status attribute of the target component. +let on = ON.enabled(true); // Use the static constructor ON to create an On object and specify the enabled status attribute of the target component. ``` -### By.focused +### focused9+ -focused(b?: bool): By +focused(b?: boolean): On Specifies the focused status attribute of the target component. @@ -243,25 +322,25 @@ Specifies the focused status attribute of the target component. **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------------- | -| b | bool | No | Focused status of the target component. The default value is **true**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------------------------- | +| b | boolean | No | Focused status of the target component.
**true**: focused.
**false**: not focused.
Default value: **true**| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ---------------------------------------- | +| [On](#on9) | **On** object that matches the focused status attribute of the target component.| **Example** ```js -let by = BY.focused(true) // Use the static constructor BY to create a By object and specify the focused status attribute of the target component. +let on = ON.focused(true); // Use the static constructor ON to create an On object and specify the focused status attribute of the target component. ``` -### By.selected +### selected9+ -selected(b?: bool): By +selected(b?: boolean): On Specifies the selected status attribute of the target component. @@ -269,25 +348,25 @@ Specifies the selected status attribute of the target component. **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------------------- | -| b | bool | No | Selected status of the target component. The default value is **true**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | No | Selected status of the target component.
**true**: selected.
**false**: not selected.
Default value: **true**| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ------------------------------------------ | +| [On](#on9) | **On** object that matches the selected status attribute of the target component.| **Example** ```js -let by = BY.selected(true) // Use the static constructor BY to create a By object and specify the selected status attribute of the target component. +let on = ON.selected(true); // Use the static constructor ON to create an On object and specify the selected status attribute of the target component. ``` -### By.checked9+ +### checked9+ -checked(b?: bool): By +checked(b?: boolean): On Specifies the checked status attribute of the target component. @@ -295,25 +374,25 @@ Specifies the checked status attribute of the target component. **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | --------------------------------- | -| b | bool | No | Checked status of the target component. The default value is **false**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | No | Checked status of the target component.
**true**: checked.
**false**: not checked.
Default value: **false**| **Return value** -| Type| Description | -| ---- | -------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ------------------------------------------ | +| [On](#on9) | **On** object that matches the checked status attribute of the target component.| **Example** ```js -let by = BY.checked(true) // Use the static constructor BY to create a By object and specify the checked status attribute of the target component. +let on = ON.checked(true); // Use the static constructor ON to create an On object and specify the checked status attribute of the target component. ``` -### By.checkable9+ +### checkable9+ -checkable(b?: bool): By +checkable(b?: boolean): On Specifies the checkable status attribute of the target component. @@ -321,25 +400,25 @@ Specifies the checkable status attribute of the target component. **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ------------------------------------- | -| b | bool | No | Checkable status of the target component. The default value is **false**.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | No | Checkable status of the target component.
**true**: checkable.
**false**: not checkable.
Default value: **false**| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | -------------------------------------------- | +| [On](#on9) | **On** object that matches the checkable status attribute of the target component.| **Example** ```js -let by = BY.checkable(true) // Use the static constructor BY to create a By object and specify the checkable status attribute of the target component. +let on = ON.checkable(true); // Use the static constructor ON to create an On object and specify the checkable status attribute of the target component. ``` -### By.isBefore +### isBefore9+ -isBefore(by: By): By +isBefore(on: On): On Specifies the attributes of the component before which the target component is located. @@ -347,25 +426,25 @@ Specifies the attributes of the component before which the target component is l **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------- | -| by | By | Yes | Attributes of the component before which the target component is located.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | Yes | Attributes of the component before which the target component is located.| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ---------------------------------------------------- | +| [On](#on9) | **On** object.| **Example** ```js -let by = BY.isBefore(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component before which the target component is located. +let on = ON.isBefore(ON.text('123')); // Use the static constructor ON to create an On object and specify the attributes of the component before which the target component is located. ``` -### By.isAfter +### isAfter9+ -isAfter(by: By): By +isAfter(on: On): On Specifies the attributes of the component after which the target component is located. @@ -373,41 +452,28 @@ Specifies the attributes of the component after which the target component is lo **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------- | -| by | By | Yes | Attributes of the component before which the target component is located.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | Yes | Attributes of the component after which the target component is located.| **Return value** -| Type| Description | -| ---- | ---------------- | -| By | Returns the **By** object itself.| +| Type | Description | +| ---------- | ---------------------------------------------------- | +| [On](#on9) | **On** object.| **Example** ```js -let by = BY.isAfter(BY.text('123')) // Use the static constructor BY to create a By object and specify the attributes of the component after which the target component is located. +let on = ON.isAfter(ON.text('123')); // Use the static constructor ON to create an On object and specify the attributes of the component after which the target component is located. ``` -## UiComponent +## Component9+ -In **UiTest**, the **UiComponent** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. +In **UiTest** of API version 9, the **Component** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. All APIs provided in this class use a promise to return the result and must be invoked using **await**. -### Rect9+ - -Provides border information of a component. - -**System capability**: SystemCapability.Test.UiTest - -| Name | Type| Readable| Writable| Description | -| ------- | -------- | ---- | ---- | ------------------------- | -| leftX | number | Yes | No | X coordinate of the upper left corner of the component borders.| -| topY | number | Yes | No | Y coordinate of the upper left corner of the component borders.| -| rightX | number | Yes | No | X coordinate of the lower right corner of the component borders.| -| bottomY | number | Yes | No | Y coordinate of the lower right corner of the component borders.| - -### UiComponent.click +### click9+ click(): Promise\ @@ -415,17 +481,26 @@ Clicks this component. **System capability**: SystemCapability.Test.UiTest +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.click() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + await button.click(); } ``` -### UiComponent.doubleClick +### doubleClick9+ doubleClick(): Promise\ @@ -433,17 +508,26 @@ Double-clicks this component. **System capability**: SystemCapability.Test.UiTest +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.doubleClick() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + await button.doubleClick(); } ``` -### UiComponent.longClick +### longClick9+ longClick(): Promise\ @@ -451,19 +535,28 @@ Long-clicks this component. **System capability**: SystemCapability.Test.UiTest +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - await button.longClick() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + await button.longClick(); } ``` -### UiComponent.getId +### getId9+ -getId(): Promise\ +getId(): Promise\ Obtains the ID of this component. @@ -473,43 +566,28 @@ Obtains the ID of this component. | Type | Description | | ---------------- | ------------------------------- | -| Promise\ | Promise used to return the ID of the component.| - -**Example** - -```js -async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let num = await button.getId() -} -``` - -### UiComponent.getKey +| Promise\ | Promise used to return the ID of the component.| -getKey(): Promise\ - -Obtains the key of this component. - -**System capability**: SystemCapability.Test.UiTest +**Error codes** -**Return value** +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). -| Type | Description | -| ---------------- | ------------------------------ | -| Promise\ | Promise used to return the key of the component.| +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let str_key = await button.getKey() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let num = await button.getId(); } ``` -### UiComponent.getText +### getText9+ getText(): Promise\ @@ -523,17 +601,26 @@ Obtains the text information of this component. | ---------------- | --------------------------------- | | Promise\ | Promise used to return the text information of the component.| +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let text = await button.getText() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let text = await button.getText(); } ``` -### UiComponent.getType +### getType9+ getType(): Promise\ @@ -547,17 +634,26 @@ Obtains the type of this component. | ---------------- | ----------------------------- | | Promise\ | Promise used to return the type of the component.| +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let type = await button.getType() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let type = await button.getType(); } ``` -### UiComponent.getBounds9+ +### getBounds9+ getBounds(): Promise\ @@ -567,23 +663,65 @@ Obtains the bounds of this component. **Return value** -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the bounds of the component.| +| Type | Description | +| ------------------------ | ------------------------------------- | +| Promise\<[Rect](#rect9)> | Promise used to return the bounds of the component.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let rect = await button.getBounds(); +} +``` + +### getBoundsCenter9+ + +getBoundsCenter(): Promise\ + +Obtains the information about the center of the bounding box around this component. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------------------- | ----------------------------------------------- | +| Promise\<[Point](#point9)> | Promise used to return the information about the center of the bounding box around the component.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let rect = await button.getBounds() + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let point = await button.getBoundsCenter(); } ``` -### UiComponent.isClickable +### isClickable9+ -isClickable(): Promise\ +isClickable(): Promise\ Obtains the clickable status of this component. @@ -591,57 +729,73 @@ Obtains the clickable status of this component. **Return value** -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the clickable status of the component.| +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that the component is clickable, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isClickable()) { - console.info('This button can be Clicked') - } - else{ - console.info('This button can not be Clicked') + console.info('This button can be Clicked'); + } else { + console.info('This button can not be Clicked'); } } ``` -### UiComponent.isLongClickable9+ +### isLongClickable9+ -isLongClickable(): Promise\ +isLongClickable(): Promise\ -Obtains the long clickable status of this component. +Obtains the long-clickable status of this component. **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ------------------------------------------- | -| Promise\ | Promise used to return the long clickable status of the component.| +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the long-clickable status of the component. The value **true** means that the component is long-clickable, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isLongClickable()) { - console.info('This button can longClick') - } - else{ - console.info('This button can not longClick') + console.info('This button can longClick'); + } else { + console.info('This button can not longClick'); } } ``` -### UiComponent.isChecked9+ +### isChecked9+ -isChecked(): Promise\ +isChecked(): Promise\ Obtains the checked status of this component. @@ -649,57 +803,73 @@ Obtains the checked status of this component. **Return value** -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the checked status of the component.| +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the checked status of the component. The value **true** means that the component is checked, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let checkBox = await driver.findComponent(BY.type('Checkbox')) + let driver = Driver.create(); + let checkBox = await driver.findComponent(ON.type('Checkbox')); if(await checkBox.isChecked) { - console.info('This checkBox is checked') - } - else{ - console.info('This checkBox is not checked') + console.info('This checkBox is checked'); + } else { + console.info('This checkBox is not checked'); } } ``` -### UiComponent.isCheckable9+ +### isCheckable9+ -isCheckable(): Promise\ +isCheckable(): Promise\ -Obtains the checked status of this component. +Obtains the checkable status of this component. **System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| -------------- | ------------------------------------------- | -| Promise\ | Promise used to return the checked status of the component.| +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the checkable status of the component. The value **true** means that the component is checkable, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let checkBox = await driver.findComponent(BY.type('Checkbox')) + let driver = Driver.create(); + let checkBox = await driver.findComponent(ON.type('Checkbox')); if(await checkBox.isCheckable) { - console.info('This checkBox is checkable') - } - else{ - console.info('This checkBox is not checkable') + console.info('This checkBox is checkable'); + } else { + console.info('This checkBox is not checkable'); } } ``` -### UiComponent.isScrollable +### isScrollable9+ -isScrollable(): Promise\ +isScrollable(): Promise\ Obtains the scrollable status of this component. @@ -707,29 +877,37 @@ Obtains the scrollable status of this component. **Return value** -| Type | Description | -| -------------- | ------------------------------------- | -| Promise\ | Promise used to return the scrollable status of the component.| +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that the component is scrollable, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.scrollable(true)) + let driver = Driver.create(); + let scrollBar = await driver.findComponent(ON.scrollable(true)); if(await scrollBar.isScrollable()) { - console.info('This scrollBar can be operated') - } - else{ - console.info('This scrollBar can not be operated') + console.info('This scrollBar can be operated'); + } else { + console.info('This scrollBar can not be operated'); } } ``` -### UiComponent.isEnabled +### isEnabled9+ -isEnabled(): Promise\ +isEnabled(): Promise\ Obtains the enabled status of this component. @@ -737,29 +915,37 @@ Obtains the enabled status of this component. **Return value** -| Type | Description | -| -------------- | ------------------------------- | -| Promise\ | Promise used to return the enabled status of the component.| +| Type | Description | +| ----------------- | ---------------------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the component is enabled, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isEnabled()) { - console.info('This button can be operated') - } - else{ - console.info('This button can not be operated') + console.info('This button can be operated'); + } else { + console.info('This button can not be operated'); } } ``` -### UiComponent.isFocused +### isFocused9+ -isFocused(): Promise\ +isFocused(): Promise\ Obtains the focused status of this component. @@ -767,28 +953,36 @@ Obtains the focused status of this component. **Return value** -| Type | Description | -| -------------- | ----------------------------------- | -| Promise\ | Promise used to return the focused status of the component.| +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the focused status of the component. The value **true** means that the component is focused, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isFocused()) { - console.info('This button is focused') - } - else{ - console.info('This button is not focused') + console.info('This button is focused'); + } else { + console.info('This button is not focused'); } } ``` -### UiComponent.isSelected +### isSelected9+ -isSelected(): Promise\ +isSelected(): Promise\ Obtains the selected status of this component. @@ -796,26 +990,34 @@ Obtains the selected status of this component. **Return value** -| Type | Description | -| -------------- | -------------------- | -| Promise\ | Promise used to return the selected status of the component.| +| Type | Description | +| ----------------- | --------------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the component is selected, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); if(await button.isSelected()) { - console.info('This button is selected') - } - else{ - console.info('This button is not selected') + console.info('This button is selected'); + } else { + console.info('This button is not selected'); } } ``` -### UiComponent.inputText +### inputText9+ inputText(text: string): Promise\ @@ -825,107 +1027,162 @@ Enters text into this component (available for text boxes). **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ---------------- | -| text | string | Yes | Text to enter.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------------------- | +| text | string | Yes | Text to enter, which can contain English and special characters.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let text = await driver.findComponent(BY.text('hello world')) - await text.inputText('123') + let driver = Driver.create(); + let text = await driver.findComponent(ON.text('hello world')); + await text.inputText('123'); } ``` -### UiComponent.clearText9+ +### clearText9+ clearText(): Promise\ -Clears text in this component (available for text boxes). +Clears text in this component. This API is applicable to text boxes. **System capability**: SystemCapability.Test.UiTest +**Error codes** + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let text = await driver.findComponent(BY.text('hello world')) - await text.clearText() + let driver = Driver.create(); + let text = await driver.findComponent(ON.text('hello world')); + await text.clearText(); } ``` -### UiComponent.scrollSearch +### scrollSearch9+ -scrollSearch(by: By): Promise\ +scrollSearch(on: On): Promise\ -Scrolls on this component to search for the target component (applicable to component that support scrolling, such as **\**). +Scrolls on this component to search for the target component. This API is applicable to components that support scrolling. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------- | -| by | By | Yes | Attributes of the target component.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| --------------------- | ------------------------------------- | -| Promise\ | Promise used to return the target component.| +| Type | Description | +| ---------------------------------- | ------------------------------------- | +| Promise\<[Component](#component9)> | Promise used to return the target component.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.type('Scroll')) - let button = await scrollBar.scrollSearch(BY.text('next page')) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('Scroll')); + let button = await scrollBar.scrollSearch(ON.text('next page')); } ``` -### UiComponent.scrollToTop9+ +### scrollToTop9+ -scrollToTop(): Promise\ +scrollToTop(speed?: number): Promise\ -Scrolls to the top of this a component (applicable to component that support scrolling, such as **\**). +Scrolls to the top of this component. This API is applicable to components that support scrolling. **System capability**: SystemCapability.Test.UiTest +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| speed | number | No | Scroll speed, in pixel/s. The value ranges from 200 to 15000. If the set value is not in the range, the default value 600 is used.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.type('Scroll')) - await scrollBar.scrollToTop() + let driver = Driver.create(); + let scrollBar = await driver.findComponent(ON.type('Scroll')); + await scrollBar.scrollToTop(); } ``` -### UiComponent.scrollToBottom9+ +### scrollToBottom9+ -scrollToBottom(): Promise\ +scrollToBottom(speed?: number): Promise\ -Scrolls to the bottom of this a component (applicable to component that support scrolling, such as **\**). +Scrolls to the bottom of this component. This API is applicable to components that support scrolling. **System capability**: SystemCapability.Test.UiTest +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| speed | number | No | Scroll speed, in pixel/s. The value ranges from 200 to 15000. If the set value is not in the range, the default value 600 is used.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + **Example** ```js async function demo() { - let driver = UiDriver.create() - let scrollBar = await driver.findComponent(BY.type('Scroll')) - await scrollBar.scrollToBottom() + let driver = Driver.create(); + let scrollBar = await driver.findComponent(ON.type('Scroll')); + await scrollBar.scrollToBottom(); } ``` -### UiComponent.dragTo9+ +### dragTo9+ -dragTo(target: UiComponent): Promise\ +dragTo(target: Component): Promise\ Drags this component to the target component. @@ -933,275 +1190,438 @@ Drags this component to the target component. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------- | ---- | ---------- | -| target | UiComponent | Yes | Target component.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | ---------- | +| target | [Component](#component9) | Yes | Target component.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.type('button')) - let text = await driver.findComponent(BY.text('hello world')) - await button.dragTo(text) + let driver = Driver.create(); + let button = await driver.findComponent(ON.type('button')); + let text = await driver.findComponent(ON.text('hello world')); + await button.dragTo(text); } ``` -## UiDriver +### pinchOut9+ -The **UiDriver** class is the main entry to the **uitest** test framework. It provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. -All APIs provided by this class, except for **UiDriver.create()**, use a promise to return the result and must be invoked using **await**. +pinchOut(scale: number): Promise\ -### UiDriver.create +Pinches a component to scale it up to the specified ratio. -static create(): UiDriver +**System capability**: SystemCapability.Test.UiTest -Creates a **UiDriver** object and returns the object created. This API is a static API. +**Parameters** -**System capability**: SystemCapability.Test.UiTest +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| scale | number | Yes | Scale factor.| -**Return value** +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). -| Type | Description | -| ------- | ------------------------ | -| UiDrive | Returns the **UiDriver** object created.| +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() -} + let driver = Driver.create(); + let image = await driver.findComponent(ON.type('image')); + await image.pinchOut(1.5); + } ``` -### UiDriver.delayMs +### pinchIn9+ -delayMs(duration: number): Promise\ +pinchIn(scale: number): Promise\ -Delays this **UiDriver** object within the specified duration. +Pinches a component to scale it down to the specified ratio. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ------------ | -| duration | number | Yes | Duration of time.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| scale | number | Yes | Scale factor.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.delayMs(1000) -} + let driver = Driver.create(); + let image = await driver.findComponent(ON.type('image')); + await image.pinchIn(0.5); + } ``` -### UiDriver.findComponent +## Driver9+ -findComponent(by: By): Promise\ +The **Driver** class is the main entry to the UiTest framework. It provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. +All APIs provided by this class, except for **Driver.create()**, use a promise to return the result and must be invoked using **await**. -Searches this **UiDriver** object for the target component that matches the given attributes. +### create9+ -**System capability**: SystemCapability.Test.UiTest +static create(): Driver -**Parameters** +Creates a **Driver** object and returns the object created. This API is a static API. -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------- | -| by | By | Yes | Attributes of the target component.| +**System capability**: SystemCapability.Test.UiTest **Return value** -| Type | Description | -| --------------------- | --------------------------------- | -| Promise\ | Promise used to return the found component.| +| Type| Description | +| -------- | ---------------------- | +| Driver | **Driver** object created.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ------------------ | +| 17000001 | Initialize failed. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.findComponent(BY.text('next page')) + let driver = Driver.create(); } ``` -### UiDriver.findComponents +### delayMs9+ -findComponents(by: By): Promise\> +delayMs(duration: number): Promise\ -Searches this **UiDriver** object for all components that match the given attributes. +Delays this **Driver** object within the specified duration. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------- | -| by | By | Yes | Attributes of the target component.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| duration | number | Yes | Duration of time, in ms.| -**Return value** +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). -| Type | Description | -| ----------------------------- | --------------------------------------- | -| Promise\> | Promise used to return a list of found components.| +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let buttonList = await driver.findComponents(BY.text('next page')) + let driver = Driver.create(); + await driver.delayMs(1000); } ``` -### UiDriver.waitForComponent9+ +### findComponent9+ -waitForComponent(by: By, time: number): Promise\ +findComponent(on: On): Promise\ -Searches this **UiDriver** object for the target component that matches the given attributes within the specified duration. +Searches this **Driver** object for the target component that matches the given attributes. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------------- | -| by | By | Yes | Attributes of the target component. | -| time | number | Yes | Duration for searching for the target component, in ms.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | Yes | Attributes of the target component.| **Return value** -| Type | Description | -| --------------------- | --------------------------------- | -| Promise\ | Promise used to return the found component.| +| Type | Description | +| ---------------------------------- | --------------------------------- | +| Promise\<[Component](#component9)> | Promise used to return the found component.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - let button = await driver.waitForComponent(BY.text('next page'),500) + let driver = Driver.create(); + let button = await driver.findComponent(ON.text('next page')); } ``` -### UiDriver.assertComponentExist +### findComponents9+ -assertComponentExist(by: By): Promise\ +findComponents(on: On): Promise\> -Asserts that a component that matches the given attributes exists on the current page. If the component does not exist, the API throws a JS exception, causing the current test case to fail. +Searches this **Driver** object for all components that match the given attributes. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | -------------------- | -| by | By | Yes | Attributes of the target component.| - -**Example** +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | Yes | Attributes of the target component.| -```js -async function demo() { - let driver = UiDriver.create() - await driver.assertComponentExist(BY.text('next page')) -} -``` +**Return value** -### UiDriver.pressBack +| Type | Description | +| ------------------------------------------ | --------------------------------------- | +| Promise\> | Promise used to return a list of found components.| -pressBack(): Promise\ +**Error codes** -Presses the Back button on this **UiDriver** object. +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). -**System capability**: SystemCapability.Test.UiTest +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.pressBack() + let driver = Driver.create(); + let buttonList = await driver.findComponents(ON.text('next page')); } ``` -### UiDriver.triggerKey +### findWindow9+ -triggerKey(keyCode: number): Promise\ +findWindow(filter: WindowFilter): Promise\ -Triggers the key of this **UiDriver** object that matches the given key code. +Searches for the window that matches the specified attributes. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------ | ---- | ------------- | -| keyCode | number | Yes | Key code.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------------- | +| filter | [WindowFilter](#windowfilter9) | Yes | Attributes of the target window.| + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------- | +| Promise\<[UiWindow](#uiwindow9)> | Promise used to return the target window.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.triggerKey(123) + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); } ``` -### UiDriver.click +### waitForComponent9+ -click(x: number, y: number): Promise\ +waitForComponent(on: On, time: number): Promise\ -Clicks a specific point of this **UiDriver** object based on the given coordinates. +Searches this **Driver** object for the target component that matches the given attributes within the specified duration. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------------------- | -| x | number | Yes | X coordinate of the target point.| -| y | number | Yes | Y coordinate of the target point.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | -------------------------------- | +| On | [On](#on9) | Yes | Attributes of the target component. | +| time | number | Yes | Duration for searching for the target component, in ms.| + +**Return value** + +| Type | Description | +| --------------------------------- | --------------------------------- | +| Promise\<[Component](#component)> | Promise used to return the found component.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.click(100,100) + let driver = Driver.create(); + let button = await driver.waitForComponent(ON.text('next page'),500); } ``` -### UiDriver.doubleClick +### assertComponentExist9+ -doubleClick(x: number, y: number): Promise\ +assertComponentExist(on: On): Promise\ -Double-clicks a specific point of this **UiDriver** object based on the given coordinates. +Asserts that a component that matches the given attributes exists on the current page. **System capability**: SystemCapability.Test.UiTest **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | -------------------------------------- | -| x | number | Yes | X coordinate of the target point.| -| y | number | Yes | Y coordinate of the target point.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | -------------------- | +| on | [On](#on9) | Yes | Attributes of the target component.| -**Example** +**Error codes** -```js +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000003 | Component existence assertion failed. | + +**Example** + +```js async function demo() { - let driver = UiDriver.create() - await driver.doubleClick(100,100) + let driver = Driver.create(); + await driver.assertComponentExist(ON.text('next page')); } ``` -### UiDriver.longClick +### pressBack9+ -longClick(x: number, y: number): Promise\ +pressBack(): Promise\ -Long-clicks a specific point of this **UiDriver** object based on the given coordinates. +Presses the Back button on this **Driver** object. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.pressBack(); +} +``` + +### triggerKey9+ + +triggerKey(keyCode: number): Promise\ + +Triggers the key of this **Driver** object that matches the given key code. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------- | +| keyCode | number | Yes | Key code.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.triggerKey(123); +} +``` + +### triggerCombineKeys9+ + +triggerCombineKeys(key0: number, key1: number, key2?: number): Promise\ + +Triggers a key combination based on the specified key values. For example, if the value of **Key** is (2072, 2019), the **Driver** object finds and clicks the key combination that matches the value, for example, **Ctrl+C**. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------- | +| key0 | number | Yes | The first key value.| +| key1 | number | Yes | The second key value.| +| key2 | number | No | The third key value.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.triggerCombineKeys(2072, 2047, 2035); +} +``` + + +### click9+ + +click(x: number, y: number): Promise\ + +Clicks a specific point of this **Driver** object based on the given coordinates. **System capability**: SystemCapability.Test.UiTest @@ -1209,23 +1629,31 @@ Long-clicks a specific point of this **UiDriver** object based on the given coor | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| x | number | Yes | X coordinate of the target point.| -| y | number | Yes | Y coordinate of the target point.| +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.longClick(100,100) + let driver = Driver.create(); + await driver.click(100,100); } ``` -### UiDriver.swipe +### doubleClick9+ -swipe(startx: number, starty: number, endx: number, endy: number): Promise\ +doubleClick(x: number, y: number): Promise\ -Swipes on this **UiDriver** object from the start point to the end point based on the given coordinates. +Double-clicks a specific point of this **Driver** object based on the given coordinates. **System capability**: SystemCapability.Test.UiTest @@ -1233,25 +1661,31 @@ Swipes on this **UiDriver** object from the start point to the end point based o | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| startx | number | Yes | X coordinate of the start point.| -| starty | number | Yes | Y coordinate of the start point.| -| endx | number | Yes | X coordinate of the end point.| -| endy | number | Yes | Y coordinate of the end point.| +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.swipe(100,100,200,200) + let driver = Driver.create(); + await driver.doubleClick(100,100); } ``` -### UiDriver.drag9+ +### longClick9+ -drag(startx: number, starty: number, endx: number, endy: number): Promise\ +longClick(x: number, y: number): Promise\ -Drags this **UiDriver** object from the given start point to the given end point. +Long-clicks a specific point of this **Driver** object based on the given coordinates. **System capability**: SystemCapability.Test.UiTest @@ -1259,25 +1693,101 @@ Drags this **UiDriver** object from the given start point to the given end point | Name| Type | Mandatory| Description | | ------ | ------ | ---- | -------------------------------------- | -| startx | number | Yes | X coordinate of the start point.| -| starty | number | Yes | Y coordinate of the start point.| -| endx | number | Yes | X coordinate of the end point.| -| endy | number | Yes | Y coordinate of the end point.| +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.drag(100,100,200,200) + let driver = Driver.create(); + await driver.longClick(100,100); } ``` -### UiDriver.screenCap +### swipe9+ -screenCap(savePath: string): Promise\ +swipe(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\ -Captures the current screen of this **UiDriver** object and saves it as a PNG image to the given save path. +Swipes on this **Driver** object from the given start point to the given end point. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| startx | number | Yes | X-coordinate of the start point. | +| starty | number | Yes | Y-coordinate of the start point. | +| endx | number | Yes | X-coordinate of the end point. | +| endy | number | Yes | Y-coordinate of the end point. | +| speed | number | No | Scroll speed, in pixel/s. The value ranges from 200 to 15000. If the set value is not in the range, the default value 600 is used.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.swipe(100,100,200,200,600); +} +``` + +### drag9+ + +drag(startx: number, starty: number, endx: number, endy: number, speed?: number): Promise\ + +Drags this **Driver** object from the given start point to the given end point. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------------------------------------ | +| startx | number | Yes | X-coordinate of the start point. | +| starty | number | Yes | Y-coordinate of the start point. | +| endx | number | Yes | X-coordinate of the end point. | +| endy | number | Yes | Y-coordinate of the end point. | +| speed | number | No | Scroll speed, in pixel/s. The value ranges from 200 to 15000. If the set value is not in the range, the default value 600 is used.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.drag(100,100,200,200,600); +} +``` + +### screenCap9+ + +screenCap(savePath: string): Promise\ + +Captures the current screen of this **Driver** object and saves it as a PNG image to the given save path. **System capability**: SystemCapability.Test.UiTest @@ -1289,30 +1799,1880 @@ Captures the current screen of this **UiDriver** object and saves it as a PNG im **Return value** -| Type | Description | -| -------------- | -------------------------------------- | -| Promise\ | Promise used to return the operation result. The value **true** means that the operation is successful.| +| Type | Description | +| ----------------- | -------------------------------------- | +| Promise\ | Promise used to return the operation result. The value **true** means that the operation is successful.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | **Example** ```js async function demo() { - let driver = UiDriver.create() - await driver.screenCap('/local/tmp/') + let driver = Driver.create(); + await driver.screenCap('/local/tmp/1.png'); } ``` -## MatchPattern +### setDisplayRotation9+ -Enumerates the match patterns supported for component attributes. +setDisplayRotation(rotation: DisplayRotation): Promise\ + +Sets the display rotation of the device. **System capability**: SystemCapability.Test.UiTest -| Name | Value | Description | -| ----------- | ---- | -------------- | -| EQUALS | 0 | Equal to the given value. | -| CONTAINS | 1 | Containing the given value. | -| STARTS_WITH | 2 | Starting from the given value.| -| ENDS_WITH | 3 | Ending with the given value.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------ | ---- | ---------------- | +| rotation | [DisplayRotation](#displayrotation9) | Yes | Display rotation of the device.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). -### +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.setDisplayRotation(DisplayRotation.ROTATION_180); +} +``` + +### getDisplayRotation9+ + +getDisplayRotation(): Promise\ + +Obtains the display rotation of the current device. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------------------------------------- | --------------------------------------- | +| Promise\<[DisplayRotation](#displayrotation9)> | Promise used to return the display rotation of the current device.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let rotation = await driver.getDisplayRotation(); +} +``` + +### setDisplayRotationEnabled9+ + +setDisplayRotationEnabled(enabled: boolean): Promise\ + +Enables or disables display rotation. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------- | ---- | ------------------------------------------------------- | +| enabled | boolean | Yes | Whether to enable display rotation. The value **true** means to enable display rotation, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.setDisplayRotationEnabled(false); +} +``` + +### getDisplaySize9+ + +getDisplaySize(): Promise\ + +Obtains the display size of the current device. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------------------- | --------------------------------------- | +| Promise\<[Point](#point9)> | Promise used to return the display size of the current device.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let size = await driver.getDisplaySize(); +} +``` + +### getDisplayDensity9+ + +getDisplayDensity(): Promise\ + +Obtains the display density of the current device. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------------------------- | ----------------------------------------- | +| Promise\<[Point](#point9)> | Promise used to return the display density of the current device.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let density = await driver.getDisplayDensity(); +} +``` + +### wakeUpDisplay9+ + +wakeUpDisplay(): Promise\ + +Wakes up the device display. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.wakeUpDisplay(); +} +``` + +### pressHome9+ + +pressHome(): Promise\ + +Returns to the home screen. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.pressHome(); +} +``` + +### waitForIdle9+ + +waitForIdle(idleTime: number, timeout: number): Promise\ + +Checks whether all components on the current page are idle. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| idleTime | number | Yes | Idle time threshold, in milliseconds. If the duration for which a component remains inactive reaches this threshold, it is considered as idle.| +| timeout | number | Yes | Maximum idle waiting time, in milliseconds. | + +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let idled = await driver.waitForIdle(4000,5000); +} +``` + +### fling9+ + +fling(from: Point, to: Point, stepLen: number, speed: number): Promise\ + +Simulates a fling operation on the screen. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | ------------------------------------------------------------ | +| from | [Point](#point9) | Yes | Coordinates of the point where the finger touches the screen. | +| to | [Point](#point9) | Yes | Coordinates of the point where the finger leaves the screen. | +| stepLen | number | Yes | Fling step length, in pixels. | +| speed | number | Yes | Scroll speed, in pixel/s. The value ranges from 200 to 15000. If the set value is not in the range, the default value 600 is used.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + await driver.fling({X: 500, Y: 480},{X: 450, Y: 480},5,600); +} +``` + +### injectMultiPointerAction9+ + +injectMultiPointerAction(pointers: PointerMatrix, speed?: number): Promise\ + +Injects a multi-touch operation to the device. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ------------------------------------------------------------ | +| pointers | [PointerMatrix](#pointermatrix9) | Yes | Scroll trajectory, including the number of fingers and an array of coordinates along the trajectory. | +| speed | number | No | Scroll speed, in pixel/s. The value ranges from 200 to 15000. If the set value is not in the range, the default value 600 is used.| + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let pointers = PointerMatrix.create(2,3); + pointers.setPoint(0,0,{X:230,Y:480}); + pointers.setPoint(0,1,{X:250,Y:380}); + pointers.setPoint(0,2,{X:270,Y:280}); + pointers.setPoint(1,0,{X:230,Y:680}); + pointers.setPoint(1,1,{X:240,Y:580}); + pointers.setPoint(1,2,{X:250,Y:480}); + await driver.injectMultiPointerAction(pointers); +} +``` + +## PointerMatrix9+ + +Implements a **PointerMatrix** object that stores coordinates and behaviors of each action of each finger in a multi-touch operation. + +### create9+ + +static create(fingers: number, steps: number): PointerMatrix + +Creates a **PointerMatrix** object and returns the object created. This API is a static API. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------------------------------------ | +| fingers | number | Yes | Number of fingers in the multi-touch operation. Value range: [1,10].| +| steps | number | Yes | Number of steps operated by each finger. Value range: [1,1000].| + +**Return value** + +| Type | Description | +| -------------------------------- | ----------------------------- | +| [PointerMatrix](#pointermatrix9) | **PointerMatrix** object created.| + +**Example** + +```js +async function demo() { + let pointerMatrix = PointerMatrix.create(2,3); +} +``` + +### setPoint9+ + +setPoint(finger: number, step: number, point: Point): void + +Sets the coordinates for the action corresponding to the specified finger and step in the **PointerMatrix** object. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------- | ---- | ---------------- | +| finger | number | Yes | Sequence number of the finger. | +| step | number | Yes | Sequence number of the step. | +| point | [Point](#point9) | Yes | Coordinates of the action.| + +**Example** + +```js +async function demo() { + let pointers = PointerMatrix.create(2,3); + pointers.setPoint(0,0,{X:230,Y:480}); + pointers.setPoint(0,1,{X:250,Y:380}); + pointers.setPoint(0,2,{X:270,Y:280}); + pointers.setPoint(1,0,{X:230,Y:680}); + pointers.setPoint(1,1,{X:240,Y:580}); + pointers.setPoint(1,2,{X:250,Y:480}); +} +``` + +## UiWindow9+ + +The **UiWindow** class represents a window on the UI and provides APIs for obtaining window attributes, dragging a window, and adjusting the window size. +All APIs provided in this class use a promise to return the result and must be invoked using **await**. + +### getBundleName9+ + +getBundleName(): Promise\ + +Obtains the bundle name of the application to which this window belongs. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------------- | +| Promise\ | Promise used to return the bundle name.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let name = await window.getBundleName(); +} +``` + +### getBounds9+ + +getBounds(): Promise\ + +Obtains the bounds information of this window. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ------------------------ | --------------------------------- | +| Promise\<[Rect](#rect9)> | Promise used to return the bounds information of the window.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let rect = await window.getBounds(); +} +``` + +### getTitle9+ + +getTitle(): Promise\ + +Obtains the title of this window. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | --------------------------------- | +| Promise\ | Promise used to return the title of the window.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let rect = await window.getTitle(); +} +``` + +### getWindowMode9+ + +getWindowMode(): Promise\ + +Obtains the window mode of this window. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ------------------------------------ | ------------------------------------- | +| Promise\<[WindowMode](#windowmode9)> | Promise used to return the window mode of the window.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let mode = await window.getWindowMode(); +} +``` + +### isFocused9+ + +isFocused(): Promise\ + +Checks whether this window is in focused state. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that the window is in focused state, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let focused = await window.isFocused(); +} +``` + +### isActived9+ + +isActived(): Promise\ + +Checks whether this window is active. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that the window is active, and **false** means the opposite.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + let focused = await window.isActived(); +} +``` + +### focus9+ + +focus(): Promise\ + +Moves the focus to this window. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.focus(); +} +``` + +### moveTo9+ + +moveTo(x: number, y: number): Promise\ + +Moves this window to the target point. This API is applicable to moveable windows. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.moveTo(100, 100); +} +``` + +### resize9+ + +resize(wide: number, height: number, direction: ResizeDirection): Promise\ + +Resizes this window based on the specified width, height, and resize direction. This API is applicable to resizable windows. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------------------ | ---- | ------------------------------------------------------------ | +| wide | number | Yes | Target width. | +| height | number | Yes | Target height. | +| direction | [ResizeDirection](#resizedirection9) | Yes | Resize direction.| + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.resize(100, 100, ResizeDirection.LEFT); +} +``` + +### split9+ + +split(): Promise\ + +Switches the window to split-screen mode. This API is applicable to windows that support screen splitting. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.split(); +} +``` + +### maximize9+ + +maximize(): Promise\ + +Maximizes this window. This API is applicable to windows that can be maximized. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.maximize(); +} +``` + +### minimize9+ + +minimize(): Promise\ + +Minimizes this window. This API is applicable to windows that can be minimized. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.minimize(); +} +``` + +### resume9+ + +resume(): Promise\ + +Restores this window to the previous window mode. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.resume(); +} +``` + +### close9+ + +close(): Promise\ + +Closes this window. + +**System capability**: SystemCapability.Test.UiTest + +**Error codes** + +For details about the error codes, see [UiTest Error Codes](../errorcodes/errorcode-uitest.md). + +| ID| Error Message | +| -------- | ---------------------------------------- | +| 17000002 | API does not allow calling concurrently. | +| 17000004 | Component lost/UiWindow lost. | +| 17000005 | This operation is not supported. | + +**Example** + +```js +async function demo() { + let driver = Driver.create(); + let window = await driver.findWindow({actived: true}); + await window.close(); +} +``` + +## By(deprecated) + +The UiTest framework provides a wide range of UI component feature description APIs in the **By** class to filter and match components. +The API capabilities provided by the **By** class exhibit the following features:
1. Allow one or more attributes as the match conditions. For example, you can specify both the **text** and **id** attributes to find the target component.
2. Provide multiple match patterns for component attributes.
3. Support absolute positioning and relative positioning for components. APIs such as [By.isBefore(deprecated)](#isbeforedeprecated) and [By.isAfter(deprecated)](#isafterdeprecated) can be used to specify the features of adjacent components to assist positioning.
All APIs provided in the **By** class are synchronous. You are advised to use the static constructor **BY** to create a **By** object in chain mode. + +This API is deprecated since API version 9. You are advised to use [On9+](#on9) instead. + +```js +BY.text('123').type('button'); +``` + +### text(deprecated) + +text(txt: string, pattern?: MatchPattern): By + +Specifies the text attribute of the target component. Multiple match patterns are supported. + +This API is deprecated since API version 9. You are advised to use [text9+](#text9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ----------------------------- | ---- | --------------------------------------------------- | +| txt | string | Yes | Component text, used to match the target component. | +| pattern | [MatchPattern](#matchpattern) | No | Match pattern. The default value is [EQUALS](#matchpattern).| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------- | +| [By](#bydeprecated) | **By** object that matches the text attribute of the target component.| + +**Example** + +```js +let by = BY.text('123'); // Use the static constructor BY to create a By object and specify the text attribute of the target component. +``` + + +### key(deprecated) + +key(key: string): By + +Specifies the key attribute of the target component. + +This API is deprecated since API version 9. You are advised to use [id9+](#id9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------- | +| key | string | Yes | Component key.| + +**Return value** + +| Type | Description | +| ------------------- | ----------------------------------- | +| [By](#bydeprecated) | **By** object that matches the key attribute of the target component.| + +**Example** + +```js +let by = BY.key('123'); // Use the static constructor BY to create a By object and specify the key attribute of the target component. +``` + + +### id(deprecated) + +id(id: number): By + +Specifies the ID attribute of the target component. + +This API is deprecated since API version 9. + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| id | number | Yes | Component ID.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------- | +| [By](#bydeprecated) | **By** object that matches the ID attribute of the target component.| + +**Example** + +```js +let by = BY.id(123); // Use the static constructor BY to create a By object and specify the ID attribute of the target component. +``` + + +### type(deprecated) + +type(tp: string): By + +Specifies the type attribute of the target component. + +This API is deprecated since API version 9. You are advised to use [type9+](#type9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------- | +| tp | string | Yes | Component type.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------------- | +| [By](#bydeprecated) | **By** object that matches the type attribute of the target component.| + +**Example** + +```js +let by = BY.type('button'); // Use the static constructor BY to create a By object and specify the type attribute of the target component. +``` + + +### clickable(deprecated) + +clickable(b?: boolean): By + +Specifies the clickable status attribute of the target component. + +This API is deprecated since API version 9. You are advised to use [clickable9+](#clickable9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | No | Clickable status of the target component.
**true**: clickable.
**false**: not clickable.
Default value: **true**| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------ | +| [By](#bydeprecated) | **By** object that matches the clickable status attribute of the target component.| + +**Example** + +```js +let by = BY.clickable(true); // Use the static constructor BY to create a By object and specify the clickable status attribute of the target component. +``` + + +### scrollable(deprecated) + +scrollable(b?: boolean): By + +Specifies the scrollable status attribute of the target component. + +This API is deprecated since API version 9. You are advised to use [scrollable9+](#scrollable9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------------------------------- | +| b | boolean | No | Scrollable status of the target component.
**true**: scrollable.
**false**: not scrollable.
Default value: **true**| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------ | +| [By](#bydeprecated) | **By** object that matches the scrollable status attribute of the target component.| + +**Example** + +```js +let by = BY.scrollable(true); // Use the static constructor BY to create a By object and specify the scrollable status attribute of the target component. +``` + +### enabled(deprecated) + +enabled(b?: boolean): By + +Specifies the enabled status attribute of the target component. + +This API is deprecated since API version 9. You are advised to use [enabled9+](#enabled9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------------------------------- | +| b | boolean | No | Enabled status of the target component.
**true**: enabled.
**false**: not disabled.
Default value: **true**| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------------- | +| [By](#bydeprecated) | **By** object that matches the enabled status attribute of the target component.| + +**Example** + +```js +let by = BY.enabled(true); // Use the static constructor BY to create a By object and specify the enabled status attribute of the target component. +``` + +### focused(deprecated) + +focused(b?: boolean): By + +Specifies the focused status attribute of the target component. + +This API is deprecated since API version 9. You are advised to use [focused9+](#focused9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ----------------------------------------------------- | +| b | boolean | No | Focused status of the target component.
**true**: focused.
**false**: not focused.
Default value: **true**| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------------- | +| [By](#bydeprecated) | **By** object that matches the focused status attribute of the target component.| + +**Example** + +```js +let by = BY.focused(true); // Use the static constructor BY to create a By object and specify the focused status attribute of the target component. +``` + +### selected(deprecated) + +selected(b?: boolean): By + +Specifies the selected status of the target component. + +This API is deprecated since API version 9. You are advised to use [selected9+](#selected9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| b | boolean | No | Selected status of the target component.
**true**: selected.
**false**: not selected.
Default value: **true**| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------ | +| [By](#bydeprecated) | **By** object that matches the selected status attribute of the target component.| + +**Example** + +```js +let by = BY.selected(true); // Use the static constructor BY to create a By object and specify the selected status attribute of the target component. +``` + +### isBefore(deprecated) + +isBefore(by: By): By + +Specifies the attributes of the component before which the target component is located. + +This API is deprecated since API version 9. You are advised to use [isBefore9+](#isbefore9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ---------------- | +| by | [By](#bydeprecated) | Yes | Attributes of the component before which the target component is located.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------------------------- | +| [By](#bydeprecated) | **By** object.| + +**Example** + +```js +let by = BY.isBefore(BY.text('123')); // Use the static constructor BY to create a By object and specify the attributes of the component before which the target component is located. +``` + +### isAfter(deprecated) + +isAfter(by: By): By + +Specifies the attributes of the component after which the target component is located. + +This API is deprecated since API version 9. You are advised to use [isAfter9+](#isafter9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | ---------------- | +| by | [By](#bydeprecated) | Yes | Attributes of the component before which the target component is located.| + +**Return value** + +| Type | Description | +| ------------------- | ---------------------------------------------------- | +| [By](#bydeprecated) | **By** object.| + +**Example** + +```js +let by = BY.isAfter(BY.text('123')); // Use the static constructor BY to create a By object and specify the attributes of the component after which the target component is located. +``` + +## UiComponent(deprecated) + +In **UiTest**, the **UiComponent** class represents a component on the UI and provides APIs for obtaining component attributes, clicking a component, scrolling to search for a component, and text injection. +All APIs provided in this class use a promise to return the result and must be invoked using **await**. + +This API is deprecated since API version 9. You are advised to use [Component9+](#component9) instead. + +### click(deprecated) + +click(): Promise\ + +Clicks this component. + +This API is deprecated since API version 9. You are advised to use [click9+](#click9). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + await button.click(); +} +``` + +### doubleClick(deprecated) + +doubleClick(): Promise\ + +Double-clicks this component. + +This API is deprecated since API version 9. You are advised to use [doubleClick9+](#doubleclick9). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + await button.doubleClick(); +} +``` + +### longClick(deprecated) + +longClick(): Promise\ + +Long-clicks this component. + +This API is deprecated since API version 9. You are advised to use [longClick9+](#longclick9). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + await button.longClick(); +} +``` + +### getId(deprecated) + +getId(): Promise\ + +Obtains the ID of this component. + +This API is deprecated since API version 9. + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------- | +| Promise\ | Promise used to return the ID of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let num = await button.getId(); +} +``` + +### getKey(deprecated) + +getKey(): Promise\ + +Obtains the key of this component. + +This API is deprecated since API version 9. You are advised to use [getId9+](#getid9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------ | +| Promise\ | Promise used to return the key of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let str_key = await button.getKey(); +} +``` + +### getText(deprecated) + +getText(): Promise\ + +Obtains the text information of this component. + +This API is deprecated since API version 9. You are advised to use [getText9+](#gettext9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | --------------------------------- | +| Promise\ | Promise used to return the text information of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let text = await button.getText(); +} +``` + +### getType(deprecated) + +getType(): Promise\ + +Obtains the type of this component. + +This API is deprecated since API version 9. You are advised to use [getType9+](#gettype9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------- | +| Promise\ | Promise used to return the type of the component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + let type = await button.getType(); +} +``` + +### isClickable(deprecated) + +isClickable(): Promise\ + +Obtains the clickable status of this component. + +This API is deprecated since API version 9. You are advised to use [isClickable9+](#isclickable9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that the component is clickable, and **false** means the opposite.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + if(await button.isClickable()) { + console.info('This button can be Clicked'); + } else { + console.info('This button can not be Clicked'); + } +} +``` + +### isScrollable(deprecated) + +isScrollable(): Promise\ + +Obtains the scrollable status of this component. + +This API is deprecated since API version 9. You are advised to use [isScrollable9+](#isscrollable9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that the component is scrollable, and **false** means the opposite.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let scrollBar = await driver.findComponent(BY.scrollable(true)); + if(await scrollBar.isScrollable()) { + console.info('This scrollBar can be operated'); + } else { + console.info('This scrollBar can not be operated'); + } +} +``` + + +### isEnabled(deprecated) + +isEnabled(): Promise\ + +Obtains the enabled status of this component. + +This API is deprecated since API version 9. You are advised to use [isEnabled9+](#isenabled9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ----------------- | ---------------------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the component is enabled, and **false** means the opposite.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + if(await button.isEnabled()) { + console.info('This button can be operated'); + } else { + console.info('This button can not be operated'); + } +} + +``` + +### isFocused(deprecated) + +isFocused(): Promise\ + +Obtains the focused status of this component. + +This API is deprecated since API version 9. You are advised to use [isFocused9+](#isfocused9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ----------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** means that the target component is focused, and **false** means the opposite.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + if(await button.isFocused()) { + console.info('This button is focused'); + } else { + console.info('This button is not focused'); + } +} +``` + +### isSelected(deprecated) + +isSelected(): Promise\ + +Obtains the selected status of this component. + +This API is deprecated since API version 9. You are advised to use [isSelected9+](#isselected9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| ----------------- | ----------------------------------------------------- | +| Promise\ | Promise used to return the result. The value **true** means that the component is selected, and **false** means the opposite.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.type('button')); + if(await button.isSelected()) { + console.info('This button is selected'); + } else { + console.info('This button is not selected'); + } +} +``` + +### inputText(deprecated) + +inputText(text: string): Promise\ + +Enters text into this component (available for text boxes). + +This API is deprecated since API version 9. You are advised to use [inputText9+](#inputtext9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| text | string | Yes | Text to enter.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let text = await driver.findComponent(BY.text('hello world')); + await text.inputText('123'); +} +``` + +### scrollSearch(deprecated) + +scrollSearch(by: By): Promise\ + +Scrolls on this component to search for the target component (applicable to components that support scrolling, such as **\**). + +This API is deprecated since API version 9. You are advised to use [scrollSearch9+](#scrollsearch9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| by | [By](#bydeprecated) | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| ----------------------------------------------- | ------------------------------------- | +| Promise\<[UiComponent](#uicomponentdeprecated)> | Promise used to return the target component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let scrollBar = await driver.findComponent(BY.type('Scroll')); + let button = await scrollBar.scrollSearch(BY.text('next page')); +} +``` + +## UiDriver(deprecated) + +The **UiDriver** class is the main entry to the UiTest framework. It provides APIs for features such as component matching/search, key injection, coordinate clicking/sliding, and screenshot. +All APIs provided by this class, except for **UiDriver.create()**, use a promise to return the result and must be invoked using **await**. + +This API is deprecated since API version 9. You are advised to use [Driver9+](#driver9) instead. + +### create(deprecated) + +static create(): UiDriver + +Creates a **UiDriver** object and returns the object created. This API is a static API. + +This API is deprecated since API version 9. You are advised to use [create9+](#create9). + +**System capability**: SystemCapability.Test.UiTest + +**Return value** + +| Type | Description | +| -------- | ------------------------ | +| UiDriver | Returns the **UiDriver** object created.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); +} +``` + +### delayMs(deprecated) + +delayMs(duration: number): Promise\ + +Delays this **UiDriver** object within the specified duration. + +This API is deprecated since API version 9. You are advised to use [delayMs9+](#delayms9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------ | +| duration | number | Yes | Duration of time.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.delayMs(1000); +} +``` + +### findComponent(deprecated) + +findComponent(by: By): Promise\ + +Searches this **UiDriver** object for the target component that matches the given attributes. + +This API is deprecated since API version 9. You are advised to use [findComponent9+](#findcomponent9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| by | [By](#bydeprecated) | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| ----------------------------------------------- | --------------------------------- | +| Promise\<[UiComponent](#uicomponentdeprecated)> | Promise used to return the found component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let button = await driver.findComponent(BY.text('next page')); +} +``` + +### findComponents(deprecated) + +findComponents(by: By): Promise\> + +Searches this **UiDriver** object for all components that match the given attributes. + +This API is deprecated since API version 9. You are advised to use [findComponents9+](#findcomponents9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| by | [By](#bydeprecated) | Yes | Attributes of the target component.| + +**Return value** + +| Type | Description | +| ------------------------------------------------------- | --------------------------------------- | +| Promise\> | Promise used to return a list of found components.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + let buttonList = await driver.findComponents(BY.text('next page')); +} +``` + +### assertComponentExist(deprecated) + +assertComponentExist(by: By): Promise\ + +Asserts that a component that matches the given attributes exists on the current page. If the component does not exist, the API throws a JS exception, causing the current test case to fail. + +This API is deprecated since API version 9. You are advised to use [assertComponentExist9+](#assertcomponentexist9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------- | ---- | -------------------- | +| by | [By](#bydeprecated) | Yes | Attributes of the target component.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.assertComponentExist(BY.text('next page')); +} +``` + +### pressBack(deprecated) + +pressBack(): Promise\ + +Presses the Back button on this **UiDriver** object. + +This API is deprecated since API version 9. You are advised to use [pressBack9+](#pressback9). + +**System capability**: SystemCapability.Test.UiTest + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.pressBack(); +} +``` + +### triggerKey(deprecated) + +triggerKey(keyCode: number): Promise\ + +Triggers the key of this **UiDriver** object that matches the given key code. + +This API is deprecated since API version 9. You are advised to use [triggerKey9+](#triggerkey9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | ------------- | +| keyCode | number | Yes | Key code.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.triggerKey(123); +} +``` + + +### click(deprecated) + +click(x: number, y: number): Promise\ + +Clicks a specific point of this **UiDriver** object based on the given coordinates. + +This API is deprecated since API version 9. You are advised to use [click9+](#click9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.click(100,100); +} +``` + +### doubleClick(deprecated) + +doubleClick(x: number, y: number): Promise\ + +Double-clicks a specific point of this **UiDriver** object based on the given coordinates. + +This API is deprecated since API version 9. You are advised to use [doubleClick9+](#doubleclick9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.doubleClick(100,100); +} +``` + +### longClick(deprecated) + +longClick(x: number, y: number): Promise\ + +Long-clicks a specific point of this **UiDriver** object based on the given coordinates. + +This API is deprecated since API version 9. You are advised to use [longClick9+](#longclick9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| x | number | Yes | X-coordinate of the target point.| +| y | number | Yes | Y-coordinate of the target point.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.longClick(100,100); +} +``` + +### swipe(deprecated) + +swipe(startx: number, starty: number, endx: number, endy: number): Promise\ + +Swipes on this **UiDriver** object from the start point to the end point based on the given coordinates. + +This API is deprecated since API version 9. You are advised to use [swipe9+](#swipe9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| startx | number | Yes | X-coordinate of the start point.| +| starty | number | Yes | Y-coordinate of the start point.| +| endx | number | Yes | X-coordinate of the end point.| +| endy | number | Yes | Y-coordinate of the end point.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.swipe(100,100,200,200); +} +``` + +### screenCap(deprecated) + +screenCap(savePath: string): Promise\ + +Captures the current screen of this **UiDriver** object and saves it as a PNG image to the given save path. + +This API is deprecated since API version 9. You are advised to use [screenCap9+](#screencap9). + +**System capability**: SystemCapability.Test.UiTest + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | -------------- | +| savePath | string | Yes | File save path.| + +**Return value** + +| Type | Description | +| ----------------- | -------------------------------------- | +| Promise\ | Promise used to return the operation result. The value **true** means that the operation is successful.| + +**Example** + +```js +async function demo() { + let driver = UiDriver.create(); + await driver.screenCap('/local/tmp/1.png'); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md index bcbac5414055dfb654ab1264ab04f92e629cb3f3..ffb07ba4f21cc5f154bcf25062f86845c97577dc 100644 --- a/en/application-dev/reference/apis/js-apis-update.md +++ b/en/application-dev/reference/apis/js-apis-update.md @@ -1,6 +1,6 @@ -# Update +# @ohos.update (Update) -The Update module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. +The **update** module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications. There are two types of updates: SD card update and over the air (OTA) update. @@ -8,10 +8,8 @@ There are two types of updates: SD card update and over the air (OTA) update. - The OTA update depends on the server deployed by the device manufacturer for managing update packages. The OTA server IP address is passed by the caller. The request interface is fixed and developed by the device manufacturer. > **NOTE** -> -> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. -> -> The APIs provided by this module are system APIs. +> - 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 @@ -39,6 +37,14 @@ Obtains an **OnlineUpdater** object. | ------------------- | ---- | | [Updater](#updater) | **OnlineUpdater** object.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -71,6 +77,14 @@ Obtains a **Restorer** object for restoring factory settings. | --------------------- | ------ | | [Restorer](#restorer) | **Restorer** object for restoring factory settings.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -95,6 +109,14 @@ Obtains a **LocalUpdater** object. | ----------------------------- | ------ | | [LocalUpdater](#localupdater) | **LocalUpdater** object.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -102,7 +124,7 @@ try { let localUpdater = update.getLocalUpdater(); } catch(error) { console.error(`Fail to get localUpdater error: ${error}`); -} +}; ``` ## Updater @@ -123,6 +145,14 @@ Checks whether a new version is available. This API uses an asynchronous callbac | -------- | ---------------------------------------- | ---- | -------------- | | callback | AsyncCallback\<[CheckResult](#checkresult)> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -147,6 +177,14 @@ Checks whether a new version is available. This API uses a promise to return the | ------------------------------------- | ------------------- | | Promise\<[CheckResult](#checkresult)> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -175,6 +213,14 @@ Obtains information about the new version. This API uses an asynchronous callbac | -------- | ---------------------------------------- | ---- | --------------- | | callback | AsyncCallback\<[NewVersionInfo](#newversioninfo)> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -200,6 +246,14 @@ Obtains information about the new version. This API uses a promise to return the | ---------------------------------------- | -------------------- | | Promise\<[NewVersionInfo](#newversioninfo)> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -226,8 +280,16 @@ Obtains the description file of the new version. This API uses an asynchronous c | Name | Type | Mandatory | Description | | ------------------ | ---------------------------------------- | ---- | -------------- | | versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | -| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file. | -| callback | AsyncCallback\>) | Yes | Callback used to return the result.| +| descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file. | +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -272,6 +334,14 @@ Obtains the description file of the new version. This API uses a promise to retu | ---------------------------------------- | ------------------- | | Promise\> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -309,6 +379,14 @@ Obtains information about the current version. This API uses an asynchronous cal | -------- | ---------------------------------------- | ---- | ---------------- | | callback | AsyncCallback\<[CurrentVersionInfo](#currentversioninfo)> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -335,6 +413,14 @@ Obtains information about the current version. This API uses a promise to return | ---------------------------------------- | ------------------- | | Promise\<[CurrentVersionInfo](#currentversioninfo)> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -362,7 +448,15 @@ Obtains the description file of the current version. This API uses an asynchrono | Name | Type | Mandatory | Description | | ------------------ | ---------------------------------------- | ---- | --------------- | | descriptionOptions | [DescriptionOptions](#descriptionoptions) | Yes | Options of the description file. | -| callback | AsyncCallback\>) | Yes | Callback used to return the result.| +| callback | AsyncCallback\> | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -401,6 +495,14 @@ Obtains the description file of the current version. This API uses a promise to | ---------------------------------------- | -------------------- | | Promise\> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -433,6 +535,14 @@ Obtains information about the update task. This API uses an asynchronous callbac | -------- | ------------------------------------- | ---- | ---------------- | | callback | AsyncCallback\<[TaskInfo](#taskinfo)> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -457,6 +567,14 @@ Obtains information about the update task. This API uses a promise to return the | ------------------------------- | ------------------- | | Promise\<[TaskInfo](#taskinfo)> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -483,7 +601,15 @@ Downloads the new version. This API uses an asynchronous callback to return the | ----------------- | --------------------------------------- | ---- | ---------------------------------- | | versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | | downloadOptions | [DownloadOptions](#downloadoptions) | Yes | Download options. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -526,6 +652,14 @@ Downloads the new version. This API uses a promise to return the result. | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -562,7 +696,15 @@ Resumes download of the new version. This API uses an asynchronous callback to r | --------------------- | ---------------------------------------- | ---- | ------------------------------------ | | versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | | resumeDownloadOptions | [ResumeDownloadOptions](#resumedownloadoptions) | Yes | Options for resuming download. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -604,6 +746,14 @@ Resumes download of the new version. This API uses a promise to return the resul | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -639,7 +789,15 @@ Pauses download of the new version. This API uses an asynchronous callback to re | -------------------- | ---------------------------------------- | ---- | ------------------------------------ | | versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | | pauseDownloadOptions | [PauseDownloadOptions](#pausedownloadoptions) | Yes | Options for pausing download. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -681,6 +839,14 @@ Resumes download of the new version. This API uses a promise to return the resul | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -716,7 +882,15 @@ Updates the version. This API uses an asynchronous callback to return the result | ----------------- | --------------------------------------- | ---- | ------------------------------------ | | versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | | upgradeOptions | [UpgradeOptions](#upgradeoptions) | Yes | Update options. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -758,6 +932,14 @@ Updates the version. This API uses a promise to return the result. | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -793,7 +975,15 @@ Clears errors. This API uses an asynchronous callback to return the result. | ----------------- | --------------------------------------- | ---- | ------------------------------------ | | versionDigestInfo | [VersionDigestInfo](#versiondigestinfo) | Yes | Version digest information. | | clearOptions | [ClearOptions](#clearoptions) | Yes | Clear options. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -835,6 +1025,14 @@ Clears errors. This API uses a promise to return the result. | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -844,7 +1042,7 @@ const versionDigestInfo = { }; // Options for clearing errors -lconstet clearOptions = { +const clearOptions = { status: update.UpgradeStatus.UPGRADE_FAIL, }; updater.clearError(versionDigestInfo, clearOptions).then(() => { @@ -870,6 +1068,14 @@ Obtains the update policy. This API uses an asynchronous callback to return the | -------- | ---------------------------------------- | ---- | --------------- | | callback | AsyncCallback\<[UpgradePolicy](#upgradepolicy)> | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -895,6 +1101,14 @@ Obtains the update policy. This API uses a promise to return the result. | ---------------------------------------- | --------------------- | | Promise\<[UpgradePolicy](#upgradepolicy)> | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -923,6 +1137,14 @@ Sets the update policy. This API uses an asynchronous callback to return the res | policy | [UpgradePolicy](#upgradepolicy) | Yes | Update policy. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -930,7 +1152,7 @@ const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes -} +}; updater.setUpgradePolicy(policy, (err) => { console.log(`setUpgradePolicy result: ${err}`); }); @@ -958,6 +1180,14 @@ Sets the update policy. This API uses a promise to return the result. | -------------- | ------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -965,7 +1195,7 @@ const policy = { downloadStrategy: false, autoUpgradeStrategy: false, autoUpgradePeriods: [ { start: 120, end: 240 } ] // Automatic update period, in minutes -} +}; updater.setUpgradePolicy(policy).then(() => { console.log(`setUpgradePolicy success`); }).catch(err => { @@ -987,7 +1217,15 @@ Terminates the update. This API uses an asynchronous callback to return the resu | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -1013,6 +1251,14 @@ Terminates the update. This API uses a promise to return the result. | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -1038,6 +1284,14 @@ Enables listening for update events. This API uses an asynchronous callback to r | eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| | taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -1065,6 +1319,14 @@ Disables listening for update events. This API uses an asynchronous callback to | eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| | taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | No | Event callback.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -1084,7 +1346,7 @@ updater.off(eventClassifyInfo, (eventInfo) => { factoryReset(callback: AsyncCallback\): void -Restore the device to its factory settings. This API uses an asynchronous callback to return the result. +Restores the scale to its factory settings. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Update.UpdateService @@ -1094,7 +1356,15 @@ Restore the device to its factory settings. This API uses an asynchronous callba | Name | Type | Mandatory | Description | | -------- | -------------------- | ---- | -------------------------------------- | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -1108,7 +1378,7 @@ restorer.factoryReset((err) => { factoryReset(): Promise\ -Restore the device to its factory settings. This API uses a promise to return the result. +Restores the scale to its factory settings. This API uses a promise to return the result. **System capability**: SystemCapability.Update.UpdateService @@ -1120,6 +1390,14 @@ Restore the device to its factory settings. This API uses a promise to return th | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -1150,6 +1428,14 @@ Verifies the update package. This API uses an asynchronous callback to return th | certsFile | string | Yes | Path of the certificate file. | | callback | AsyncCallback\ | Yes | Callback used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -1186,6 +1472,14 @@ Verifies the update package. This API uses a promise to return the result. | -------------- | ---------------------- | | Promise\ | Promise used to return the result.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -1214,7 +1508,15 @@ Installs the update package. This API uses an asynchronous callback to return th | Name | Type | Mandatory | Description | | ----------- | ---------------------------------- | ---- | --------------------------------------- | | upgradeFile | Array<[UpgradeFile](#upgradefile)> | Yes | Update file. | -| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, `err` is `undefined`; otherwise, `err` is an `Error` object.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -1245,10 +1547,18 @@ Installs the update package. This API uses a promise to return the result. | -------------- | -------------------------- | | Promise\ | Promise that returns no value.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts -localUpdater upgradeFiles = [{ +const upgradeFiles = [{ fileType: update.ComponentType.OTA, // OTA package filePath: "path" // Path of the local update package }]; @@ -1273,6 +1583,14 @@ Enables listening for update events. This API uses an asynchronous callback to r | eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| | taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | + **Example** ```ts @@ -1300,7 +1618,15 @@ Disables listening for update events. This API uses an asynchronous callback to | Name | Type | Mandatory | Description | | ----------------- | ---------------------------------------- | ---- | ---- | | eventClassifyInfo | [EventClassifyInfo](#eventclassifyinfo) | Yes | Event information.| -| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | Yes | Event callback.| +| taskCallback | [UpgradeTaskCallback](#upgradetaskcallback) | No | Event callback.| + +**Error codes** + +For details about the error codes, see [Update Error Codes](../errorcodes/errorcode-update.md). + +| ID | Error Message | +| ------- | ---------------------------------------------------- | +| 11500104 | BusinessError 11500104: IPC error. | **Example** @@ -1337,7 +1663,7 @@ Enumerates update service types. | Name | Type | Mandatory | Description | | ------- | ----------------------------------- | ---- | ---- | | vendor | [BusinessVendor](#businessvendor) | Yes | Application vendor. | -| subType | [BusinessSubType](#businesssubtype) | Yes | Type | +| subType | [BusinessSubType](#businesssubtype) | Yes | Update service type. | ## CheckResult @@ -1377,7 +1703,7 @@ Represents a version component. **System capability**: SystemCapability.Update.UpdateService -| Parameter | Type | Mandatory | Description | +| Name | Type | Mandatory | Description | | --------------- | ----------------------------------- | ---- | -------- | | componentId | string | Yes | Component ID. | | componentType | [ComponentType](#componenttype) | Yes | Component type. | @@ -1498,7 +1824,7 @@ Represents an update policy. ## UpgradePeriod -Represents a period for automatic update. +Represents an automatic update period. **System capability**: SystemCapability.Update.UpdateService @@ -1509,7 +1835,7 @@ Represents a period for automatic update. ## TaskInfo -Represents task information. +Task information. **System capability**: SystemCapability.Update.UpdateService @@ -1520,7 +1846,7 @@ Represents task information. ## EventInfo -Represents event type information. +Represents event information. **System capability**: SystemCapability.Update.UpdateService @@ -1554,7 +1880,7 @@ Represents an error message. | Name | Type | Mandatory | Description | | ------------ | ------ | ---- | ---- | | errorCode | number | Yes | Error code. | -| errorMessage | string | Yes | Error description.| +| errorMessage | string | Yes | Error message.| ## EventClassifyInfo @@ -1592,11 +1918,11 @@ Represents an event callback. ## BusinessVendor -Device vendor. +Represents a device vendor. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ------ | -------- | ---- | | PUBLIC | "public" | Open source. | @@ -1606,7 +1932,7 @@ Represents an update type. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | -------- | ---- | ---- | | FIRMWARE | 1 | Firmware. | @@ -1616,7 +1942,7 @@ Represents a component type. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ---- | ---- | ---- | | OTA | 1 | Firmware. | @@ -1626,7 +1952,7 @@ Represents an update mode. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | -------- | ---------- | ---- | | UPGRADE | "upgrade" | Differential package. | | RECOVERY | "recovery" | Recovery package. | @@ -1637,7 +1963,7 @@ Represents an effective mode. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ------------- | ---- | ---- | | COLD | 1 | Cold update. | | LIVE | 2 | Live update. | @@ -1649,7 +1975,7 @@ Represents a description file type. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ------- | ---- | ---- | | CONTENT | 0 | Content. | | URI | 1 | Link. | @@ -1660,18 +1986,18 @@ Represents a description file format. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ---------- | ---- | ---- | | STANDARD | 0 | Standard format.| | SIMPLIFIED | 1 | Simple format.| ## NetType -Enumerates network types. +Represents a network type. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ----------------- | ---- | --------- | | CELLULAR | 1 | Data network. | | METERED_WIFI | 2 | Wi-Fi hotspot. | @@ -1685,7 +2011,7 @@ Represents an update command. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | -------------------- | ---- | ----- | | DOWNLOAD | 1 | Download. | | INSTALL | 2 | Install. | @@ -1699,7 +2025,7 @@ Enumerates update states. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ---------------- | ---- | ---- | | WAITING_DOWNLOAD | 20 | Waiting for download. | | DOWNLOADING | 21 | Downloading. | @@ -1718,7 +2044,7 @@ Represents an event type. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ---- | ---------- | ---- | | TASK | 0x01000000 | Task event.| @@ -1728,22 +2054,22 @@ Enumerates event IDs. **System capability**: SystemCapability.Update.UpdateService -| Name | Default Value | Description | +| Name | Value | Description | | ---------------------- | ---------- | ------ | -| EVENT_TASK_BASE | 0x01000000 | Indicates a task event. | -| EVENT_TASK_RECEIVE | 0x01000001 | Indicates that a task is received. | -| EVENT_TASK_CANCEL | 0x01000010 | Indicates that a task is cancelled. | -| EVENT_DOWNLOAD_WAIT | 0x01000011 | Indicates the state of waiting for the download. | -| EVENT_DOWNLOAD_START | 0x01000100 | Indicates that the download starts. | -| EVENT_DOWNLOAD_UPDATE | 0x01000101 | Indicates the download progress update.| -| EVENT_DOWNLOAD_PAUSE | 0x01000110 | Indicates that the download is paused. | -| EVENT_DOWNLOAD_RESUME | 0x01000111 | Indicates that the download is resumed. | -| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | Indicates that the download succeeded. | -| EVENT_DOWNLOAD_FAIL | 0x01001001 | Indicates that the download failed. | -| EVENT_UPGRADE_WAIT | 0x01001010 | Indicates the state of waiting for the update. | -| EVENT_UPGRADE_START | 0x01001011 | Indicates that the update starts. | -| EVENT_UPGRADE_UPDATE | 0x01001100 | Indicates that the update is in progress. | -| EVENT_APPLY_WAIT | 0x01001101 | Indicates the state of waiting for applying the update. | -| EVENT_APPLY_START | 0x01001110 | Indicates the state of applying the update. | -| EVENT_UPGRADE_SUCCESS | 0x01001111 | Indicates that the update succeeded. | -| EVENT_UPGRADE_FAIL | 0x01010000 | Indicates that the update failed. | +| EVENT_TASK_BASE | 0x01000000 | Task event. | +| EVENT_TASK_RECEIVE | 0x01000001 | Task received. | +| EVENT_TASK_CANCEL | 0x01000010 | Task cancelled. | +| EVENT_DOWNLOAD_WAIT | 0x01000011 | Waiting for download. | +| EVENT_DOWNLOAD_START | 0x01000100 | Download started. | +| EVENT_DOWNLOAD_UPDATE | 0x01000101 | Download progress update.| +| EVENT_DOWNLOAD_PAUSE | 0x01000110 | Download paused. | +| EVENT_DOWNLOAD_RESUME | 0x01000111 | Download resumed. | +| EVENT_DOWNLOAD_SUCCESS | 0x01001000 | Download succeeded. | +| EVENT_DOWNLOAD_FAIL | 0x01001001 | Download failed. | +| EVENT_UPGRADE_WAIT | 0x01001010 | Waiting for update. | +| EVENT_UPGRADE_START | 0x01001011 | Update started. | +| EVENT_UPGRADE_UPDATE | 0x01001100 | Update in progress. | +| EVENT_APPLY_WAIT | 0x01001101 | Waiting for applying the update. | +| EVENT_APPLY_START | 0x01001110 | Applying the update. | +| EVENT_UPGRADE_SUCCESS | 0x01001111 | Update succeeded. | +| EVENT_UPGRADE_FAIL | 0x01010000 | Update failed. | diff --git a/en/application-dev/reference/apis/js-apis-uri.md b/en/application-dev/reference/apis/js-apis-uri.md index d058b555c87be4fe5f9601ef4b9f9c7198964463..00bf51656958f8ca58b926cb54ad9fd1d82a8e53 100644 --- a/en/application-dev/reference/apis/js-apis-uri.md +++ b/en/application-dev/reference/apis/js-apis-uri.md @@ -1,4 +1,4 @@ -# URI String Parsing +# @ohos.uri (URI String Parsing) > **NOTE** > @@ -29,6 +29,70 @@ import uri from '@ohos.uri' | authority | string | Yes| No| Authority part in the URI.| | ssp | string | Yes| No| Scheme-specific part in the URI.| +### Naming Rules + +Naming format: + +A standard URI consists of the following parts: +[scheme:]scheme-specific-part[#fragment] +- Scheme: scheme component, which is mandatory. Example values: **http**, **https**, **ftp**, **datashare**, and **dataability**. +- scheme-specific-part: specific part of the URI decoding scheme. The value consists of [//][authority][path][?query]. Set this parameter as required. + - authority: decoding authority component of the URI. The value consists of [userinfo@]host[:port]. Set this parameter as required. + - userinfo: user information. Set this parameter as required. + - host: host name of the server. This parameter is mandatory when authority exists. + - port: port number of the server. Set this parameter as required. + - path: path information. Set this parameter as required. + - query: query component. Set this parameter as required. +- fragment: fragment component. Set this parameter as required. + +**Example URIs** + +```js +const result1 = new uri.URI("ftp://ftp.aaa.bbb.ccc/dddd/eee.txt"); +console.log(result1.host) // ftp.aaa.bbb.ccc +console.log(result1.fragment) // null +console.log(result1.path) // /dddd/eee.txt +console.log(result1.scheme) // ftp +console.log(result1.userInfo) // null +console.log(result1.port) // -1 +console.log(result1.query) // null + +const result2 = new uri.URI("gopher://spinaltap.micro.umn.edu/00/Weather/California/Los%20Angeles#fragment"); +console.log(result2.host) // spinaltap.micro.umn.edu +console.log(result2.fragment) // fragment +console.log(result2.path) // /dddd/eee.txt +console.log(result2.scheme) // ftp +console.log(result2.userInfo) // null +console.log(result2.port) //-1 +console.log(result2.query) // null + +const result3 = new uri.URI("datashare:///com.samples.datasharetest.DataShare/DB00/TBL00"); +console.log(result3.host) // null +console.log(result3.fragment) // null +console.log(result3.path) // /com.samples.datasharetest.DataShare/DB00/TBL00 +console.log(result3.scheme) // datashare +console.log(result3.userInfo) // null +console.log(result3.port) // -1 +console.log(result3.query) // null + +const result4 = new uri.URI("https://username:password@host:8080/directory/file?foo=1&bar=2#fragment"); +console.log(result4.host) // host +console.log(result4.fragment) // fragment +console.log(result4.path) // /directory/file +console.log(result4.scheme) // https +console.log(result4.userInfo) // username:password +console.log(result4.port) // 8080 +console.log(result4.query) // foo=1&bar=2 + +const result5 = new uri.URI("dataability:///com.example.DataAbility"); +console.log(result5.host) // null +console.log(result5.fragment) // null +console.log(result5.path) // /com.example.DataAbility: +console.log(result5.scheme) // dataability +console.log(result5.userInfo) // null +console.log(result5.port) // -1 +console.log(result5.query) // null +``` ### constructor @@ -40,18 +104,26 @@ A constructor used to create a URI instance. **Parameters** -| Name| Type.| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| uri | string | Yes| Yes| Input object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| uri | string | Yes| Input object.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200002 | Invalid uri string. | **Example** ```js -let mm = 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; -new uri.URI(mm); // Output 'http://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; +let mm = 'https://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; +new uri.URI(mm); // Output 'https://username:password@host:8080/directory/file?foo=1&bar=2#fragment'; ``` ```js -new uri.URI('http://username:password@host:8080'); // Output 'http://username:password@host:8080'; +new uri.URI('https://username:password@host:8080'); // Output 'https://username:password@host:8080'; ``` @@ -65,46 +137,47 @@ Obtains the query string applicable to this URI. **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | string | Website address in a serialized string.| **Example** ```js -const result = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const result = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); result.toString() ``` ### equals(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. equals(other: URI): boolean Checks whether this URI is the same as another URI object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [equalsTo9+](#equalsto9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type.| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | other | [URI](#uri) | Yes| URI object to compare.| **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the two URIs are the same; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); uriInstance.equals(uriInstance1); ``` ### equalsTo9+ @@ -117,21 +190,21 @@ Checks whether this URI is the same as another URI object. **Parameters** -| Name| Type.| Mandatory| Description| +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | other | [URI](#uri) | Yes| URI object to compare.| **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | boolean | Returns **true** if the two URIs are the same; returns **false** otherwise.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -const uriInstance1 = new uri.URI('http://username:password@host:8080/directory/file?query=pppppp#qwer=da#fragment'); +const uriInstance = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +const uriInstance1 = new uri.URI('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); uriInstance.equalsTo(uriInstance1); ``` @@ -145,14 +218,14 @@ Checks whether this URI is an absolute URI (whether the scheme component is defi **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | -| boolean | Returns **true** if the URI is an absolute URI; returns **false** otherwise.| +| boolean | If the URI is an absolute URI, **true** is returned. Otherwise, **false** is returned.| **Example** ```js -const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080?query=pppppp'); +const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080?query=pppppp'); uriInstance.checkIsAbsolute(); ``` @@ -167,13 +240,14 @@ Normalizes the path of this URI. **Return value** -| Type.| Description| +| Type| Description| | -------- | -------- | | URI | URI with the normalized path.| **Example** + ```js -const uriInstance = new uri.URI('http://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); +const uriInstance = new uri.URI('https://username:password@www.qwer.com:8080/path/path1/../path2/./path3?query=pppppp'); let uriInstance1 = uriInstance.normalize(); uriInstance1.path; ``` diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index 383dd4b3862b849db5e9292d4b841acbc8e3cc33..8a972e121d32b041e1ff7f8319c4e26261afb2f5 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -1,4 +1,4 @@ -# URL String Parsing +# @ohos.url (URL String Parsing) > **NOTE** > @@ -11,10 +11,9 @@ import Url from '@ohos.url' ``` ## URLParams9+ - ### constructor9+ -constructor(init?: string[][] | Record<string, string> | string | URLParams) +constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) A constructor used to create a **URLParams** instance. @@ -24,7 +23,7 @@ A constructor used to create a **URLParams** instance. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| init | string[][] \| Record<string, string> \| string \| URLParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLParams**: object| +| init | string[][] \| Record<string, string> \| string \| URLSearchParams | No| Input parameter objects, which include the following:
- **string[][]**: two-dimensional string array
- **Record<string, string>**: list of objects
- **string**: string
- **URLSearchParams**: object| **Example** @@ -32,7 +31,7 @@ A constructor used to create a **URLParams** instance. let objectParams = new Url.URLParams([ ['user1', 'abc1'], ['query2', 'first2'], ['query3', 'second3'] ]); let objectParams1 = new Url.URLParams({"fod" : '1' , "bard" : '2'}); let objectParams2 = new Url.URLParams('?fod=1&bard=2'); -let urlObject = new Url.URL('https://developer.mozilla.org/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.mozilla.org/?fod=1&bard=2'); let params = new Url.URLParams(urlObject.search); ``` @@ -55,7 +54,7 @@ Appends a key-value pair into the query string. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.append('fod', '3'); ``` @@ -78,9 +77,9 @@ Deletes key-value pairs of the specified key. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -let paramsobject = new Url.URLParams(urlObject.search.slice(1)); -paramsobject.delete('fod'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); +let paramsObject = new Url.URLParams(urlObject.search.slice(1)); +paramsObject.delete('fod'); ``` @@ -88,7 +87,7 @@ paramsobject.delete('fod'); getAll(name: string): string[] -Obtains all the key-value pairs based on the specified key. +Obtains all the key-value pairs based on the specified name. **System capability**: SystemCapability.Utils.Lang @@ -102,12 +101,12 @@ Obtains all the key-value pairs based on the specified key. | Type| Description| | -------- | -------- | -| string[] | All key-value pairs matching the specified key.| +| string[] | Key-value pairs obtained.| **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let params = new Url.URLParams(urlObject.search.slice(1)); params.append('fod', '3'); // Add a second value for the fod parameter. console.log(params.getAll('fod').toString()) // Output ["1","3"]. @@ -132,7 +131,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ```js let searchParamsObject = new Url.URLParams("keyName1=valueName1&keyName2=valueName2"); -for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs +for (var pair of searchParamsObject.entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } ``` @@ -140,7 +139,7 @@ for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pair ### forEach9+ -forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void +forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. @@ -150,10 +149,10 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| -**Table 1** callbackfn parameter description +**Table 1** callbackFn parameter description | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -164,9 +163,9 @@ Traverses the key-value pairs in the **URLSearchParams** instance by using a cal **Example** ```js -const myURLObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); -myURLObject.URLParams.forEach((value, name, searchParams) => { - console.log(name, value, myURLObject.searchParams === searchParams); +const myURLObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); +myURLObject.params.forEach((value, name, searchParams) => { + console.log(name, value, myURLObject.params === searchParams); }); ``` @@ -224,7 +223,7 @@ Checks whether a key has a value. **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.has('bard') === true; ``` @@ -248,7 +247,7 @@ Sets the value for a key. If key-value pairs matching the specified key exist, t **Example** ```js -let urlObject = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let urlObject = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let paramsObject = new Url.URLParams(urlObject.search.slice(1)); paramsObject.set('baz', '3'); // Add a third parameter. ``` @@ -360,24 +359,163 @@ Obtains search parameters that are serialized as a string and, if necessary, per **Example** ```js -let url = new Url.URL('https://developer.exampleUrl/?fod=1&bard=2'); +let url = Url.URL.parseURL('https://developer.exampleUrl/?fod=1&bard=2'); let params = new Url.URLParams(url.search.slice(1)); params.append('fod', '3'); console.log(params.toString()); ``` -## URLSearchParams(deprecated) +## URL + +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.| +| host | string | Yes| Yes| Host information in a URL.| +| hostname | string | Yes| Yes| Hostname (without the port) in a URL.| +| href | string | Yes| Yes| String that contains the whole URL.| +| origin | string | Yes| No| Read-only string that contains the Unicode serialization of the origin of the represented URL.| +| password | string | Yes| Yes| Password in a URL.| +| pathname | string | Yes| Yes| Path in a URL.| +| port | string | Yes| Yes| Port in a URL.| +| protocol | string | Yes| Yes| Protocol in a URL.| +| search | string | Yes| Yes| Serialized query string in a URL.| +| searchParams(deprecated) | [URLSearchParams](#urlsearchparamsdeprecated) | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.
- **NOTE**: This attribute is supported since API version 7 and is deprecated since API version 9. You are advised to use params9+ instead.| +| params9+ | [URLParams](#urlparams9) | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| +| username | string | Yes| Yes| Username in a URL.| ### constructor(deprecated) > **NOTE** > -> This API is deprecated since API version 9. You are advised to use [URLParams9+](#constructor9+) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [parseURL9+](#parseurl9) instead. + +constructor(url: string, base?: string | URL) + +Creates a URL. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Input object.| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| + +**Example** + +```js +let mm = 'https://username:password@host:8080'; +let a = new Url.URL("/", mm); // Output 'https://username:password@host:8080/'; +let b = new Url.URL(mm); // Output 'https://username:password@host:8080/'; +new Url.URL('path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +let c = new Url.URL('/path/path1', b); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', c); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', a); // Output 'https://username:password@host:8080/path/path1'; +new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 +new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL +new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL +new Url.URL('https://www.example.com', ); // Output https://www.example.com/ +new Url.URL('https://www.example.com', b); // Output https://www.example.com/ +``` + +### constructor9+ + +constructor() + +A no-argument constructor used to create a URL. It returns a **URL** object after **parseURL** is called. It is not used independently. + +**System capability**: SystemCapability.Utils.Lang + +### parseURL9+ + +static parseURL(url : string, base?: string | URL): URL + +Parses a URL. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| url | string | Yes| Input object.| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200002 | Invalid url string. | + + +**Example** + +```js +let mm = 'https://username:password@host:8080'; +let url = Url.URL.parseURL(mm); +url.toString(); // Output 'https://username:password@host:8080/'; +``` + +### tostring + +toString(): string + +Converts the parsed URL into a string. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| + +**Example** + +```js +const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +url.toString(); +``` + +### toJSON + +toJSON(): string + +Converts the parsed URL into a JSON string. + +**System capability**: SystemCapability.Utils.Lang + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Website address in a serialized string.| + +**Example** +```js +const url = Url.URL.parseURL('https://username:password@host:8080/directory/file?query=pppppp#qwer=da'); +url.toJSON(); +``` + +## URLSearchParams(deprecated) + +### constructor(deprecated) constructor(init?: string[][] | Record<string, string> | string | URLSearchParams) A constructor used to create a **URLSearchParams** instance. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -398,14 +536,14 @@ let params = new Url.URLSearchParams(urlObject.search); ### append(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.append9+](#append9) instead. - append(name: string, value: string): void Appends a key-value pair into the query string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.append9+](#append9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -425,14 +563,14 @@ paramsObject.append('fod', '3'); ### delete(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.delete9+](#delete9) instead. - delete(name: string): void Deletes key-value pairs of the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.delete9+](#delete9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -451,14 +589,14 @@ paramsobject.delete('fod'); ### getAll(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.getAll9+](#getall9) instead. - getAll(name: string): string[] Obtains all the key-value pairs based on the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.getAll9+](#getall9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -484,14 +622,14 @@ console.log(params.getAll('fod').toString()) // Output ["1","3"]. ### entries(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.entries9+](#entries9) instead. - entries(): IterableIterator<[string, string]> Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.entries9+](#entries9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -504,31 +642,32 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th ```js let searchParamsObject = new Url.URLSearchParams("keyName1=valueName1&keyName2=valueName2"); -for (var pair of searchParamsObject .entries()) { // Show keyName/valueName pairs +for (var pair of searchParamsObject.entries()) { // Show keyName/valueName pairs console.log(pair[0]+ ', '+ pair[1]); } ``` ### forEach(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.forEach9+](#foreach9) instead. -forEach(callbackfn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void +forEach(callbackFn: (value: string, key: string, searchParams: this) => void, thisArg?: Object): void Traverses the key-value pairs in the **URLSearchParams** instance by using a callback. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.forEach9+](#foreach9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| -| thisArg | Object | No| Value to use when the callback is invoked.| +| callbackFn | function | Yes| Callback invoked to traverse the key-value pairs in the **URLSearchParams** instance.| +| thisArg | Object | No| Value of **this** to use when **callbackFn** is invoked.| -**Table 1** callbackfn parameter description +**Table 1** callbackFn parameter description | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -547,14 +686,15 @@ myURLObject.searchParams.forEach((value, name, searchParams) => { ### get(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.get9+](#get9) instead. get(name: string): string | null Obtains the value of the first key-value pair based on the specified key. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.get9+](#get9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -580,14 +720,15 @@ let age = parseInt(paramsObject.get("age"), 10); // is the number 18 ### has(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.has9+](#has9) instead. has(name: string): boolean Checks whether a key has a value. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.has9+](#has9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -612,14 +753,15 @@ paramsObject.has('bard') === true; ### set(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.set9+](#set9) instead. set(name: string, value: string): void Sets the value for a key. If key-value pairs matching the specified key exist, the value of the first key-value pair will be set to the specified value and other key-value pairs will be deleted. Otherwise, the key-value pair will be appended to the query string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.set9+](#set9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -639,14 +781,15 @@ paramsObject.set('baz', '3'); // Add a third parameter. ### sort(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.sort9+](#sort9) instead. sort(): void Sorts all key-value pairs contained in this object based on the Unicode code points of the keys and returns undefined. This method uses a stable sorting algorithm, that is, the relative order between key-value pairs with equal keys is retained. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.sort9+](#sort9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -659,14 +802,15 @@ console.log(searchParamsObject.toString()); // Display the sorted query string / ### keys(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.keys9+](#keys9) instead. keys(): IterableIterator<string> Obtains an ES6 iterator that contains the keys of all the key-value pairs. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.keys9+](#keys9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -686,14 +830,15 @@ for (var key of searchParamsObject .keys()) { // Output key-value pairs ### values(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.values9+](#values9) instead. values(): IterableIterator<string> Obtains an ES6 iterator that contains the values of all the key-value pairs. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [URLParams9+.values9+](#values9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -714,15 +859,14 @@ for (var value of searchParams.values()) { ### [Symbol.iterator](deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [[Symbol.iterator]9+](#symboliterator9) instead. - - [Symbol.iterator]\(): IterableIterator<[string, string]> Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and the first and second fields of each array are the key and value respectively. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [Symbol.iterator]9+](#symboliterator9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -741,14 +885,15 @@ for (const [name, value] of paramsObject) { ``` ### tostring(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [URLParams9+.tostring9+](#tostring9) instead. toString(): string Obtains search parameters that are serialized as a string and, if necessary, percent-encodes the characters in the string. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [tostring9+](#tostring9) instead. + **System capability**: SystemCapability.Utils.Lang **Return value** @@ -765,123 +910,4 @@ let params = new Url.URLSearchParams(url.search.slice(1)); params.append('fod', '3'); console.log(params.toString()); ``` - -## URL - -### Attributes - -**System capability**: SystemCapability.Utils.Lang - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| hash | string | Yes| Yes| String that contains a harsh mark (#) followed by the fragment identifier of a URL.| -| host | string | Yes| Yes| Host information in a URL.| -| hostname | string | Yes| Yes| Hostname (without the port) in a URL.| -| href | string | Yes| Yes| String that contains the whole URL.| -| origin | string | Yes| No| Read-only string that contains the Unicode serialization of the origin of the represented URL.| -| password | string | Yes| Yes| Password in a URL.| -| pathname | string | Yes| Yes| Path in a URL.| -| port | string | Yes| Yes| Port in a URL.| -| protocol | string | Yes| Yes| Protocol in a URL.| -| search | string | Yes| Yes| Serialized query string in a URL.| -| searchParams | URLsearchParams | Yes| No| **URLSearchParams** object allowing access to the query parameters in a URL.| -| URLParams | URLParams | Yes| No| **URLParams** object allowing access to the query parameters in a URL.| -| username | string | Yes| Yes| Username in a URL.| - - -### constructor - -constructor(url?: string, base?: string | URL) - -Creates a URL. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| - -**Example** - -```js -let mm = 'http://username:password@host:8080'; -let a = new Url.URL("/", mm); // Output 'http://username:password@host:8080/'; -let b = new Url.URL(mm); // Output 'http://username:password@host:8080/'; -new Url.URL('path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -let c = new Url.URL('/path/path1', b); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', c); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', a); // Output 'http://username:password@host:8080/path/path1'; -new Url.URL('/path/path1', "https://www.exampleUrl/fr-FR/toto"); // Output https://www.exampleUrl/path/path1 -new Url.URL('/path/path1', ''); // Raises a TypeError exception as '' is not a valid URL -new Url.URL('/path/path1'); // Raises a TypeError exception as '/path/path1' is not a valid URL -new Url.URL('http://www.shanxi.com', ); // Output http://www.shanxi.com/ -new Url.URL('http://www.shanxi.com', b); // Output http://www.shanxi.com/ -``` - -### parseURL9+ - -static parseURL(inputUrl : string, inputBase ?: string | URL) - -Parses a URL. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| inputUrl | string | Yes| Input object.| -| inputBase | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| - -**Example** - -```js -let mm = 'http://username:password@host:8080'; -Url.URL.parseURL(mm); // Output 'http://username:password@host:8080/'; -``` - -### tostring - -toString(): string - -Converts the parsed URL into a string. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Website address in a serialized string.| - -**Example** - -```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toString(); -``` - - -### toJSON - -toJSON(): string - -Converts the parsed URL into a JSON string. - -**System capability**: SystemCapability.Utils.Lang - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Website address in a serialized string.| - -**Example** -```js -const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toJSON(); -``` diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md new file mode 100644 index 0000000000000000000000000000000000000000..68a127a08bdfd1df0ca558866dc3cde577e2b25a --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -0,0 +1,859 @@ +# @ohos.usb (USB Management) + +The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. + +## Modules to Import + +```js +import usb from "@ohos.usb"; +``` + +## usb.getDevices + +getDevices(): Array<Readonly<USBDevice>> + +Obtains the USB device list. + +**System capability**: SystemCapability.USB.USBManager + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------- | +| Array<Readonly<[USBDevice](#usbdevice)>> | Device information list.| + +**Example** + +```js +let devicesList = usb.getDevices(); +console.log(`devicesList = ${JSON.stringify(devicesList)}`); +// devicesList is a list of USB devices. +// A simple example of devicesList is provided as follows: +[ + { + name: "1-1", + serial: "", + manufacturerName: "", + productName: "", + version: "", + vendorId: 7531, + productId: 2, + clazz: 9, + subclass: 0, + protocol: 1, + devAddress: 1, + busNum: 1, + configs: [ + { + id: 1, + attributes: 224, + isRemoteWakeup: true, + isSelfPowered: true, + maxPower: 0, + name: "1-1", + interfaces: [ + { + id: 0, + protocol: 0, + clazz: 9, + subclass: 0, + alternateSetting: 0, + name: "1-1", + endpoints: [ + { + address: 129, + attributes: 3, + interval: 12, + maxPacketSize: 4, + direction: 128, + number: 1, + type: 3, + interfaceId: 0, + }, + ], + }, + ], + }, + ], + }, +] +``` + +## usb.connectDevice + +connectDevice(device: USBDevice): Readonly<USBDevicePipe> + +Connects to a USB device. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, and then call [usb.requestRight](#usbrequestright) to request the device access permission. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| device | [USBDevice](#usbdevice) | Yes| USB device information.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Readonly<[USBDevicePipe](#usbdevicepipe)> | USB device pipe for data transfer.| + +**Example** + +```js +let devicepipe= usb.connectDevice(device); +console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); +``` + +## usb.hasRight + +hasRight(deviceName: string): boolean + +Checks whether the application has the permission to access the device. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceName | string | Yes| Device name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | The value **true** indicates that the application has the permission to access the device, and the value **false** indicates the opposite.| + +**Example** + +```js +let devicesName="1-1"; +let bool = usb.hasRight(devicesName); +console.log(bool); +``` + +## usb.requestRight + +requestRight(deviceName: string): Promise<boolean> + +Requests the temporary permission for the application to access the USB device. This API uses a promise to return the result. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceName | string | Yes| Device name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted, and the value **false** indicates the opposite.| + +**Example** + +```js +let devicesName="1-1"; +usb.requestRight(devicesName).then((ret) => { + console.log(`requestRight = ${JSON.stringify(ret)}`); +}); +``` + +## usb.claimInterface + +claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number + +Claims a USB interface. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and USB interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| +| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to claim.| +| force | boolean | No| Whether to forcibly claim the USB interface. The default value is **false**, indicating not to forcibly claim the USB interface.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | The value **0** indicates that the USB interface is successfully claimed, and an error code indicates the opposite.| + +**Example** + +```js +let ret = usb.claimInterface(devicepipe, interfaces); +console.log(`claimInterface = ${ret}`); +``` + +## usb.releaseInterface + +releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number + +Releases a USB interface. + +Before you do this, ensure that you have claimed the interface by calling [usb.claimInterface](#usbclaiminterface). + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| +| iface | [USBInterface](#usbinterface) | Yes| USB interface, which is used to determine the index of the interface to release.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | The value **0** indicates that the USB interface is successfully released, and an error code indicates the opposite.| + +**Example** + +```js +let ret = usb.releaseInterface(devicepipe, interfaces); +console.log(`releaseInterface = ${ret}`); +``` + +## usb.setConfiguration + +setConfiguration(pipe: USBDevicePipe, config: USBConfig): number + +Sets the device configuration. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device configuration, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| +| config | [USBConfig](#usbconfig) | Yes| USB configuration to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | The value **0** indicates that the USB configuration is successfully set, and an error code indicates the opposite.| + +**Example** + +```js +let ret = usb.setConfiguration(devicepipe, config); +console.log(`setConfiguration = ${ret}`); +``` + +## usb.setInterface + +setInterface(pipe: USBDevicePipe, iface: USBInterface): number + +Sets a USB interface. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and interfaces, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name | Type | Mandatory | Description | +| ----- | ------------------------------- | --- | ------------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes | Device pipe, which is used to determine the bus number and device address.| +| iface | [USBInterface](#usbinterface) | Yes | USB interface to set. | + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | The value **0** indicates that the USB interface is successfully set, and an error code indicates the opposite.| + +**Example** + +```js +let ret = usb.setInterface(devicepipe, interfaces); +console.log(`setInterface = ${ret}`); +``` + +## usb.getRawDescriptor + +getRawDescriptor(pipe: USBDevicePipe): Uint8Array + +Obtains the raw USB descriptor. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Uint8Array | The return value is the raw USB descriptor if the operation is successful, or **undefined** if the operation has failed.| + +**Example** + +```js +let ret = usb.getRawDescriptor(devicepipe); +``` + +## usb.getFileDescriptor + +getFileDescriptor(pipe: USBDevicePipe): number + +Obtains the file descriptor. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| Device pipe, which is used to determine the bus number and device address.| + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| number | The return value is the file descriptor of the USB device if the operation is successful, or **-1** if the operation has failed.| + +**Example** + +```js +let ret = usb.getFileDescriptor(devicepipe); +``` + +## usb.controlTransfer + +controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout?: number): Promise<number> + +Performs control transfer. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| +| controlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.| +| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.| + +**Example** + +```js +usb.controlTransfer(devicepipe, USBControlParams).then((ret) => { + console.log(`controlTransfer = ${JSON.stringify(ret)}`); +}) +``` + +## usb.bulkTransfer + +bulkTransfer(pipe: USBDevicePipe, endpoint: USBEndpoint, buffer: Uint8Array, timeout?: number): Promise<number> + +Performs bulk transfer. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and endpoints, call [usb.requestRight](#usbrequestright) to request the device access permission, call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter, and call [usb.claimInterface](#usbclaiminterface) to claim the USB interface. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| +| endpoint | [USBEndpoint](#usbendpoint) | Yes| USB endpoint, which is used to determine the USB port for data transfer.| +| buffer | Uint8Array | Yes| Buffer for writing or reading data.| +| timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the result, which is the size of the transmitted or received data block if the transfer is successful, or **-1** if an exception has occurred.| + +**Example** + +```js +// Call usb.getDevices to obtain a data set. Then, obtain a USB device and its access permission. +// Pass the obtained USB device as a parameter to usb.connectDevice. Then, call usb.connectDevice to connect the USB device. +// Call usb.claimInterface to claim the USB interface. After that, call usb.bulkTransfer to start bulk transfer. +usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { + console.log(`bulkTransfer = ${JSON.stringify(ret)}`); +}); +``` + +## usb.closePipe + +closePipe(pipe: USBDevicePipe): number + +Closes a USB device pipe. + +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, call [usb.requestRight](#usbrequestright) to request the device access permission, and call [usb.connectDevice](#usbconnectdevice) to obtain **devicepipe** as an input parameter. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | The value **0** indicates that the USB device pipe is closed successfully, and an error code indicates the opposite.| + +**Example** + +```js +let ret = usb.closePipe(devicepipe); +console.log(`closePipe = ${ret}`); +``` + +## usb.usbFunctionsFromString9+ + +usbFunctionsFromString(funcs: string): number + +Converts the USB function list in the string format to a numeric mask in Device mode. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| funcs | string | Yes | Function list in string format.| + +**Return value** + +| Type | Description | +| ------ | ------------------ | +| number | Function list in numeric mask format.| + +**Example** + +```js +let funcs = "acm"; +let ret = usb.usbFunctionsFromString(funcs); +``` + +## usb.usbFunctionsToString9+ + +usbFunctionsToString(funcs: FunctionType): string + +Converts the USB function list in the numeric mask format to a string in Device mode. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ----------------- | +| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.| + +**Return value** + +| Type | Description | +| ------ | ------------------------------ | +| string | Function list in string format.| + +**Example** + +```js +let funcs = ACM | ECM; +let ret = usb.usbFunctionsToString(funcs); +``` + +## usb.setCurrentFunctions9+ + +setCurrentFunctions(funcs: FunctionType): Promise\ + +Sets the current USB function list in Device mode. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ----------------- | +| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.| + +**Return value** + +| Type | Description | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| + +**Example** + +```js +let funcs = HDC; +let ret = usb.setCurrentFunctions(funcs); +``` + +## usb.getCurrentFunctions9+ + +getCurrentFunctions(): FunctionType + +Obtains the numeric mask combination for the USB function list in Device mode. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Return value** + +| Type | Description | +| ------------------------------ | --------------------------------- | +| [FunctionType](#functiontype9) | Numeric mask combination for the USB function list.| + +**Example** + +```js +let ret = usb.getCurrentFunctions(); +``` + +## usb.getPorts9+ + +getPorts(): Array\ + +Obtains the list of all physical USB ports. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Return value** + +| Type | Description | +| ----------------------------- | --------------------- | +| [Array\](#usbport9) | List of physical USB ports.| + +**Example** + +```js +let ret = usb.getPorts(); +``` + +## usb.getSupportedModes9+ + +getSupportedModes(portId: number): PortModeType + +Obtains the mask combination for the supported mode list of a given USB port. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------- | +| portId | number | Yes | Port number.| + +**Return value** + +| Type | Description | +| ------------------------------ | -------------------------- | +| [PortModeType](#portmodetype9) | Mask combination for the supported mode list.| + +**Example** + +```js +let ret = usb.getSupportedModes(0); +``` + +## usb.setPortRoles9+ + +setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ + +Sets the role types supported by a specified port, which can be **powerRole** (for charging) and **dataRole** (for data transfer). + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | -------------------------------- | ---- | ---------------- | +| portId | number | Yes | Port number. | +| powerRole | [PowerRoleType](#powerroletype9) | Yes | Role for charging. | +| dataRole | [DataRoleType](#dataroletype9) | Yes | Role for data transfer.| + +**Return value** + +| Type | Description | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | Promise used to return the result. The value **true** indicates that the operation is successful, and the value **false** indicates the opposite.| + +**Example** + +```js +let ret = usb.getSupportedModes(0); +``` + +## USBEndpoint + +Represents the USB endpoint from which data is sent or received. You can obtain the USB endpoint through [USBInterface](#usbinterface). + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| address | number | Yes | Endpoint address. | +| attributes | number | Yes | Endpoint attributes. | +| interval | number | Yes | Endpoint interval. | +| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. | +| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. | +| number | number | Yes | Endpoint number. | +| type | number | Yes | Endpoint type. | +| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.| + +## USBInterface + +Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **USBInterface** instances, each providing a specific function. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| id | number | Yes | Unique ID of the USB interface. | +| protocol | number | Yes | Interface protocol. | +| clazz | number | Yes | Device type. | +| subClass | number | Yes | Device subclass. | +| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.| +| name | string | Yes | Interface name. | +| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes | Endpoints that belong to the USB interface. | + +## USBConfig + +Represents the USB configuration. One [USBDevice](#usbdevice) can contain multiple **USBConfig** instances. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| id | number | Yes | Unique ID of the USB configuration. | +| attributes | number | Yes | Configuration attributes. | +| maxPower | number | Yes | Maximum power consumption, in mA. | +| name | string | Yes | Configuration name, which can be left empty. | +| isRemoteWakeup | boolean | Yes | Support for remote wakeup.| +| isSelfPowered | boolean | Yes | Support for independent power supplies.| +| interfaces | Array <[USBInterface](#usbinterface)> | Yes | Supported interface attributes. | + +## USBDevice + +Represents the USB device information. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| busNum | number | Yes | Bus address. | +| devAddress | number | Yes | Device address. | +| serial | string | Yes | Sequence number. | +| name | string | Yes | Device name. | +| manufacturerName | string | Yes | Device manufacturer. | +| productName | string | Yes | Product name. | +| version | string | Yes | Version number. | +| vendorId | number | Yes | Vendor ID. | +| productId | number | Yes | Product ID. | +| clazz | number | Yes | Device class. | +| subClass | number | Yes | Device subclass. | +| protocol | number | Yes | Device protocol code. | +| configs | Array<[USBConfig](#usbconfig)> | Yes | Device configuration descriptor information.| + +## USBDevicePipe + +Represents a USB device pipe, which is used to determine a USB device. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| busNum | number | Yes | Bus address.| +| devAddress | number | Yes | Device address.| + +## USBControlParams + +Represents control transfer parameters. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| request | number | Yes | Request type. | +| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. | +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. | +| value | number | Yes | Request parameter value. | +| index | number | Yes | Index of the request parameter value.| +| data | Uint8Array | Yes | Buffer for writing or reading data. | + +## USBPort9+ + +Represents a USB port. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| id | number | Yes | Unique identifier of a USB port. | +| supportedModes | [PortModeType](#portmodetype9) | Yes | Numeric mask combination for the supported mode list.| +| status | [USBPortStatus](#usbportstatus9) | Yes | USB port role. | + +## USBPortStatus9+ + +Enumerates USB port roles. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Type | Mandatory | Description | +| -------- | ------- | --------- | ----------- | +| currentMode | number | Yes | Current USB mode. | +| currentPowerRole | number | Yes | Current power role. | +| currentDataRole | number | Yes | Current data role. | + +## USBRequestTargetType + +Enumerates request target types. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ---------------------------- | ---- | ------ | +| USB_REQUEST_TARGET_DEVICE | 0 | Device.| +| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.| +| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint.| +| USB_REQUEST_TARGET_OTHER | 3 | Other.| + +## USBControlRequestType + +Enumerates control request types. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------------------------- | ---- | ------ | +| USB_REQUEST_TYPE_STANDARD | 0 | Standard.| +| USB_REQUEST_TYPE_CLASS | 1 | Class. | +| USB_REQUEST_TYPE_VENDOR | 2 | Vendor.| + +## USBRequestDirection + +Enumerates request directions. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| --------------------------- | ---- | ------------------------ | +| USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.| +| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.| + +## FunctionType9+ + +Enumerates USB device function types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------------ | ---- | ---------- | +| NONE | 0 | No function.| +| ACM | 1 | ACM function. | +| ECM | 2 | ECM function. | +| HDC | 4 | HDC function. | +| MTP | 8 | Not supported currently.| +| PTP | 16 | Not supported currently.| +| RNDIS | 32 | Not supported currently.| +| MIDI | 64 | Not supported currently.| +| AUDIO_SOURCE | 128 | Not supported currently.| +| NCM | 256 | Not supported currently.| + +## PortModeType9+ + +Enumerates USB port mode types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| --------- | ---- | ---------------------------------------------------- | +| NONE | 0 | None. | +| UFP | 1 | Upstream facing port, which functions as the sink of power supply. | +| DFP | 2 | Downstream facing port, which functions as the source of power supply. | +| DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.| +| NUM_MODES | 4 | Not supported currently. | + +## PowerRoleType9+ + +Enumerates power role types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------ | ---- | ---------- | +| NONE | 0 | None. | +| SOURCE | 1 | External power supply.| +| SINK | 2 | Internal power supply.| + +## DataRoleType9+ + +Enumerates data role types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +| Name | Value | Description | +| ------ | ---- | ------------ | +| NONE | 0 | None. | +| HOST | 1 | USB host.| +| DEVICE | 2 | USB device.| diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md index d21f6372b5fe26f6e8aeded00e3245b2def23428..9035d2d040209f44a019fb69b3da6edc49b481b3 100644 --- a/en/application-dev/reference/apis/js-apis-usb.md +++ b/en/application-dev/reference/apis/js-apis-usb.md @@ -1,22 +1,21 @@ -# USB +# @ohos.usbV9 (USB Management) -The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control. +The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side. -> **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. +> **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 usb from "@ohos.usb"; +import usb from "@ohos.usbV9"; ``` ## usb.getDevices getDevices(): Array<Readonly<USBDevice>> -Obtains the USB device list. +Obtains the list of USB devices connected to the host. If no device is connected, an empty list is returned. **System capability**: SystemCapability.USB.USBManager @@ -24,7 +23,7 @@ Obtains the USB device list. | Type | Description | | ---------------------------------------------------- | ------- | -| Array<Readonly<[USBDevice](#usbdevice)>> | Device information list.| +| Array<Readonly<[USBDevice](#usbdevice)>> | USB device list.| **Example** @@ -87,9 +86,9 @@ console.log(`devicesList = ${JSON.stringify(devicesList)}`); connectDevice(device: USBDevice): Readonly<USBDevicePipe> -Connects to a USB device. +Connects to a USB device based on the device list obtained by using **getDevices()**. -Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list, and then call [usb.requestRight](#usbrequestright) to request the device access permission. +Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB device list and device information, and then call [usb.requestRight](#usbrequestright) to request the device access permission. **System capability**: SystemCapability.USB.USBManager @@ -105,10 +104,26 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | -------- | -------- | | Readonly<[USBDevicePipe](#usbdevicepipe)> | USB device pipe for data transfer.| +**Error codes** + +For details about the error codes, see [USB Error Codes](../errorcodes/errorcode-usb.md). + +| ID| Error Message| +| -------- | -------- | +| 14400001 |Permission denied. Need call requestRight to get permission. | + **Example** ```js -let devicepipe= usb.connectDevice(device); +let devicesList = usb.getDevices(); +if (devicesList.length == 0) { + console.log(`device list is empty`); + return; +} + +let device = devicesList[0]; +usb.requestRight(device.name); +let devicepipe = usb.connectDevice(device); console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); ``` @@ -118,6 +133,8 @@ hasRight(deviceName: string): boolean Checks whether the application has the permission to access the device. +The value **true** is returned if the device access permission is available; the value **false** is returned otherwise. + **System capability**: SystemCapability.USB.USBManager **Parameters** @@ -130,7 +147,7 @@ Checks whether the application has the permission to access the device. | Type| Description| | -------- | -------- | -| boolean | The value **true** indicates that the application has the permission to access the device, and the value **false** indicates the opposite.| +| boolean | Returns **true** if the application has the permission to access the device; returns **false** otherwise.| **Example** @@ -144,7 +161,7 @@ console.log(bool); requestRight(deviceName: string): Promise<boolean> -Requests the temporary permission for the application to access the USB device. This API uses a promise to return the result. +Requests the temporary permission for the application to access a USB device. This API uses a promise to return the result. **System capability**: SystemCapability.USB.USBManager @@ -158,7 +175,7 @@ Requests the temporary permission for the application to access the USB device. | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted, and the value **false** indicates the opposite.| +| Promise<boolean> | Promise used to return the result. The value **true** indicates that the temporary device access permissions are granted; and the value **false** indicates the opposite.| **Example** @@ -169,6 +186,70 @@ usb.requestRight(devicesName).then((ret) => { }); ``` +## usb.removeRight + +removeRight(deviceName: string): boolean + +Removes the permission for the application to access a USB device. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceName | string | Yes| Device name.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Permission removal result. The value **true** indicates that the access permission is removed successfully; and the value **false** indicates the opposite.| + +**Example** + +```js +let devicesName="1-1"; +if (usb.removeRight(devicesName) { + console.log(`Succeed in removing right`); +} +``` + +## usb.addRight + +addRight(bundleName: string, deviceName: string): boolean + +Adds the permission for the application to access a USB device. + +[requestRight](#usbrequestright) triggers a dialog box to request for user authorization, whereas **addRight** adds the access permission directly without displaying a dialog box. + +**System API**: This is a system API. + +**System capability**: SystemCapability.USB.USBManager + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| deviceName | string | Yes| Device name.| +| bundleName | string | Yes| Bundle name of the application.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Permission addition result. The value **true** indicates that the access permission is added successfully; and the value **false** indicates the opposite.| + +**Example** + +```js +let devicesName = "1-1"; +let bundleName = "com.example.hello"; +if (usb.addRight(bundleName, devicesName) { + console.log(`Succeed in adding right`); +} +``` + ## usb.claimInterface claimInterface(pipe: USBDevicePipe, iface: USBInterface, force?: boolean): number @@ -191,7 +272,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | Type| Description| | -------- | -------- | -| number | The value **0** indicates that the USB interface is successfully claimed, and an error code indicates the opposite.| +| number | Returns **0** if the USB interface is successfully claimed; returns an error code otherwise.| **Example** @@ -221,7 +302,7 @@ Before you do this, ensure that you have claimed the interface by calling [usb.c | Type| Description| | -------- | -------- | -| number | The value **0** indicates that the USB interface is successfully released, and an error code indicates the opposite.| +| number | Returns **0** if the USB interface is successfully released; returns an error code otherwise.| **Example** @@ -251,7 +332,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | Type| Description| | -------- | -------- | -| number | The value **0** indicates that the USB configuration is successfully set, and an error code indicates the opposite.| +| number | Returns **0** if the USB configuration is successfully set; returns an error code otherwise.| **Example** @@ -281,7 +362,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | Type| Description| | -------- | -------- | -| number | The value **0** indicates that the USB interface is successfully set, and an error code indicates the opposite.| +| number | Returns **0** if the USB interface is successfully set; returns an error code otherwise.| **Example** @@ -310,7 +391,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | Type| Description| | -------- | -------- | -| Uint8Array | The return value is the raw USB descriptor if the operation is successful, or **undefined** if the operation has failed.| +| Uint8Array | Returns the raw USB descriptor if the operation is successful; returns **undefined** otherwise.| **Example** @@ -338,7 +419,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | Type | Description | | ------ | -------------------- | -| number | The return value is the file descriptor of the USB device if the operation is successful, or **-1** if the operation has failed.| +| number | Returns the file descriptor of the USB device if the operation is successful; returns **-1** otherwise.| **Example** @@ -348,7 +429,7 @@ let ret = usb.getFileDescriptor(devicepipe); ## usb.controlTransfer -controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise<number> +controlTransfer(pipe: USBDevicePipe, controlparam: USBControlParams, timeout?: number): Promise<number> Performs control transfer. @@ -361,7 +442,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | pipe | [USBDevicePipe](#usbdevicepipe) | Yes| USB device pipe, which is used to determine the USB device.| -| contrlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.| +| controlparam | [USBControlParams](#usbcontrolparams) | Yes| Control transfer parameters.| | timeout | number | No| Timeout duration in ms. This parameter is optional. The default value is **0**, indicating no timeout.| **Return value** @@ -434,7 +515,7 @@ Before you do this, call [usb.getDevices](#usbgetdevices) to obtain the USB devi | Type| Description| | -------- | -------- | -| number | The value **0** indicates that the USB device pipe is closed successfully, and an error code indicates the opposite.| +| number | Returns **0** if the USB device pipe is closed successfully; returns an error code otherwise.| **Example** @@ -443,7 +524,7 @@ let ret = usb.closePipe(devicepipe); console.log(`closePipe = ${ret}`); ``` -## usb.usbFunctionsFromString9+ +## usb.usbFunctionsFromString usbFunctionsFromString(funcs: string): number @@ -472,7 +553,7 @@ let funcs = "acm"; let ret = usb.usbFunctionsFromString(funcs); ``` -## usb.usbFunctionsToString9+ +## usb.usbFunctionsToString usbFunctionsToString(funcs: FunctionType): string @@ -486,7 +567,7 @@ Converts the USB function list in the numeric mask format to a string in Device | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ----------------- | -| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.| +| funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| **Return value** @@ -501,7 +582,7 @@ let funcs = ACM | ECM; let ret = usb.usbFunctionsToString(funcs); ``` -## usb.setCurrentFunctions9+ +## usb.setCurrentFunctions setCurrentFunctions(funcs: FunctionType): Promise\ @@ -515,7 +596,7 @@ Sets the current USB function list in Device mode. | Name| Type | Mandatory| Description | | ------ | ------------------------------ | ---- | ----------------- | -| funcs | [FunctionType](#functiontype9) | Yes | USB function list in numeric mask format.| +| funcs | [FunctionType](#functiontype) | Yes | USB function list in numeric mask format.| **Return value** @@ -530,7 +611,7 @@ let funcs = HDC; let ret = usb.setCurrentFunctions(funcs); ``` -## usb.getCurrentFunctions9+ +## usb.getCurrentFunctions getCurrentFunctions(): FunctionType @@ -544,7 +625,7 @@ Obtains the numeric mask combination for the USB function list in Device mode. | Type | Description | | ------------------------------ | --------------------------------- | -| [FunctionType](#functiontype9) | Numeric mask combination for the USB function list.| +| [FunctionType](#functiontype) | Numeric mask combination for the USB function list.| **Example** @@ -552,7 +633,7 @@ Obtains the numeric mask combination for the USB function list in Device mode. let ret = usb.getCurrentFunctions(); ``` -## usb.getPorts9+ +## usb.getPorts getPorts(): Array\ @@ -566,7 +647,7 @@ Obtains the list of all physical USB ports. | Type | Description | | ----------------------------- | --------------------- | -| [Array\](#usbport9) | List of physical USB ports.| +| [Array\](#usbport) | List of physical USB ports.| **Example** @@ -574,7 +655,7 @@ Obtains the list of all physical USB ports. let ret = usb.getPorts(); ``` -## usb.getSupportedModes9+ +## usb.getSupportedModes getSupportedModes(portId: number): PortModeType @@ -594,7 +675,7 @@ Obtains the mask combination for the supported mode list of a given USB port. | Type | Description | | ------------------------------ | -------------------------- | -| [PortModeType](#portmodetype9) | Mask combination for the supported mode list.| +| [PortModeType](#portmodetype) | Mask combination for the supported mode list.| **Example** @@ -602,7 +683,7 @@ Obtains the mask combination for the supported mode list of a given USB port. let ret = usb.getSupportedModes(0); ``` -## usb.setPortRoles9+ +## usb.setPortRoles setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ @@ -617,8 +698,8 @@ Sets the role types supported by a specified port, which can be **powerRole** (f | Name | Type | Mandatory| Description | | --------- | -------------------------------- | ---- | ---------------- | | portId | number | Yes | Port number. | -| powerRole | [PowerRoleType](#powerroletype9) | Yes | Role for charging. | -| dataRole | [DataRoleType](#dataroletype9) | Yes | Role for data transfer.| +| powerRole | [PowerRoleType](#powerroletype) | Yes | Role for charging. | +| dataRole | [DataRoleType](#dataroletype) | Yes | Role for data transfer.| **Return value** @@ -638,16 +719,16 @@ Represents the USB endpoint from which data is sent or received. You can obtain **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ------------- | ------------------------------------------- | ------------- | -| address | number | Endpoint address. | -| attributes | number | Endpoint attributes. | -| interval | number | Endpoint interval. | -| maxPacketSize | number | Maximum size of data packets on the endpoint. | -| direction | [USBRequestDirection](#usbrequestdirection) | Endpoint direction. | -| number | number | Endpoint number. | -| type | number | Endpoint type. | -| interfaceId | number | Unique ID of the interface to which the endpoint belongs.| +| Name | Type | Mandatory |Description | +| ------------- | ------------------------------------------- | ------------- |------------- | +| address | number | Yes | Endpoint address. | +| attributes | number | Yes | Endpoint attributes. | +| interval | number | Yes | Endpoint interval. | +| maxPacketSize | number | Yes | Maximum size of data packets on the endpoint. | +| direction | [USBRequestDirection](#usbrequestdirection) | Yes | Endpoint direction. | +| number | number | Yes | Endpoint number. | +| type | number | Yes | Endpoint type. | +| interfaceId | number | Yes | Unique ID of the interface to which the endpoint belongs.| ## USBInterface @@ -655,15 +736,15 @@ Represents a USB interface. One [USBConfig](#usbconfig) can contain multiple **U **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ---------------- | ---------------------------------------- | --------------------- | -| id | number | Unique ID of the USB interface. | -| protocol | number | Interface protocol. | -| clazz | number | Device type. | -| subClass | number | Device subclass. | -| alternateSetting | number | Settings for alternating between descriptors of the same USB interface.| -| name | string | Interface name. | -| endpoints | Array<[USBEndpoint](#usbendpoint)> | Endpoints that belong to the USB interface. | +| Name | Type | Mandatory |Description | +| ---------------- | ---------------------------------------- | ------------- |--------------------- | +| id | number | Yes | Unique ID of the USB interface. | +| protocol | number | Yes | Interface protocol. | +| clazz | number | Yes | Device type. | +| subClass | number | Yes | Device subclass. | +| alternateSetting | number | Yes | Settings for alternating between descriptors of the same USB interface.| +| name | string | Yes | Interface name. | +| endpoints | Array<[USBEndpoint](#usbendpoint)> | Yes | Endpoints that belong to the USB interface. | ## USBConfig @@ -671,15 +752,15 @@ Represents the USB configuration. One [USBDevice](#usbdevice) can contain multip **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| -------------- | ------------------------------------------------ | --------------- | -| id | number | Unique ID of the USB configuration. | -| attributes | number | Configuration attributes. | -| maxPower | number | Maximum power consumption, in mA. | -| name | string | Configuration name, which can be left empty. | -| isRemoteWakeup | boolean | Support for remote wakeup.| -| isSelfPowered | boolean | Support for independent power supplies.| -| interfaces | Array <[USBInterface](#usbinterface)> | Supported interface attributes. | +| Name | Type | Mandatory |Description | +| -------------- | ------------------------------------------------ | --------------- |--------------- | +| id | number | Yes | Unique ID of the USB configuration. | +| attributes | number | Yes | Configuration attributes. | +| maxPower | number | Yes | Maximum power consumption, in mA. | +| name | string | Yes | Configuration name, which can be left empty. | +| isRemoteWakeup | boolean | Yes | Support for remote wakeup.| +| isSelfPowered | boolean | Yes | Support for independent power supplies.| +| interfaces | Array <[USBInterface](#usbinterface)> | Yes | Supported interface attributes. | ## USBDevice @@ -687,21 +768,21 @@ Represents the USB device information. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ---------------- | ------------------------------------ | ---------- | -| busNum | number | Bus address. | -| devAddress | number | Device address. | -| serial | string | Sequence number. | -| name | string | Device name. | -| manufacturerName | string | Device manufacturer. | -| productName | string | Product name. | -| version | string | Version number. | -| vendorId | number | Vendor ID. | -| productId | number | Product ID. | -| clazz | number | Device class. | -| subClass | number | Device subclass. | -| protocol | number | Device protocol code. | -| configs | Array<[USBConfig](#usbconfig)> | Device configuration descriptor information.| +| Name | Type | Mandatory |Description | +| ---------------- | ------------------------------------ | ---------- |---------- | +| busNum | number | Yes | Bus address. | +| devAddress | number | Yes | Device address. | +| serial | string | Yes | Sequence number. | +| name | string | Yes | Device name. | +| manufacturerName | string | Yes | Device manufacturer. | +| productName | string | Yes | Product name. | +| version | string | Yes | Version number. | +| vendorId | number | Yes | Vendor ID. | +| productId | number | Yes | Product ID. | +| clazz | number | Yes | Device class. | +| subClass | number | Yes | Device subclass. | +| protocol | number | Yes | Device protocol code. | +| configs | Array<[USBConfig](#usbconfig)> | Yes | Device configuration descriptor information.| ## USBDevicePipe @@ -709,10 +790,10 @@ Represents a USB device pipe, which is used to determine a USB device. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ---------- | ------ | ----- | -| busNum | number | Bus address.| -| devAddress | number | Device address.| +| Name | Type | Mandatory |Description | +| ---------- | ------ | ----- |----- | +| busNum | number |Yes| Bus address.| +| devAddress | number |Yes| Device address.| ## USBControlParams @@ -720,16 +801,16 @@ Represents control transfer parameters. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| ------- | ----------------------------------------------- | ---------------- | -| request | number | Request type. | -| target | [USBRequestTargetType](#usbrequesttargettype) | Request target type. | -| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Control request type. | -| value | number | Request parameter value. | -| index | number | Index of the request parameter value.| -| data | Uint8Array | Buffer for writing or reading data. | +| Name | Type | Mandatory |Description | +| ------- | ----------------------------------------------- | ---------------- |---------------- | +| request | number | Yes | Request type. | +| target | [USBRequestTargetType](#usbrequesttargettype) | Yes | Request target type. | +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | Yes | Control request type. | +| value | number | Yes | Request parameter value. | +| index | number | Yes | Index of the request parameter value.| +| data | Uint8Array | Yes | Buffer for writing or reading data. | -## USBPort9+ +## USBPort Represents a USB port. @@ -737,13 +818,13 @@ Represents a USB port. **System capability**: SystemCapability.USB.USBManager -| Name | Type | Description | -| -------------- | -------------------------------- | ----------------------------------- | -| id | number | Unique identifier of a USB port. | -| supportedModes | [PortModeType](#portmodetype9) | Numeric mask combination for the supported mode list.| -| status | [USBPortStatus](#usbportstatus9) | USB port role. | +| Name | Type | Mandatory |Description | +| -------------- | ------------------------------- | ------------------- |------------------------ | +| id | number | Yes | Unique identifier of a USB port. | +| supportedModes | [PortModeType](#portmodetype) | Yes | Numeric mask combination for the supported mode list.| +| status | [USBPortStatus](#usbportstatus) | Yes | USB port role. | -## USBPortStatus9+ +## USBPortStatus Enumerates USB port roles. @@ -751,11 +832,11 @@ Enumerates USB port roles. **System capability**: SystemCapability.USB.USBManager -| Name | Type| Description | -| ---------------- | -------- | ---------------------- | -| currentMode | number | Current USB mode. | -| currentPowerRole | number | Current power role. | -| currentDataRole | number | Current data role.| +| Name | Type| Mandatory |Description | +| ---------------- | -------- | ---------------- |---------------------- | +| currentMode | number | Yes | Current USB mode. | +| currentPowerRole | number | Yes | Current power role. | +| currentDataRole | number | Yes | Current data role.| ## USBRequestTargetType @@ -763,12 +844,12 @@ Enumerates request target types. **System capability**: SystemCapability.USB.USBManager -| Name | Value | Description | -| ---------------------------- | ---- | ------ | -| USB_REQUEST_TARGET_DEVICE | 0 | Device.| -| USB_REQUEST_TARGET_INTERFACE | 1 | Interface.| -| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint.| -| USB_REQUEST_TARGET_OTHER | 3 | Other.| +| Name | Value | Description | +| ---------------------------- | ----- | ----------- | +| USB_REQUEST_TARGET_DEVICE | 0 | Device | +| USB_REQUEST_TARGET_INTERFACE | 1 | Interface | +| USB_REQUEST_TARGET_ENDPOINT | 2 | Endpoint | +| USB_REQUEST_TARGET_OTHER | 3 | Other | ## USBControlRequestType @@ -778,9 +859,9 @@ Enumerates control request types. | Name | Value | Description | | ------------------------- | ---- | ------ | -| USB_REQUEST_TYPE_STANDARD | 0 | Standard.| -| USB_REQUEST_TYPE_CLASS | 1 | Class. | -| USB_REQUEST_TYPE_VENDOR | 2 | Vendor.| +| USB_REQUEST_TYPE_STANDARD | 0 | Standard| +| USB_REQUEST_TYPE_CLASS | 1 | Class | +| USB_REQUEST_TYPE_VENDOR | 2 | Vendor| ## USBRequestDirection @@ -793,7 +874,7 @@ Enumerates request directions. | USB_REQUEST_DIR_TO_DEVICE | 0 | Request for writing data from the host to the device.| | USB_REQUEST_DIR_FROM_DEVICE | 0x80 | Request for reading data from the device to the host.| -## FunctionType9+ +## FunctionType Enumerates USB device function types. @@ -814,7 +895,7 @@ Enumerates USB device function types. | AUDIO_SOURCE | 128 | Not supported currently.| | NCM | 256 | Not supported currently.| -## PortModeType9+ +## PortModeType Enumerates USB port mode types. @@ -830,7 +911,7 @@ Enumerates USB port mode types. | DRP | 3 | Dynamic reconfiguration port (DRP), which can function as the DFP (host) or UFP (device). It is not supported currently.| | NUM_MODES | 4 | Not supported currently. | -## PowerRoleType9+ +## PowerRoleType Enumerates power role types. @@ -844,7 +925,7 @@ Enumerates power role types. | SOURCE | 1 | External power supply.| | SINK | 2 | Internal power supply.| -## DataRoleType9+ +## DataRoleType Enumerates data role types. diff --git a/en/application-dev/reference/apis/js-apis-userfilemanager.md b/en/application-dev/reference/apis/js-apis-userfilemanager.md index 77805c1c54764ae6c9fdc2498fbead88db696a84..5249fa7cc0feff1afbf6e79fe7fb3263434d346a 100644 --- a/en/application-dev/reference/apis/js-apis-userfilemanager.md +++ b/en/application-dev/reference/apis/js-apis-userfilemanager.md @@ -1,19 +1,23 @@ -# User Data Management +# @ohos.filemanagement.userFileManager -> **NOTE**
-> This module is supported since API Version 9. Updates will be marked with a superscript to indicate their earliest API version. +The **userFileManager** module provides user data management capabilities, including accessing and modifying user media data (audio and video clips, images, and files). + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs provided by this module are system APIs. ## Modules to Import -```js -import userFileManager from '@ohos.filemanagement.userfile_manager'; +```ts +import userFileManager from '@ohos.filemanagement.userFileManager'; ``` ## 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). +Obtains a **UserFileManager** instance. This instance can be used to access and modify user media data (such as audio and video clips, images, and files). **Model restriction**: This API can be used only in the stage model. @@ -23,7 +27,7 @@ Obtains a **UserFileManager** instance. This instance can be used to access and | Name | Type | Mandatory| Description | | ------- | ------- | ---- | -------------------------- | -| context | [Context](#../apis/js-apis-Context.md) | Yes | Context of the ability instance.| +| context | [Context](js-apis-inner-app-context.md) | Yes | Context of the ability instance.| **Return value** @@ -35,762 +39,807 @@ Obtains a **UserFileManager** instance. This instance can be used to access and ```ts const context = getContext(this); -let userFileMgr = userfilemanager.getUserFileMgr(context); +let mgr = userFileManager.getUserFileMgr(context); ``` -## userFileManager.getUserFileMgr +## UserFileManager + +### getPhotoAssets -getUserFileMgr(): UserFileManager +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -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. +Obtains image and video assets. This API uses an asynchronous callback to return the result. + -> **NOTE**
You are advised to use [UserFileManager.getUserFileMgr](#userfilemanagergetuserfilemgr), the API used in the stage model. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -**Return value** +**Required permissions**: ohos.permission.READ_IMAGEVIDEO -| Type | Description | -| ----------------------------- | :--------- | -| [UserFileManager](#userfilemanager) | **UserFileManager** instance obtained.| +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the image and video assets obtained.| **Example** -```js -let userFileMgr = userfilemanager.getUserFileMgr(); +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getPhotoAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchResult fail' + err); + } + }); +} ``` -## UserFileManager -### getPublicDirectory +### getPhotoAssets -getPublicDirectory(type: DirectoryType, callback: AsyncCallback<string>): void; +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -Obtains the preset public directory. This API uses an asynchronous callback to return the result. +Obtains image and video assets. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + **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.| +| Name | Type | Mandatory| Description | +| ------- | ------------------- | ---- | ---------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise used to return the image and video assets obtained.| **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'); - } - }); +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getPhotoAssets(fetchOptions); + if (fetchResult != undefined) { + console.info('fetchResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } + } catch (err) { + console.info('getPhotoAssets failed, message = ', err); + } } ``` +### createPhotoAsset -### getPublicDirectory - -getPublicDirectory(type: DirectoryType): Promise<string>; +createPhotoAsset(displayName: string, albumUri: string, callback: AsyncCallback<FileAsset>): void; -Obtains the preset public directory. This API uses a promise to return the result. +Creates an image or video asset. 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.| +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO -**Return value** +**Parameters** -| Type | Description | -| ---------------- | ---------------- | -| Promise\ | Promise used to return the public directory.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | Yes | File name of the image or video to create. | +| albumUri | string | Yes | URI of the album where the image or video is located. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the image or video created.| **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); +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('createPhotoAssetDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + predicates: predicates + }; + let albums = await mgr.getPhotoAlbums(fetchOptions); + let album = await albums.getFirstObject(); + let testFileName = "testFile" + Date.now() + ".jpg"; + mgr.createPhotoAsset(testFileName, album.albumUri, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); } + }); } ``` -### getFileAssets +### createPhotoAsset -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; +createPhotoAsset(displayName: string, callback: AsyncCallback<FileAsset>): void; -Obtains file assets. This API uses an asynchronous callback to return the result. +Creates an image or video asset. 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO **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.| +| displayName | string | Yes | File name of the image or video to create. | +| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the image or video created.| **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); - }; - } - }) +async function example() { + console.info('createPhotoAssetDemo'); + let testFileName = "testFile" + Date.now() + ".jpg"; + mgr.createPhotoAsset(testFileName, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } else { + console.info('createPhotoAsset failed, message = ', err); + } + }); } ``` -### getFileAssets +### createPhotoAsset -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; +createPhotoAsset(displayName: string, albumUri?: string): Promise<FileAsset>; -Obtains file assets. This API uses a promise to return the result. +Creates an image or video asset. 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO **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. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| displayName | string | Yes | File name of the image or video to create. | +| albumUri | string | No | URI of the album where the image or video is located. | **Return value** | Type | Description | | --------------------------- | -------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| +| Promise<[FileAsset](#fileasset)> | Promise used to return the image or video created.| **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); - }; - } +async function example() { + console.info('createPhotoAssetDemo'); + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ', err); + } } ``` -### on +### getPhotoAlbums -on(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback: Callback<void>): void +getPhotoAlbums(options: AlbumFetchOptions, callback: AsyncCallback<FetchResult<Album>>): void; -Subscribes to changes of the file management library. This API uses a callback to return the result. + +Obtains image and video albums. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + **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. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | Yes | Options for fetching the albums. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[Album](#album)>> | Yes | Callback invoked to return the albums obtained.| **Example** ```ts -async function onDemo() { - console.info('onDemo') - userFileMgr.on('imageChange', () => { - // Image file changes. Do something. - }); +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAlbumsDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + + mgr.getPhotoAlbums(albumFetchOptions, (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('albums.count = ' + fetchResult.getCount()); + fetchResult.getFirstObject((err, album) => { + if (album != undefined) { + console.info('first album.albumName = ' + album.albumName); + } else { + console.info('album is undefined, err = ', err); + } + }); + } else { + console.info('getPhotoAlbums fail, message = ', err); + } + }); } ``` -### off +### getPhotoAlbums -off(type: 'deviceChange'|'albumChange'|'imageChange'|'audioChange'|'videoChange'|'fileChange'|'remoteFileChange', callback?: Callback<void>): void +getPhotoAlbums(options: AlbumFetchOptions): Promise<FetchResult<Album>>; -Unsubscribes from changes of the file management library. This API uses a callback to return the result. +Obtains image and video albums. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + **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. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [AlbumFetchOptions](#albumfetchoptions) | Yes | Options for fetching the albums. | + +**Return value** + +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[Album](#album)>> | Promise used to return the albums obtained.| **Example** ```ts -async function offDemo() { - console.info('offDemo') - userFileMgr.off('imageChange', () => { - // stop listening success - }); +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getPhotoAlbumsDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + let fetchResult = await mgr.getPhotoAlbums(albumFetchOptions); + console.info('album.count = ' + fetchResult.getCount()); + const album = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + album.albumName); + } catch (err) { + console.info('getPhotoAlbums fail, message = ' + err); + } } ``` -### createAsset +### getPrivateAlbum -createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback<FileAsset>): void +getPrivateAlbum(type: PrivateAlbumType, callback: AsyncCallback<FetchResult<PrivateAlbum>>): void; -Creates a file asset. This API uses an asynchronous callback to return the result. -This is a system API. +Obtains the system album. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT +**Required permissions**: ohos.permission.READ_IMAGEVIDEO **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. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | Yes | Type of the album to obtain. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Yes | Callback invoked to return the album obtained.| **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); - } - }) +async function example() { + console.info('getPrivateAlbumDemo'); + mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH, async (err, fetchResult) => { + if (fetchResult != undefined) { + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } else { + console.info('getPrivateAlbum failed. message = ', err); + } + }); } ``` -### createAsset +### getPrivateAlbum -createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise<FileAsset>; +getPrivateAlbum(type: PrivateAlbumType): Promise<FetchResult<PrivateAlbum>>; -Creates a file asset. This API uses a promise to return the result. -This is a system API. +Obtains the system album. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT +**Required permissions**: ohos.permission.READ_IMAGEVIDEO **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.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| type | [PrivateAlbumType](#privatealbumtype) | Yes | Type of the album to obtain. | **Return value** -| Type | Description | -| --------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset created.| +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[PrivateAlbum](#privatealbum)>> | Promise used to return the album obtained.| **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); - } +async function example() { + console.info('getPrivateAlbumDemo'); + try { + var fetchResult = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let trashAlbum = await fetchResult.getFirstObject(); + console.info('first album.albumName = ' + trashAlbum.albumName); + } catch (err) { + console.info('getPrivateAlbum failed. message = ', err); + } } ``` -### deleteAsset +### getAudioAssets -deleteAsset(uri: string, callback: AsyncCallback<void>): void; +getAudioAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; -Deletes a file asset. This API uses an asynchronous callback to return the result. -This is a system API. +Obtains audio assets. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT +**Required permissions**: ohos.permission.READ_AUDIO **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.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the audio assets. | +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the audio assets obtained.| **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) - } +import dataSharePredicates from '@ohos.data.dataSharePredicates'; - if (asset == undefined) { - console.error('asset not exist') - return +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + + mgr.getAudioAssets(fetchOptions, async (err, fetchResult) => { + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); + } + } else { + console.info('fetchFileResult fail' + err); } - userFileMgr.deleteAsset(asset.uri, (err) => { - if (err == undefined) { - console.info("deleteAsset successfully"); - } else { - console.info("deleteAsset failed with error:"+ err); - } - }); + }); } ``` -### deleteAsset +### getAudioAssets -deleteAsset(uri: string): Promise<void>; +getAudioAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -Deletes a file asset. This API uses a promise to return the result. -This is a system API. +Obtains audio assets. This API uses a promise to return the result. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO, ohos.permission.WRITE_AUDIO, or ohos.permission.WRITE_DOCUMENT +**Required permissions**: ohos.permission.READ_AUDIO **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------ | ---- | ------- | -| uri | string | Yes | URI of the file to delete.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ------------------------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the audio assets. | **Return value** -| Type | Description | -| ---------------- | --------------------------------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| --------------------------- | -------------- | +| Promise<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Promise used to return the audio assets obtained.| **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); +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('getAudioAssets'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + var fetchResult = await mgr.getAudioAssets(fetchOptions); + } catch (err) { + console.info('getAudioAssets failed, message = ', err); + } + + if (fetchResult != undefined) { + console.info('fetchFileResult success'); + let fileAsset = await fetchResult.getFirstObject(); + if (fileAsset != undefined) { + console.info("fileAsset.displayName :" + fileAsset.displayName); } + } } ``` +### delete -### 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.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | URI of the media file to delete.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| **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); - } - }) +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('deleteAssetDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err); + } + + if (asset == undefined) { + console.error('asset not exist'); + return; + } + mgr.delete(asset.uri, (err) => { + if (err == undefined) { + console.info("delete successfully"); + } else { + console.info("delete failed with error:" + err); + } + }); } ``` +### delete -### getAlbums - -getAlbums(type: Array<MediaType>, options: MediaFetchOptions): Promise>; +delete(uri: string): Promise<void>; -Obtains albums. This API uses a promise to return the result. +Deletes a media file. This API uses a promise to return the result. The deleted file is moved to the recycle bin. -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO **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. | +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | URI of the media file to delete.| **Return value** -| Type | Description | -| ------------------------ | -------------------------- | -| Promise> | Promise used to return the album list.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<void>| Promise that returns no value.| **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); - } +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('deleteDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOptions = { + fetchColumns: [], + predicates: predicates + }; + try { + const fetchResult = await mgr.getPhotoAssets(fetchOptions); + var asset = await fetchResult.getFirstObject(); + } catch (err) { + console.info('fetch failed, message =', err); + } + + if (asset == undefined) { + console.error('asset not exist'); + return; + } + try { + await mgr.delete(asset.uri); + console.info("delete successfully"); + } catch (err) { + console.info("delete failed with error:" + err); + } } ``` -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback): void +### on -Obtains the system album. This API uses an asynchronous callback to return the result. +on(type: ChangeEvent, callback: Callback<void>): void -This is a system API. +Subscribes to changes of the file management library. This API uses a 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 | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain. | -| callback | AsyncCallback> | Yes | Callback invoked to return the system album obtained.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | Yes | Type of event 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.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | Yes | Callback that returns no value. | **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); - } - }); +async function example() { + console.info('onDemo'); + let count = 0; + mgr.on('imageChange', () => { + count++; + // Image file changed. Do something. + }); + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ' + err); + } + //sleep 1s + if (count > 0) { + console.info("onDemo success"); + } else { + console.info("onDemo fail"); + } + mgr.off('imageChange', () => { + // Unsubscription succeeds. + }); } ``` -### getPrivateAlbum - -getPrivateAlbum(type: VirtualAlbumType): Promise +### off -Obtains the system album. This API uses a promise to return the result. +off(type: ChangeEvent, callback?: Callback<void>): void -This is a system API. +Unsubscribes from changes of the file management library. This API uses a 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 | [VirtualAlbumType](#virtualalbumtype) | Yes | Type of the album to obtain.| - -**Return value** - -| Type | Description | -| ------------------------------- | --------------------------------- | -| Promise> | Promise used to return the system album obtained.| +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ------------------------------------------------------------ | +| type | [ChangeEvent](#changeevent) | Yes | Type of event 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.
**remoteFileChange** indicates the file change on the registered device.| +| callback | Callback<void> | No | Callback that returns no value. | **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) +async function example() { + console.info('offDemo'); + let count = 0; + mgr.on('imageChange', () => { + count++; + // Image file changed. Do something. + }); + + mgr.off('imageChange', () => { + // Unsubscription succeeds. + }); + + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + let fileAsset = await mgr.createPhotoAsset(testFileName); + console.info('createPhotoAsset file displayName' + fileAsset.displayName); + console.info('createPhotoAsset successfully'); + } catch (err) { + console.info('createPhotoAsset failed, message = ' + err); + } + //sleep 1s + if (count == 0) { + console.info("offDemo success"); + } else { + console.info("offDemo fail"); + } } ``` ### getActivePeers -getActivePeers(callback: AsyncCallback>): void; +getActivePeers(callback: AsyncCallback<Array<PeerInfo>>): 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.| +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | Yes | Callback invoked to return the online peer 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) - } - }); +async function example() { + console.info('getActivePeersDemo'); + mgr.getActivePeers((err, devicesInfo) => { + 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('getActivePeers failed. message = ', err); + } + }); } ``` ### getActivePeers -getActivePeers(): Promise>; +getActivePeers(): Promise<Array<PeerInfo>>; 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.| +| Promise<Array<[PeerInfo](#peerinfo)>> | 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') +async function example() { + console.info('getActivePeersDemo'); + try { + var devicesInfo = await mgr.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; +getAllPeers(callback: AsyncCallback<Array<PeerInfo>>): 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.| +| callback | AsyncCallback<Array<[PeerInfo](#peerinfo)>> | Yes | Callback invoked to return the online 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) - } - }); +async function example() { + console.info('getAllPeersDemo'); + mgr.getAllPeers((err, devicesInfo) => { + 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('getAllPeers failed. message = ', err); + } + }); } ``` ### getAllPeers -getAllPeers(): Promise>; +getAllPeers(): Promise<Array<PeerInfo>>; 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.| +| Promise<Array<[PeerInfo](#peerinfo)>> | 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') +async function example() { + console.info('getAllPeersDemo'); + try { + var devicesInfo = await mgr.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'); + } } ``` @@ -807,20 +856,20 @@ Call this API when the APIs in the **UserFileManager** instance are no longer us | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------- | -| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| **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.'); - } - }) +async function example() { + console.info('releaseDemo'); + mgr.release((err) => { + if (err != undefined) { + console.info('release failed. message = ', err); + } else { + console.info('release ok.'); + } + }); } ``` @@ -837,19 +886,19 @@ Call this API when the APIs in the **UserFileManager** instance are no longer us | Type | Description | | ------------------- | --------------------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** ```ts -async function releaseDemoPromise() { - console.info('releaseDemo'); - try { - await userFileMgr.release(); - console.info('release ok.'); - } catch (err) { - console.info('release failed. message = ', err); - } +async function example() { + console.info('releaseDemo'); + try { + await mgr.release(); + console.info('release ok.'); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -864,79 +913,83 @@ Provides APIs for encapsulating file asset attributes. | 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. | +| fileType | [FileType](#filetype) | Yes | No | Type of the file. | | displayName | string | Yes | Yes | File name, including the file name extension, to display. | -### isDirectory +### get -isDirectory(callback: AsyncCallback<boolean>): void +get(member: string): MemberType; -Checks whether this file asset is a directory. This API uses an asynchronous callback to return the result. +Obtains the value of a **FileAsset** parameter. **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.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| member | string | Yes | Name of the parameter to obtain, for example, **ImageVideoKey.URI**.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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: "", + console.info('fileAssetGetDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - let userFileMgr = userfile_manager.getUserFileMgr(context); - const fetchFileResult = await userFileMgr.getFileAssets(getImageOp); - const asset = await fetchFileResult.getFirstObject(); - asset.isDirectory((err, isDirectory) => { - // do something - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` -### isDirectory +### set -isDirectory():Promise<boolean> +set(member: string, value: string): void; -Checks whether this file asset is a directory. This API uses a promise to return the result. +Sets a **FileAsset** parameter. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -**Return value** +**Parameters** -| 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.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------- | ---- | ----- | +| member | string | Yes | Name of the parameter to set, for example, **ImageVideoKey.URI**.| +| value | string | Yes | Value to set. Only the value of **ImageVideoKey.TITLE** can be changed.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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: "", + console.info('fileAssetSetDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - 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); - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + fileAsset.set(title.toString(), "newTitle"); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -946,7 +999,7 @@ 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -958,23 +1011,30 @@ Commits the modification on the file metadata to the database. This API uses an **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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'); - }); + console.info('commitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle"); + fileAsset.commitModify((err) => { + if (err == undefined) { + let newFileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } else { + console.info('commitModify failed, message =', err); + } + }); } ``` @@ -984,7 +1044,7 @@ 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -994,23 +1054,31 @@ Commits the modification on the file metadata to the database. This API uses a p | ------------------- | ---------- | | Promise<void> | Promise that returns no value.| -**Example** +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; -```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('commitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + let title = userFileManager.ImageVideoKey.TITLE; + let fileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get fileAssetTitle = ', fileAssetTitle); + fileAsset.set(title.toString(), "newTitle"); + try { + await fileAsset.commitModify(); + let newFileAssetTitle = fileAsset.get(title.toString()); + console.info('fileAsset Get newFileAssetTitle = ', newFileAssetTitle); + } catch (err) { + console.info('release failed. message = ', err); + } } ``` @@ -1020,9 +1088,11 @@ 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. +>**NOTE** +> +>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 +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -1036,20 +1106,19 @@ Opens this file asset. This API uses an asynchronous callback to return the resu **Example** -```js +```ts 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); - } - }); + console.info('openDemo'); + let testFileName = "testFile" + Date.now() + ".jpg"; + const fileAsset = await mgr.createPhotoAsset(testFileName); + fileAsset.open('rw', (err, fd) => { + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd); + } else { + console.info('File err' + err); + } + }); } ``` @@ -1059,9 +1128,11 @@ 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. +>**NOTE** +> +>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 +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, ohos.permission.WRITE_IMAGEVIDEO, or ohos.permission.WRITE_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -1079,20 +1150,22 @@ Opens this file asset. This API uses a promise to return the result. **Example** -```js +```ts 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); - }); + console.info('openDemo'); + try { + let testFileName = "testFile" + Date.now() + ".jpg"; + const fileAsset = await mgr.createPhotoAsset(testFileName); + let fd = await fileAsset.open('rw'); + if (fd != undefined) { + console.info('File fd' + fd); + fileAsset.close(fd); + } else { + console.info(' open File fail'); + } + } catch (err) { + console.info('open Demo err' + err); + } } ``` @@ -1113,33 +1186,31 @@ Closes this file asset. This API uses an asynchronous callback to return the res **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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: "", + console.info('closeDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - 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); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let fd = await fileAsset.open('rw'); + console.info('file fd', fd); + fileAsset.close(fd, (err) => { + if (err == undefined) { + console.info('asset close succeed.'); + } else { + console.info('close failed, message = ' + err); + } }); + } catch (err) { + console.info('close failed, message = ' + err); + } } ``` @@ -1165,34 +1236,26 @@ Closes this file asset. This API uses a promise to return the result. **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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: "", + console.info('closeDemo'); + try { + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates }; - 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); - }); + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + let fd = await asset.open('rw'); + console.info('file fd', fd); + await asset.close(fd); + console.info('asset close succeed.'); + } catch (err) { + console.info('close failed, message = ' + err); + } } ``` @@ -1202,7 +1265,7 @@ 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 +**Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -1210,36 +1273,40 @@ Obtains the thumbnail of this file asset. This API uses an asynchronous callback | 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.| +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }); + console.info('getThumbnailDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName); + asset.getThumbnail((err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); + } + }); } ``` ### getThumbnail -getThumbnail(size: Size, callback: AsyncCallback<image.PixelMap>): void +getThumbnail(size: image.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 +**Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -1247,38 +1314,42 @@ Obtains the file thumbnail of the given size. This API uses an asynchronous call | 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.| +| size | [image.Size](js-apis-image.md#size) | Yes | Size of the thumbnail to obtain. | +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes | Callback invoked to return the pixel map of the thumbnail.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }); + console.info('getThumbnailDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName); + asset.getThumbnail(size, (err, pixelMap) => { + if (err == undefined) { + console.info('getThumbnail successful ' + pixelMap); + } else { + console.info('getThumbnail fail', err); + } + }); } ``` ### getThumbnail -getThumbnail(size?: Size): Promise<image.PixelMap> +getThumbnail(size?: image.Size): Promise<image.PixelMap> -Obtains the file thumbnail of the given size. This API uses a promise to return the result. +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 +**Required permissions**: ohos.permission.READ_IMAGEVIDEO or ohos.permission.READ_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -1286,37 +1357,35 @@ Obtains the file thumbnail of the given size. This API uses a promise to return | Name | Type | Mandatory | Description | | ---- | -------------- | ---- | ----- | -| size | [Size](#size) | No | Size of the thumbnail to obtain.| +| size | [image.Size](js-apis-image.md#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.| +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the pixel map of the thumbnail.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }); + console.info('getThumbnailDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let size = { width: 720, height: 720 }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + console.info('asset displayName = ', asset.displayName); + asset.getThumbnail(size).then((pixelMap) => { + console.info('getThumbnail successful ' + pixelMap); + }).catch((err) => { + console.info('getThumbnail fail' + err); + }); } ``` @@ -1326,7 +1395,7 @@ 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -1339,22 +1408,25 @@ Favorites or unfavorites this file asset. This API uses an asynchronous callback **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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. - }); + console.info('favoriteDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true, (err) => { + if (err == undefined) { + console.info("favorite successfully"); + } else { + console.info("favorite failed with error:" + err); + } + }); } ``` @@ -1364,7 +1436,7 @@ 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.WRITE_AUDIO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -1382,267 +1454,27 @@ Favorites or unfavorites this file asset. This API uses a promise to return the **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** +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; -```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); - }); + console.info('favoriteDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const asset = await fetchResult.getFirstObject(); + asset.favorite(true).then(function () { + console.info("favorite successfully"); + }).catch(function (err) { + console.info("favorite failed with error:" + err); + }); } ``` -## FetchFileResult +## FetchResult Provides APIs to manage the file retrieval result. @@ -1662,19 +1494,19 @@ Obtains the total number of files in the result set. **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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(); + console.info('getCountDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('fetchCount = ', fetchCount); } ``` @@ -1694,31 +1526,24 @@ Checks whether the cursor is in the last row of the result set. **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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(); - } - } + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + const fetchCount = fetchResult.getCount(); + console.info('count:' + fetchCount); + let fileAsset = await fetchResult.getLastObject(); + if (!fetchResult.isAfterLast()) { + console.info('fileAsset isAfterLast displayName = ', fileAsset.displayName); + } else { + console.info('fileAsset not isAfterLast '); + } } ``` @@ -1732,25 +1557,29 @@ Releases and invalidates this **FetchFileResult** instance. After this instance **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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(); + console.info('fetchResultCloseDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + try { + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.close(); + console.info('close succeed.'); + } catch (err) { + console.info('close fail. message = ' + err); + } } ``` ### getFirstObject -getFirstObject(callback: AsyncCallback<FileAsset>): void +getFirstObject(callback: AsyncCallback<T>): void Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result. @@ -1760,35 +1589,34 @@ Obtains the first file asset in the result set. This API uses an asynchronous ca | Name | Type | Mandatory| Description | | -------- | --------------------------------------------- | ---- | ------------------------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the first file asset.| +| callback | AsyncCallback<T> | Yes | Callback invoked to return the first file asset.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }) + console.info('getFirstObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getFirstObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getFirstObject -getFirstObject(): Promise<FileAsset> +getFirstObject(): Promise<T> Obtains the first file asset in the result set. This API uses a promise to return the result. @@ -1798,33 +1626,29 @@ Obtains the first file asset in the result set. This API uses a promise to retur | Type | Description | | --------------------------------------- | -------------------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the first file asset.| +| Promise<T> | Promise used to return the first file asset.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }); + console.info('getFirstObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getFirstObject(); + console.info('fileAsset displayName: ', fileAsset.displayName); } ``` ### getNextObject - getNextObject(callback: AsyncCallback<FileAsset>): void + getNextObject(callback: AsyncCallback<T>): void Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result. @@ -1834,35 +1658,37 @@ Obtains the next file asset in the result set. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | --------- | --------------------------------------------- | ---- | ----------------------------------------- | -| callbacke | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the next file asset.| +| callbacke | AsyncCallback<T> | Yes | Callback invoked to return the next file asset.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }) + console.info('getNextObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + fetchResult.getNextObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); + } } ``` ### getNextObject - getNextObject(): Promise<FileAsset> + getNextObject(): Promise<T> Obtains the next file asset in the result set. This API uses a promise to return the result. @@ -1872,31 +1698,32 @@ Obtains the next file asset in the result set. This API uses a promise to return | Type | Description | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the next file asset.| +| Promise<T> | Promise used to return the next file asset obtained.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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(); + console.info('getNextObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + await fetchResult.getFirstObject(); + if (fetchResult.isAfterLast()) { + let fileAsset = await fetchResult.getNextObject(); + console.info('fileAsset displayName: ', fileAsset.displayName); + } } ``` ### getLastObject -getLastObject(callback: AsyncCallback<FileAsset>): void +getLastObject(callback: AsyncCallback<T>): void Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result. @@ -1906,35 +1733,34 @@ Obtains the last file asset in the result set. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------------------------------- | ---- | --------------------------- | -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the last file asset.| +| callback | AsyncCallback<T> | Yes | Callback invoked to return the last file asset obtained.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }) + console.info('getLastObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getLastObject((err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getLastObject -getLastObject(): Promise<FileAsset> +getLastObject(): Promise<T> Obtains the last file asset in the result set. This API uses a promise to return the result. @@ -1944,29 +1770,29 @@ Obtains the last file asset in the result set. This API uses a promise to return | Type | Description | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the last file asset.| +| Promise<T> | Promise used to return the last file asset obtained.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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(); + console.info('getLastObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getLastObject(); + console.info('fileAsset displayName: ', fileAsset.displayName); } ``` ### getPositionObject -getPositionObject(index: number, callback: AsyncCallback<FileAsset>): void +getPositionObject(index: number, callback: AsyncCallback<T>): void Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result. @@ -1977,35 +1803,34 @@ Obtains a file asset with the specified index in the result set. This API uses a | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ------------------ | | index | number | Yes | Index of the file asset to obtain. The value starts from **0**. | -| callback | AsyncCallback<[FileAsset](#fileasset)> | Yes | Callback invoked to return the file asset obtained.| +| callback | AsyncCallback<T> | Yes | Callback invoked to return the file asset obtained.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }) + console.info('getPositionObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + fetchResult.getPositionObject(0, (err, fileAsset) => { + if (fileAsset != undefined) { + console.info('fileAsset displayName: ', fileAsset.displayName); + } else { + console.info("fileAsset failed with err:" + err); + } + }); } ``` ### getPositionObject -getPositionObject(index: number): Promise<FileAsset> +getPositionObject(index: number): Promise<T> Obtains a file asset with the specified index in the result set. This API uses a promise to return the result. @@ -2021,27 +1846,23 @@ Obtains a file asset with the specified index in the result set. This API uses a | Type | Description | | --------------------------------------- | ----------------- | -| Promise<[FileAsset](#fileasset)> | Promise used to return the file asset obtained.| +| Promise<T> | Promise used to return the file asset obtained.| **Example** -```js +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + 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); - }); + console.info('getPositionObjectDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + let fetchResult = await mgr.getPhotoAssets(fetchOption); + let fileAsset = await fetchResult.getPositionObject(0); + console.info('fileAsset displayName: ', fileAsset.displayName); } ``` @@ -2059,16 +1880,102 @@ Provides APIs to manage albums. | 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. +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +Obtains image and video assets. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumGetFileAssetsDemoCallback'); + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption, (err, albumFetchResult) => { + if (albumFetchResult != undefined) { + console.info("album getPhotoAssets successfully, getCount:" + albumFetchResult.getCount()); + } else { + console.info("album getPhotoAssets failed with error:" + err); + } + }); +} +``` +### getPhotoAssets + +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; + +Obtains image and video assets. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| +| Promise | [FetchResult](#fetchresult)<[FileAsset](#fileasset)> | Yes | Promise used to return the image and video assets obtained.| + +**Example** + +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumGetFileAssetsDemoPromise'); + + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.getPhotoAssets(fetchOption).then((albumFetchResult) => { + console.info("album getFileAssets successfully, getCount:" + albumFetchResult.getCount()); + }).catch((err) => { + console.info("album getFileAssets failed with error:" + err); + }); +} +``` + ### 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -2081,28 +1988,24 @@ Commits the modification on the album attributes to the database. This API uses **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); - } - }); +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumCommitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + const albumList = await mgr.getPhotoAlbums(albumFetchOptions); + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify((err) => { + if (err != undefined) { + console.info("commitModify failed with error:" + err); + } else { + console.info("commitModify successfully"); + } + }); } ``` @@ -2112,7 +2015,7 @@ 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 +**Required permissions**: ohos.permission.WRITE_IMAGEVIDEO **System capability**: SystemCapability.FileManagement.UserFileManager.Core @@ -2125,265 +2028,338 @@ Commits the modification on the album attributes to the database. This API uses **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); - } +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('albumCommitModifyDemo'); + let predicates = new dataSharePredicates.DataSharePredicates(); + let albumFetchOptions = { + predicates: predicates + }; + try { + var albumList = await mgr.getPhotoAlbums(albumFetchOptions); + } catch (err) { + console.info('getPhotoAlbums failed. message = ', err); + } + const album = await albumList.getFirstObject(); + album.albumName = 'hello'; + album.commitModify().then(() => { + console.info("commitModify successfully"); + }).catch((err) => { + console.info("commitModify failed with error:" + err); + }); } ``` -### getFileAssets +## PrivateAlbum -getFileAssets(type: Array<MediaType>, callback: AsyncCallback<FetchFileResult>): void; +Provides APIs for managing the system albums. -Obtains the file assets in this album. This API uses an asynchronous callback to return the result. +### Attributes -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT +**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.| +| coverUri | string | Yes | No | URI of the cover file of the album. + +### getPhotoAssets + +getPhotoAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<FileAsset>>): void; + +Obtains image and video assets from a system album. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO **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.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| +| callback | AsyncCallback<[FetchResult](#fetchresult)<[FileAsset](#fileasset)>> | Yes | Callback invoked to return the image and video 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); - } - }); +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumGetFileAssetsDemoCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + trashAlbum.getPhotoAssets(fetchOption, (err, fetchResult) => { + if (fetchResult != undefined) { + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); + } else { + console.info('getFileAssets failed, message = ', err); + } + }); } -``` -### getFileAssets +``` +### getPhotoAssets -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; +getPhotoAssets(options: FetchOptions): Promise<FetchResult<FileAsset>>; -Obtains the file assets in this album. This API uses an asynchronous callback to return the result. +Obtains image and video assets from a system 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 +**Required permissions**: ohos.permission.READ_IMAGEVIDEO **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.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| options | [FetchOptions](#fetchoptions) | Yes | Options for fetching the image and video assets.| + +**Return value** + +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise:[FetchResult](#fetchresult)<[FileAsset](#fileasset)>| Promise used to return the image and video 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); - } - }); - } +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumGetFileAssetsDemoPromise'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + let count = fetchResult.getCount(); + console.info('fetchResult.count = ', count); +} ``` +### delete + +delete(uri: string, callback: AsyncCallback<void>): void; -### getFileAssets +Deletes files from a system album. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core -getFileAssets(type: Array<MediaType>, options?: MediaFetchOptions): Promise<FetchFileResult>; +**Parameters** -Obtains the file assets in this album. This API uses a promise to return the result. +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT +**Example** +```ts +import dataSharePredicates from '@ohos.data.dataSharePredicates'; + +async function example() { + console.info('privateAlbumDeleteCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.delete failed, message = ', err); + } else { + console.info('trashAlbum.delete successfully'); + } + }); +} +``` +### delete + +delete(uri: string): Promise<void>; + +Deletes files from a system album. + +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO **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.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| **Return value** -| Type | Description | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<void>| Promise that returns no value.| **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. +import dataSharePredicates from '@ohos.data.dataSharePredicates'; -### getFileAssets - -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions, callback: AsyncCallback<FetchFileResult>): void; +async function example() { + console.info('privateAlbumDeleteDemoPromise'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let deleteFileUri = fileAsset.uri; + trashAlbum.delete(deleteFileUri).then(() => { + console.info('trashAlbum.delete successfully'); + }).catch((err) => { + console.info('trashAlbum.delete failed, message = ', err); + }); +} +``` -Obtains file assets in the virtual album. This API uses an asynchronous callback to return the result. +### recover -This is a system API. +recover(uri: string, callback: AsyncCallback<void>): void; -**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.READ_AUDIO, or ohos.permission.READ_DOCUMENT +Recovers files in a system album. -> **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. +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO **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.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value.| **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]; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; - 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); - } - }); +async function example() { + console.info('privateAlbumRecoverDemoCallback'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri, (err) => { + if (err != undefined) { + console.info('trashAlbum.recover failed, message = ', err); + } else { + console.info('trashAlbum.recover successfully'); + } + }); } ``` +### recover -### getFileAssets -getFileAssets(type: Array<MediaType>, options: MediaFetchOptions): Promise<FetchFileResult>; +recover(uri: string): Promise<void>; -Obtains file assets in the virtual album. This API uses a promise to return the result. +Recovers files in a system album. -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. +**Required permissions**: ohos.permission.READ_IMAGEVIDEO, ohos.permission.WRITE_IMAGEVIDEO or ohos.permission.READ_AUDIO, and ohos.permission.WRITE_AUDIO **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.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------- | +| uri | string | Yes | Album URI.| **Return value** -| Type | Description | -| --------------------------------------------- | ------------------------- | -| Promise<[FetchFileResult](#fetchfileresult)> | Promise used to return the file assets obtained.| +| Type | Description | +| --------------------------------------- | ----------------- | +| Promise<void>| Promise that returns no value.| **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]; +import dataSharePredicates from '@ohos.data.dataSharePredicates'; - let fetchResult = await trashAlbum.getFileAssets([userfile_manager.MediaType.IMAGE], fetchOpt); - let count = fetchResult.getCount(); - console.info('fetchResult.count = ', count); +async function example() { + console.info('privateAlbumRecoverDemoPromise'); + let albumList = await mgr.getPrivateAlbum(userFileManager.PrivateAlbumType.TYPE_TRASH); + let predicates = new dataSharePredicates.DataSharePredicates(); + let fetchOption = { + fetchColumns: [], + predicates: predicates + }; + const trashAlbum = await albumList.getFirstObject(); + let fetchResult = await trashAlbum.getPhotoAssets(fetchOption); + const fileAsset = await fetchResult.getFirstObject(); + let recoverFileUri = fileAsset.uri; + trashAlbum.recover(recoverFileUri).then(() => { + console.info('trashAlbum.recover successfully'); + }).catch((err) => { + console.info('trashAlbum.recover failed, message = ', err); + }); } ``` +## MemberType + +Enumerates the member types. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type| Readable | Writable | Description | +| ----- | ---- | ---- | ---- | ---- | +| number | number | Yes| Yes| The member is a number.| +| string | string | Yes| Yes| The member is a string.| +| boolean | boolean | Yes| Yes| The member is a Boolean value.| + +## ChangeEvent + +Enumerates the type of changes to observe. + +**System capability**: SystemCapability.FileManagement.UserFileManager.Core + +| Name | Type| Readable | Writable | Description| +| ----- | ---- | ---- | ---- | ---- | +| deviceChange | string | Yes| Yes| Device.| +| albumChange | string | Yes| Yes| Album.| +| imageChange | string | Yes| Yes| Image.| +| audioChange | string | Yes| Yes| Audio.| +| videoChange | string | Yes| Yes| Video.| +| remoteFileChange | string | Yes| Yes| Remote file.| + ## PeerInfo -Describes information about a registered device. -This is a system API. +Defines information about a registered device. **System capability**: SystemCapability.FileManagement.UserFileManager.DistributedCore @@ -2393,33 +2369,31 @@ This is a system API. | 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. +## FileType + +Enumerates media file types. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -| Name | Description| -| ----- | ---- | -| FILE | File.| -| IMAGE | Image.| -| VIDEO | Video.| -| AUDIO | Audio.| +| Name | Value| Description| +| ----- | ---- | ---- | +| IMAGE | 1 | Image.| +| VIDEO | 2 | Video.| +| AUDIO | 3 | Audio.| -## FileKey +## PrivateAlbumType -Defines the key file information. +Enumerates the system album types. **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. | +| Name | Value| Description | +| ----- | ---- | ---- | +| TYPE_FAVORITE | 0 | Favorites.| +| TYPE_TRASH | 1 | Recycle bin.| + + ## AudioKey @@ -2427,10 +2401,9 @@ Defines the key information about an audio file. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------- | ------------------- | ---------------------------------------------------------- | -| URI | uri | Promise used to return the URI of the file created. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| URI | uri | File URI. | | 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. | @@ -2438,6 +2411,7 @@ Defines the key information about an audio file. | ARTIST | artist | Author of the file. | | AUDIOALBUM | audio_album | Audio album. | | DURATION | duration | Duration, in ms. | +| FAVORITE | favorite | Whether the file is added to favorites. | ## ImageVideoKey @@ -2445,17 +2419,20 @@ Defines the key information about an image or video file. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -| Name | Default Value | Description | +| Name | Value | Description | | ------------- | ------------------- | ---------------------------------------------------------- | | URI | uri | File URI. | -| RELATIVE_PATH | relative_path | Relative public directory of the file. | +| FILE_TYPE | file_type | Type 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. | | 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. | +| ORIENTATION | orientation | Orientation of the image file. | +| FAVORITE | favorite | Whether the file is added to favorites. | ## AlbumKey @@ -2463,58 +2440,32 @@ Defines the key album information. **System capability**: SystemCapability.FileManagement.UserFileManager.Core -| Name | Default Value | Description | +| Name | 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 +| FILE_TYPE | file_type | Type of the file. | +| ALBUM_NAME | album_name | Name of the album. | +| 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. | -| 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 +## FetchOptions 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.| +| Name | Type | Readable| Writable| Description | +| ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ | +| fetchColumns | Array<string> | Yes | Yes | Columns to fetch. If this parameter is left empty, data is fetched by URI, name, and file type by default. For example,
**fetchColumns: "uri"**.| +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | Yes | Yes | Predicates that specify the fetch criteria.| -## VirtualAlbumType -Enumerates the system or virtual album types. +## AlbumFetchOptions -This is a system API. +Defines the options for fetching an album. **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.| +| Name | Type | Readable| Writable| Description | +| ---------------------- | ------------------- | ---- |---- | ------------------------------------------------ | +| predicates | [dataSharePredicates.DataSharePredicates](js-apis-data-dataSharePredicates.md) | Yes | Yes | Predicates that specify the fetch criteria.| diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md index 9a45d1fe8f9644f0072fdfdb44c31f66c19e3d59..7005776c804fa21fe899f82d29253c2436b4f5ea 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md @@ -1,4 +1,4 @@ -# Facial Authentication +# @ohos.userIAM.faceAuth (Facial Authentication) The **userIAM.faceAuth** module provides APIs for face enrollment. @@ -34,17 +34,17 @@ A constructor used to create a **FaceAuthManager** object. **Example** - ```js - import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; - let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); - ``` +let faceAuthManager = new userIAM_faceAuth.FaceAuthManager(); +``` ### setSurfaceId setSurfaceId(surfaceId: string): void; -Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. +Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. This API must be used with [AddCredential](./js-apis-osAccount.md#addcredential8). **System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth @@ -56,17 +56,28 @@ Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#ge | -------------- | ---------------------------------- | ---- | -------------------------- | | surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).| +For details about the following error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 202 | The caller is not a system application. | +| 12700001 | The operation is failed. | + **Example** - ```js - import faceAuth from '@ohos.userIAM.faceAuth'; - - let surfaceId = "123456"; - let manager = new faceAuth.FaceAuthManager(); - try { - manager.setSurfaceId(surfaceId); - console.info("Set the surface ID successfully"); - } catch (e) { - console.error("Failed to set the surface ID, error = " + e); - } - ``` +```js +import userIAM_faceAuth from '@ohos.userIAM.faceAuth'; + +// The surfaceId is obtained from the XComponent control. The surfaceId here is only an example. +let surfaceId = "123456"; +let manager = new userIAM_faceAuth.FaceAuthManager(); +try { + manager.setSurfaceId(surfaceId); + console.info("Set the surface ID successfully"); +} catch (e) { + console.error("Failed to set the surface ID, error = " + e); +} +``` diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md index ce73ba0bcd0ed53bb75bcb873cf35dd8f6910f6d..29044d135b43286a8b3df624584750022f6576b8 100644 --- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md +++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md @@ -1,4 +1,4 @@ -# User Authentication +# @ohos.userIAM.userAuth (User Authentication) The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login. @@ -12,268 +12,115 @@ The **userIAM.userAuth** module provides user authentication capabilities in ide import userIAM_userAuth from '@ohos.userIAM.userAuth'; ``` -## Sample Code - -```js -// API version 9 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; - -export default { - getVersion() { - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - }, - - start() { - console.info("start auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { - callback: (result: userIAM_userAuth.AuthResultInfo) => { - console.log("authV9 result " + result.result); - console.log("authV9 token " + result.token); - console.log("authV9 remainAttempts " + result.remainAttempts); - console.log("authV9 lockoutDuration " + result.lockoutDuration); - } - }); - // If tips are needed - auth.on("tip", { - callback : (result : userIAM_userAuth.TipInfo) => { - switch (result.tip) { - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: - // Do something; - case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: - // Do something; - // ... - default: - // Do others. - } - } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - }, +## AuthResultInfo9+ - getAvailableStatus() { - console.info("start check auth support"); - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - }, +Defines the authentication result. - cancel() { - console.info("start cancel auth"); - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +**System capability**: SystemCapability.UserIAM.UserAuth.Core - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| result | number | Yes | Authentication result. | +| token | Uint8Array | No | Token that has passed the user identity authentication.| +| remainAttempts | number | No | Number of remaining authentication times allowed.| +| lockoutDuration | number | No | Time for which the authentication operation is frozen.| -```js -// API version 8 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; -let auth = new userIAM_userAuth.UserAuth(); +## TipInfo9+ -export default { - getVersion() { - console.info("start get version"); - let version = auth.getVersion(); - console.info("auth version = " + version); - }, - - startAuth() { - console.info("start auth"); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - }, - - checkAuthSupport() { - console.info("start check auth support"); - let checkCode = this.auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - }, - - cancelAuth() { - console.info("start cancel auth"); - // Obtain contextId using auth(). - let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - console.info("auth onResult result = " + result); - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - console.info("auth onAcquireInfo module = " + module); - } - }); - let cancelCode = this.auth.cancel(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - } -} -``` +Defines the authentication tip information. -```js -// API version 6 -import userIAM_userAuth from '@ohos.userIAM.userAuth'; +**System capability**: SystemCapability.UserIAM.UserAuth.Core -export default { - startAuth() { - console.info("start auth"); - let auth = userIAM_userAuth.getAuthenticator(); - auth.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - // Add the logic to be executed when the authentication is successful. - }).catch((code)=>{ - console.error("auth fail, code = " + code); - // Add the logic to be executed when the authentication fails. - }); - } -} -``` +| Name | Type | Mandatory| Description | +| ------------ | ---------- | ---- | -------------------- | +| module | number | Yes | ID of the module that sends the tip information. | +| tip | number | Yes | Tip to be given during the authentication process. | ## EventInfo9+ -Defines the event information used in authentication. +Enumerates the authentication event information types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Type | Description | +| Value | Description | | --------- | ----------------------- | -| [AuthResultInfo](#authresultinfo9) | Authentication result information. | +| [AuthResultInfo](#authresultinfo9) | Authentication result. | | [TipInfo](#tipinfo9) | Authentication tip information. | +## AuthEventKey9+ + +Defines the keyword of the authentication event type. It is used as a parameter of [on](#on9). + +| Value | Description | +| ---------- | ----------------------- | +| "result" | If the first parameter of [on](#on9) is **result**, the [callback](#callback9) returns the authentication result.| +| "tip" | If the first parameter of [on](#on9) is **tip**, the [callback](#callback9) returns the authentication tip information.| + ## AuthEvent9+ -Provides callbacks to return authentication events. +Provides an asynchronous callback to return the authentication event information. ### callback9+ -callback: (result : EventInfo) => void +callback(result : EventInfo) : void -Called to return the authentication result or authentication tips. +Called to return the authentication result or authentication tip information. **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | -------------------------------------------------------- | -| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------ | +| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +// Obtain the authentication result through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` - -## AuthResultInfo9+ - -Defines the authentication result information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| result | number | Yes | Authentication result. | -| token | Uint8Array | No | Token that has passed the user identity authentication.| -| remainAttempts | number | No | Number of remaining authentication times allowed.| -| lockoutDuration | number | No | Time for which the authentication operation is frozen.| - -## TipInfo9+ - -Defines the authentication tip information. - -**System capability**: SystemCapability.UserIAM.UserAuth.Core - -| Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| module | number | No | Authentication module. | -| tip | number | No | Tip to be given during the authentication process. | - -## AuthEventKey9+ - -Defines the keyword of an authentication event. - -| Value | Description | -| ---------- | ----------------------- | -| "result" | Indicates authentication result.| -| "tip" | If **AuthEventKey** is **result**, the callback returns the authentication tip information.| + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +// Obtain the authentication tip information through a callback. +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.on("tip", { + callback : (result : userIAM_userAuth.TipInfo) => { + switch (result.tip) { + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: + // Do something; + case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: + // Do something. + default: + // Do others. + } + } + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ## AuthInstance9+ @@ -281,9 +128,12 @@ Implements user authentication. ### on9+ -on(name : AuthEventKey, callback : AuthEvent) : void +on : (name : AuthEventKey, callback : AuthEvent) => void -Enables authentication event listening. +Subscribes to the user authentication events of the specified type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to subscribe to events. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -291,151 +141,210 @@ Enables authentication event listening. | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event to listen for. | -| callback | AuthEvent | Yes | Callback invoked to return the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Authentication event type. If the value is **result**, the callback returns the authentication result. If the value is **tip**, the callback returns the authentication tip information.| +| callback | [AuthEvent](#authevent9) | Yes | Callback invoked to return the authentication result or tip information.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - // If tips are needed - auth.on("tip", { + }); + // Subscribe to authentication tip information. + auth.on("tip", { callback : (result : userIAM_userAuth.TipInfo) => { switch (result.tip) { case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT: // Do something; case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK: // Do something; - // ... default: // Do others. } } - }); - auth.start(); - console.log("authV9 start success"); - } catch (error) { - console.log("authV9 error = " + error); - // do error - } - ``` + }); + auth.start(); + console.log("authV9 start success"); +} catch (error) { + console.log("authV9 error = " + error); + // do error +} +``` ### off9+ -off(name : AuthEventKey) : void +off : (name : AuthEventKey) => void -Disables authentication event listening. +Unsubscribes from the user authentication events of the specific type. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to unsubscribe from events. **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | | --------- | -------------------------- | ---- | ------------------------- | -| name | AuthEventKey | Yes | Keyword of the authentication event. | +| name | [AuthEventKey](#autheventkey9) | Yes | Type of the authentication event to unsubscribe from. If the value is **result**, the authentication result is unsubscribed from. If the value is **tip**, the authentication tip information is unsubscribed from.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +let auth; +try { + auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.log("get auth instance success"); +} catch (error) { + console.log("get auth instance failed" + error); +} - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.on("result", { +try { + // Subscribe to the authentication result. + auth.on("result", { callback: (result: userIAM_userAuth.AuthResultInfo) => { console.log("authV9 result " + result.result); console.log("authV9 token " + result.token); console.log("authV9 remainAttempts " + result.remainAttempts); console.log("authV9 lockoutDuration " + result.lockoutDuration); } - }); - console.log("turn on authentication event listening success"); - } catch (error) { - console.log("turn off authentication event listening failed " + error); - // do error - } - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.off("result"); - console.info("turn off authentication event listening success"); - } catch (error) { - console.info("turn off authentication event listening failed, error = " + error); - } - ``` + }); + console.log("subscribe authentication event success"); +} catch (error) { + console.log("subscribe authentication event failed " + error); +} +// Unsubscribe from the authentication result. +try { + auth.off("result"); + console.info("cancel subscribe authentication event success"); +} catch (error) { + console.info("cancel subscribe authentication event failed, error = " + error); +} +``` ### start9+ -start() : void +start : () => void Starts authentication. +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500001 | Authentication failed. | +| 12500002 | General operation error. | +| 12500003 | The operation is canceled. | +| 12500004 | The operation is time-out. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500007 | The authentication task is busy. | +| 12500009 | The authenticator is locked. | +| 12500010 | The type of credential has not been enrolled. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - console.info("authV9 start auth success"); - } catch (error) { - console.info("authV9 start auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.start(); + console.info("authV9 start auth success"); +} catch (error) { + console.info("authV9 start auth failed, error = " + error); +} +``` ### cancel9+ -cancel(): void +cancel : () => void -Cancels the authentication. +Cancels this authentication. + +> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. The [AuthInstance](#authinstance9) instance must be the one being authenticated. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; - - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - auth.start(); - auth.cancel(); - console.info("cancel auth success"); - } catch (error) { - console.info("cancel auth failed, error = " + error); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + auth.cancel(); + console.info("cancel auth success"); +} catch (error) { + console.info("cancel auth failed, error = " + error); +} +``` ## userIAM_userAuth.getAuthInstance9+ @@ -444,7 +353,7 @@ getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel Obtains an **AuthInstance** instance for user authentication. > **NOTE**
-> Each **AuthInstance** can be used to initiate an authentication only once. +> An **AuthInstance** instance can be used for an authentication only once. **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -460,23 +369,35 @@ Obtains an **AuthInstance** instance for user authentication. | Type | Description | | ----------------------------------------- | ------------ | -| [AuthInstance](#authinstance9) | **Authenticator** object obtained.| +| [AuthInstance](#authinstance9) | **Authenticator** instance obtained.| + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); - let authType = userIAM_userAuth.UserAuthType.FACE; - let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); - console.info("get auth instance success"); - } catch (error) { - console.info("get auth instance success failed, error = " + error); - } - ``` +let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]); +let authType = userIAM_userAuth.UserAuthType.FACE; +let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1; + +try { + let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel); + console.info("get auth instance success"); +} catch (error) { + console.info("get auth instance success failed, error = " + error); +} +``` ## userIAM_userAuth.getVersion9+ @@ -494,24 +415,33 @@ Obtains the version of this authenticator. | ------ | ---------------------- | | number | Authenticator version obtained.| +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 12500002 | General operation error. | + **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - let version = userIAM_userAuth.getVersion(); - console.info("auth version = " + version); - } catch (error) { - console.info("get version failed, error = " + error); - } - ``` +try { + let version = userIAM_userAuth.getVersion(); + console.info("auth version = " + version); +} catch (error) { + console.info("get version failed, error = " + error); +} +``` ## userIAM_userAuth.getAvailableStatus9+ getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void -Checks whether the authentication capability of the specified trust level is available. +Checks whether the specified authentication capability is supported. **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -522,54 +452,65 @@ Checks whether the authentication capability of the specified trust level is ava | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | + +For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md). + +**Error codes** + +| ID| Error Message| +| -------- | ------- | +| 201 | Permission verification failed. | +| 401 | Incorrect parameters. | +| 12500002 | General operation error. | +| 12500005 | The authentication type is not supported. | +| 12500006 | The authentication trust level is not supported. | +| 12500010 | The type of credential has not been enrolled. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - try { - userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - console.info("current auth trust level is supported"); - } catch (error) { - console.info("current auth trust level is not supported, error = " + error); - } - ``` +try { + userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); + console.info("current auth trust level is supported"); +} catch (error) { + console.info("current auth trust level is not supported, error = " + error); +} +``` - ## ResultCodeV99+ +## UserAuthResultCode9+ -Enumerates the operation results. +Enumerates the authentication result codes. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------- | ------ | -------------------- | -| SUCCESS | 12500000 | The operation is successful. | -| FAIL | 12500001 | The operation failed. | -| GENERAL_ERROR | 12500002 | A common operation error occurred. | -| CANCELED | 12500003 | The operation is canceled. | -| TIMEOUT | 12500004 | The operation timed out. | +| SUCCESS | 12500000 | The authentication is successful. | +| FAIL | 12500001 | The authentication failed. | +| GENERAL_ERROR | 12500002 | A general operation error occurred. | +| CANCELED | 12500003 | The authentication is canceled. | +| TIMEOUT | 12500004 | The authentication timed out. | | TYPE_NOT_SUPPORT | 12500005 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 12500006 | The authentication trust level is not supported. | | BUSY | 12500007 | Indicates the busy state. | -| INVALID_PARAMETERS | 12500008 | Invalid parameters are detected. | | LOCKED | 12500009 | The authentication executor is locked. | | NOT_ENROLLED | 12500010 | The user has not entered the authentication information.| ## UserAuth8+ -Provides methods to manage an **Authenticator** object. +Provides APIs to manage an **Authenticator** object. ### constructor(deprecated) constructor() -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). +A constructor used to create an authenticator instance. -A constructor used to create an **authenticator** object. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -577,25 +518,24 @@ A constructor used to create an **authenticator** object. | Type | Description | | ---------------------- | -------------------- | -| [UserAuth](#userauth8) | **Authenticator** object obtained.| +| [UserAuth](#userauth8) | **Authenticator** instance obtained.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - ``` +let auth = new userIAM_userAuth.UserAuth(); +``` ### getVersion(deprecated) getVersion() : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). +Obtains the version of this authenticator. -Obtains the authentication executor version. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -609,23 +549,22 @@ Obtains the authentication executor version. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; - let auth = new userIAM_userAuth.UserAuth(); - let version = auth.getVersion(); - console.info("auth version = " + version); - ``` +let auth = new userIAM_userAuth.UserAuth(); +let version = auth.getVersion(); +console.info("auth version = " + version); +``` ### getAvailableStatus(deprecated) getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). +Checks whether the specified authentication capability is supported. -Obtains the available status of the specified authentication trust level. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -636,40 +575,37 @@ Obtains the available status of the specified authentication trust level. | Name | Type | Mandatory| Description | | -------------- | ---------------------------------- | ---- | -------------------------- | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | **Return value** | Type | Description | | ------ | ------------------------------------------------------------ | -| number | Available status obtained. For details, see [ResultCode](#resultcodedeprecated).| +| number | Query result. If the authentication capability is supported, **SUCCESS** is returned. Otherwise, a [ResultCode](#resultcodedeprecated) is returned.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); - if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("check auth support success"); - // Add the logic to be executed if the specified authentication type is supported. - } else { - console.error("check auth support fail, code = " + checkCode); - // Add the logic to be executed if the specified authentication type is not supported. - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1); +if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("check auth support success"); +} else { + console.error("check auth support fail, code = " + checkCode); +} +``` ### auth(deprecated) auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9). - Performs user authentication. This API uses a 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 [start](#start9). + **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -680,8 +616,8 @@ Performs user authentication. This API uses a callback to return the result. | -------------- | ---------------------------------------- | ---- | ------------------------ | | challenge | Uint8Array | Yes | Challenge value, which can be null. | | authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.| -| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. | -| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | +| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. | +| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. | **Return value** @@ -691,36 +627,35 @@ Performs user authentication. This API uses a callback to return the result. **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### cancelAuth(deprecated) cancelAuth(contextID : Uint8Array) : number -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). +Cancels an authentication based on the context ID. -Cancels an authentication. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9). **Required permissions**: ohos.permission.ACCESS_BIOMETRIC @@ -730,100 +665,86 @@ Cancels an authentication. | Name | Type | Mandatory| Description | | --------- | ---------- | ---- | ------------------------------------------ | -| contextID | Uint8Array | Yes | Context ID, which is obtained by using [auth](#authdeprecated).| +| contextID | Uint8Array | Yes | Context ID, which is obtained by [auth](#authdeprecated).| **Return value** | Type | Description | | ------ | ------------------------ | -| number | Whether the authentication is canceled.| +| number | Returns **SUCCESS** if the cancellation is successful. Returns a [ResultCode](#resultcodedeprecated) otherwise.| **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - // contextId can be obtained using auth(). In this example, it is defined here. - let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); - let auth = new userIAM_userAuth.UserAuth(); - let cancelCode = auth.cancelAuth(contextId); - if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { - console.info("cancel auth success"); - } else { - console.error("cancel auth fail"); - } - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +// contextId can be obtained by auth(). In this example, it is defined here. +let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]); +let auth = new userIAM_userAuth.UserAuth(); +let cancelCode = auth.cancelAuth(contextId); +if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) { + console.info("cancel auth success"); +} else { + console.error("cancel auth fail"); +} +``` ## IUserAuthCallback(deprecated) -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). +Provides callbacks to return the authentication result. -Defines the object of the result returned by the callback during authentication. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9). ### onResult(deprecated) onResult: (result : number, extraInfo : AuthResult) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to return the authentication result. -Obtains the authentication result. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| --------- | -------------------------- | ---- | ------------------------------------------------------------ | -| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated). | +| Name | Type | Mandatory| Description | +| --------- | -------------------------- | ---- | ------------------------------------------------ | +| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated).| | extraInfo | [AuthResult](#authresultdeprecated) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.| - **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; + +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onResult: (result, extraInfo) => { + try { + console.info("auth onResult result = " + result); + console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); + if (result == userIAM_userAuth.ResultCode.SUCCESS) { + // Add the logic to be executed when the authentication is successful. + } else { + // Add the logic to be executed when the authentication fails. + } + } catch (e) { + console.info("auth onResult error = " + e); + } + } +}); +``` ### onAcquireInfo(deprecated) onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void -> **NOTE** -> ->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). +Called to acquire authentication tip information. This API is optional. -Obtains the tip code information during authentication. This function is optional. +> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9). **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -831,89 +752,74 @@ Obtains the tip code information during authentication. This function is optiona | Name | Type | Mandatory| Description | | --------- | ------ | ---- | ------------------------------ | -| module | number | Yes | Type of the authentication executor. | -| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.| +| module | number | Yes | ID of the module that sends the tip information. | +| acquire | number | Yes | Authentication tip information.| | extraInfo | any | Yes | Reserved field. | **Example** - ```js - import userIAM_userAuth from '@ohos.userIAM.userAuth'; - - let auth = new userIAM_userAuth.UserAuth(); - auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { - onResult: (result, extraInfo) => { - try { - console.info("auth onResult result = " + result); - console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo)); - if (result == userIAM_userAuth.ResultCode.SUCCESS) { - // Add the logic to be executed when the authentication is successful. - } else { - // Add the logic to be executed when the authentication fails. - } - } catch (e) { - console.info("auth onResult error = " + e); - } - }, - - onAcquireInfo: (module, acquire, extraInfo) => { - try { - console.info("auth onAcquireInfo module = " + module); - console.info("auth onAcquireInfo acquire = " + acquire); - console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); - } catch (e) { - console.info("auth onAcquireInfo error = " + e); - } - } - }); - ``` +```js +import userIAM_userAuth from '@ohos.userIAM.userAuth'; -## AuthResult(deprecated) +let auth = new userIAM_userAuth.UserAuth(); +auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, { + onAcquireInfo: (module, acquire, extraInfo) => { + try { + console.info("auth onAcquireInfo module = " + module); + console.info("auth onAcquireInfo acquire = " + acquire); + console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo)); + } catch (e) { + console.info("auth onAcquireInfo error = " + e); + } + } +}); +``` -> **NOTE** -> ->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). +## AuthResult(deprecated) Represents the authentication result object. +> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9). + **System capability**: SystemCapability.UserIAM.UserAuth.Core | Name | Type | Mandatory| Description | -| ------------ | ---------- | ---- | -------------------- | -| token | Uint8Array | No | Identity authentication token. | +| ------------ | ---------- | ---- | -------------------| +| token | Uint8Array | No | Authentication token information.| | remainTimes | number | No | Number of remaining authentication operations.| | freezingTime | number | No | Time for which the authentication operation is frozen.| ## ResultCode(deprecated) -> **NOTE**
-> This object is deprecated since API version 9. You are advised to use [ResultCodeV9](#resultcodev99). +Enumerates the authentication result codes. -Enumerates the operation results. +> **NOTE**
+> This object is deprecated since API version 9. You are advised to use [UserAuthResultCode](#userauthresultcode9). **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value| Description | | ----------------------- | ------ | -------------------- | | SUCCESS | 0 | The operation is successful. | -| FAIL | 1 | The operation failed. | -| GENERAL_ERROR | 2 | A common operation error occurred. | -| CANCELED | 3 | The operation is canceled. | -| TIMEOUT | 4 | The operation timed out. | +| FAIL | 1 | The authentication failed. | +| GENERAL_ERROR | 2 | A general operation error occurred. | +| CANCELED | 3 | The authentication is canceled. | +| TIMEOUT | 4 | The authentication timed out. | | TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. | | TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. | | BUSY | 7 | Indicates the busy state. | +| INVALID_PARAMETERS | 8 | Invalid parameters are detected. | | LOCKED | 9 | The authentication executor is locked. | | NOT_ENROLLED | 10 | The user has not entered the authentication information.| - ## FaceTips8+ Enumerates the tip codes used during the facial authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------------------------- | ------ | ------------------------------------ | | FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. | | FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. | @@ -934,7 +840,7 @@ Enumerates the tip codes used during the fingerprint authentication process. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | --------------------------------- | ------ | -------------------------------------------------- | | FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. | | FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.| @@ -950,7 +856,7 @@ Enumerates the identity authentication types. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ----------- | ------ | ---------- | | FACE | 2 | Facial authentication.| | FINGERPRINT | 4 | Fingerprint authentication.| @@ -961,7 +867,7 @@ Enumerates the trust levels of the authentication result. **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name| Default Value| Description | +| Name| Value | Description | | ---- | ------ | ------------------------- | | ATL1 | 10000 | Trust level 1.| | ATL2 | 20000 | Trust level 2.| @@ -972,18 +878,18 @@ Enumerates the trust levels of the authentication result. getAuthenticator(): Authenticator +Obtains an **Authenticator** instance for user authentication. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [constructor](#constructordeprecated). -Obtains an **Authenticator** object for user authentication. - **System capability**: SystemCapability.UserIAM.UserAuth.Core **Return value** | Type | Description | | ----------------------------------------- | ------------ | -| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.| +| [Authenticator](#authenticatordeprecated) | **Authenticator** instance obtained.| **Example** ```js @@ -992,61 +898,61 @@ Obtains an **Authenticator** object for user authentication. ## Authenticator(deprecated) +Defines the **Authenticator** object. + > **NOTE**
> This object is deprecated since API version 8. You are advised to use [UserAuth](#userauth8). -Provides methods to manage an **Authenticator** object. - - ### execute(deprecated) execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void +Performs user authentication. This API uses asynchronous callback to return the result. + > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses asynchronous callback to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | -------------------------- | | type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.| -| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| -| callback | AsyncCallback<number> | No | Callback used to return the result. | +| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | - Parameters returned in callback +Parameters returned in callback | Type | Description | | ------ | ------------------------------------------------------------ | | number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).| **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ - if (code === userIAM_userAuth.ResultCode.SUCCESS) { - console.info("auth success"); - return; - } - console.error("auth fail, code = " + code); - }); - ``` + +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2", (error, code)=>{ + if (code === userIAM_userAuth.ResultCode.SUCCESS) { + console.info("auth success"); + return; + } + console.error("auth fail, code = " + code); +}); +``` ### execute(deprecated) -execute(type:AuthType, level:SecureLevel): Promise<number> +execute(type : AuthType, level : SecureLevel): Promise<number> + +Performs user authentication. This API uses a promise to return the result. > **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated). -Performs user authentication. This API uses a promise to return the result. - **Required permissions**: ohos.permission.ACCESS_BIOMETRIC **System capability**: SystemCapability.UserIAM.UserAuth.Core @@ -1066,25 +972,25 @@ Performs user authentication. This API uses a promise to return the result. **Example** - ```js - let authenticator = userIAM_userAuth.getAuthenticator(); - authenticator.execute("FACE_ONLY", "S2").then((code)=>{ - console.info("auth success"); - }).catch((error)=>{ - console.error("auth fail, code = " + error); - }); - ``` +```js +let authenticator = userIAM_userAuth.getAuthenticator(); +authenticator.execute("FACE_ONLY", "S2").then((code)=>{ + console.info("auth success"); +}).catch((error)=>{ + console.error("auth fail, code = " + error); +}); +``` ## AuthenticationResult(deprecated) +Enumerates the authentication results. + > **NOTE**
> This object is discarded since API version 8. You are advised to use [ResultCode](#resultcodedeprecated). -Enumerates the authentication results. - **System capability**: SystemCapability.UserIAM.UserAuth.Core -| Name | Default Value| Description | +| Name | Value | Description | | ------------------ | ------ | -------------------------- | | NO_SUPPORT | -1 | The device does not support the current authentication mode.| | SUCCESS | 0 | The authentication is successful. | diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md index 226f7686f490b2d3fd28e8263d7226eb02091c09..f4193680d4d0732a38ab9564bbd67428c7a3497a 100755 --- a/en/application-dev/reference/apis/js-apis-util.md +++ b/en/application-dev/reference/apis/js-apis-util.md @@ -1,17 +1,15 @@ -# util +# @ohos.util (util) +The **util** module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. > **NOTE** > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. -This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types. - - ## Modules to Import -``` +```js import util from '@ohos.util'; ``` @@ -43,37 +41,6 @@ let res = util.format("%s", "hello world!"); console.log(res); ``` -## util.printf(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. - -printf(format: string, ...args: Object[]): string - -Formats the specified values and inserts them into the string by replacing the wildcard in the string. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| format | string | Yes| String.| -| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string. | - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | String containing the formatted values.| - -**Example** - ```js - let res = util.printf("%s", "hello world!"); - console.log(res); - ``` - ## util.errnoToString9+ errnoToString(errno: number): string @@ -96,42 +63,11 @@ Obtains detailed information about a system error code. **Example** - ```js -let errnum = 10; // 10 is a system error code. +```js +let errnum = -1; // -1 is a system error code. let result = util.errnoToString(errnum); console.log("result = " + result); - ``` - -## util.getErrorString(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. - -getErrorString(errno: number): string - -Obtains detailed information about a system error code. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| errno | number | Yes| Error code generated.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Detailed information about the error code.| - -**Example** - ```js - let errnum = 10; // 10 is a system error code. - let result = util.getErrorString(errnum); - console.log("result = " + result); - ``` +``` ## util.callbackWrapper @@ -154,6 +90,7 @@ Calls back an asynchronous function. In the callback, the first parameter indica | Function | Callback, in which the first parameter indicates the cause of the rejection (the value is **null** if the promise has been resolved) and the second parameter indicates the resolved value.| **Example** + ```js async function promiseFn() { return Promise.reject('value'); @@ -187,6 +124,7 @@ Processes an asynchronous function and returns a promise. | Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| **Example** + ```js function aysnFun(str1, str2) { if (typeof str1 === 'object' && typeof str2 === 'object') { @@ -201,30 +139,6 @@ Processes an asynchronous function and returns a promise. }) ``` -## util.promiseWrapper(deprecated) - -promiseWrapper(original: (err: Object, value: Object) => void): Object - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use **[util.promisify9+](#utilpromisify9)** instead. - -Processes an asynchronous function and returns a promise. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| original | Function | Yes| Asynchronous function.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| - ## util.randomUUID9+ randomUUID(entropyCache?: boolean): string @@ -246,6 +160,7 @@ Uses a secure random number generator to generate a random universally unique id | string | A string representing the UUID generated.| **Example** + ```js let uuid = util.randomUUID(true); console.log("RFC 4122 Version 4 UUID:" + uuid); @@ -274,6 +189,7 @@ Uses a secure random number generator to generate a random binary UUID of RFC 41 | Uint8Array | A Uint8Array value representing the UUID generated.| **Example** + ```js let uuid = util.randomBinaryUUID(true); console.log(JSON.stringify(uuid)); @@ -302,6 +218,7 @@ Parses a UUID from a string, as described in RFC 4122 version 4. | Uint8Array | A Uint8Array value representing the UUID parsed. If the parsing fails, **SyntaxError** is thrown.| **Example** + ```js let uuid = util.parseUUID("84bdf796-66cc-4655-9b89-d6218d100f9c"); console.log(JSON.stringify(uuid)); @@ -309,6 +226,96 @@ Parses a UUID from a string, as described in RFC 4122 version 4. // 132,189,247,150,102,204,70,85,155,137,214,33,141,16,15,156 ``` +## util.printf(deprecated) + +printf(format: string, ...args: Object[]): string + +Formats the specified values and inserts them into the string by replacing the wildcard in the string. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.format9+](#utilformat9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| format | string | Yes| String.| +| ...args | Object[] | No| Values to format. The formatted values will be replaced the wildcard in the string.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | String containing the formatted values.| + +**Example** + + ```js + let res = util.printf("%s", "hello world!"); + console.log(res); + ``` + + +## util.getErrorString(deprecated) + +getErrorString(errno: number): string + +Obtains detailed information about a system error code. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [util.errnoToString9+](#utilerrnotostring9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| errno | number | Yes| Error code generated.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Detailed information about the error code.| + +**Example** + + ```js + let errnum = -1; // -1 is a system error code. + let result = util.getErrorString(errnum); + console.log("result = " + result); + ``` + +## util.promiseWrapper(deprecated) + +promiseWrapper(original: (err: Object, value: Object) => void): Object + +Processes an asynchronous function and returns a promise. + +> **NOTE** +> +> This API is unavailable. You are advised to use [util.promisify9+](#utilpromisify9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| original | Function | Yes| Asynchronous function.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Function | Function in the error-first style (that is, **(err, value) =>...** is called as the last parameter) and the promise.| + + ## TextDecoder ### Attributes @@ -331,10 +338,12 @@ A constructor used to create a **TextDecoder** object. ### create9+ -create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean },): TextDecoder; +create(encoding?: string,options?: { fatal?: boolean; ignoreBOM?: boolean }): TextDecoder; Creates a **TextDecoder** object. It provides the same function as the deprecated argument constructor. +**System capability**: SystemCapability.Utils.Lang + **Parameters** | Name | Type | Mandatory| Description | @@ -342,7 +351,7 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate | encoding | string | No | Encoding format. | | options | Object | No | Encoding-related options, which include **fatal** and **ignoreBOM**.| - **Table 1.1** options +**Table 1.1** options | Name | Type| Mandatory| Description | | --------- | -------- | ---- | ------------------ | @@ -351,21 +360,64 @@ Creates a **TextDecoder** object. It provides the same function as the deprecate **Example** - ```js +```js let textDecoder = new util.TextDecoder() textDecoder.create('utf-8', { ignoreBOM : true }); +``` + +### decodeWithStream9+ + +decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string + +Decodes the input content. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| input | Uint8Array | Yes| Uint8Array to decode.| +| options | Object | No| Options related to decoding.| + +**Table 2** options + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| string | Data decoded.| + +**Example** + + ```js + let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); + let result = new Uint8Array(6); + result[0] = 0xEF; + result[1] = 0xBB; + result[2] = 0xBF; + result[3] = 0x61; + result[4] = 0x62; + result[5] = 0x63; + console.log("input num:"); + let retStr = textDecoder.decodeWithStream( result , {stream: false}); + console.log("retStr = " + retStr); ``` ### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - -constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean },) +constructor(encoding?: string, options?: { fatal?: boolean; ignoreBOM?: boolean }) A constructor used to create a **TextDecoder** object. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [create9+](#create9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -383,16 +435,21 @@ A constructor used to create a **TextDecoder** object. | ignoreBOM | boolean | No| Whether to ignore the BOM.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); ``` -### decode +### decode(deprecated) decode(input: Uint8Array, options?: { stream?: false }): string Decodes the input content. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [decodeWithStream9+](#decodewithstream9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -402,7 +459,7 @@ Decodes the input content. | input | Uint8Array | Yes| Uint8Array to decode.| | options | Object | No| Options related to decoding.| - **Table 2** options +**Table 2** options | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | @@ -415,6 +472,7 @@ Decodes the input content. | string | Data decoded.| **Example** + ```js let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); let result = new Uint8Array(6); @@ -429,72 +487,48 @@ Decodes the input content. console.log("retStr = " + retStr); ``` +## TextEncoder -### decodeWithStream9+ +### Attributes -decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string +**System capability**: SystemCapability.Utils.Lang -Decodes the input content. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| encoding | string | Yes| No| Encoding format. The default format is **utf-8**.| -**System capability**: SystemCapability.Utils.Lang +### constructor -**Parameters** +constructor() -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| input | Uint8Array | Yes| Uint8Array to decode.| -| options | Object | No| Options related to decoding.| +A constructor used to create a **TextEncoder** object. - **Table 2** options - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| stream | boolean | No| Whether to allow data blocks in subsequent **decodeWithStream()**. If data is processed in blocks, set this parameter to **true**. If this is the last data block to process or data is not divided into blocks, set this parameter to **false**. The default value is **false**.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| string | Data decoded.| +**System capability**: SystemCapability.Utils.Lang **Example** + ```js - let textDecoder = new util.TextDecoder("utf-8",{ignoreBOM: true}); - let result = new Uint8Array(6); - result[0] = 0xEF; - result[1] = 0xBB; - result[2] = 0xBF; - result[3] = 0x61; - result[4] = 0x62; - result[5] = 0x63; - console.log("input num:"); - let retStr = textDecoder.decodeWithStream( result , {stream: false}); - console.log("retStr = " + retStr); + let textEncoder = new util.TextEncoder(); ``` +### constructor9+ -## TextEncoder +constructor(encoding?: string) -### Attributes +A constructor used to create a **TextEncoder** object. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| encoding | string | Yes| No| Encoding format. The default format is **utf-8**.| - - -### constructor - -constructor() - -A constructor used to create a **TextEncoder** object. +**Parameters** -**System capability**: SystemCapability.Utils.Lang +| Name| Type| Mandatory| Description| +| ----- | ---- | ---- | ---- | +| encoding | string | No| Encoding format.| **Example** + ```js - let textEncoder = new util.TextEncoder(); + let textEncoder = new util.TextEncoder("utf-8"); ``` ### encodeInto9+ @@ -509,7 +543,7 @@ Encodes the input content. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| input | string | Yes | String to encode.| +| input | string | No | String to encode.| **Return value** @@ -526,38 +560,6 @@ let result = new Uint8Array(buffer); result = textEncoder.encodeInto("\uD800¥¥"); ``` -### encode(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. - -encode(input?: string): Uint8Array - -Encodes the input content. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| input | string | Yes| String to encode.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Uint8Array | Encoded text.| - -**Example** - ```js - let textEncoder = new util.TextEncoder(); - let buffer = new ArrayBuffer(20); - let result = new Uint8Array(buffer); - result = textEncoder.encode("\uD800¥¥"); - ``` - ### encodeIntoUint8Array9+ encodeIntoUint8Array(input: string, dest: Uint8Array, ): { read: number; written: number } @@ -586,19 +588,19 @@ let that = new util.TextEncoder() let buffer = new ArrayBuffer(4) let dest = new Uint8Array(buffer) let result = new Object() -result = that.encodeInto('abcd', dest) +result = that.encodeIntoUint8Array('abcd', dest) ``` ### encodeInto(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeIntoUint8Array9+](#encodeintouint8array9) instead. - encodeInto(input: string, dest: Uint8Array, ): { read: number; written: number } Stores the UTF-8 encoded text. +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeIntoUint8Array9+](#encodeintouint8array9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -623,6 +625,38 @@ Stores the UTF-8 encoded text. result = that.encodeInto('abcd', dest) ``` +### encode(deprecated) + +encode(input?: string): Uint8Array + +Encodes the input content. + +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [encodeInto9+](#encodeinto9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| input | string | No| String to encode.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Uint8Array | Encoded text.| + +**Example** + ```js + let textEncoder = new util.TextEncoder(); + let buffer = new ArrayBuffer(20); + let result = new Uint8Array(buffer); + result = textEncoder.encode("\uD800¥¥"); + ``` + ## RationalNumber8+ ### constructor9+ @@ -635,13 +669,13 @@ A constructor used to create a **RationalNumber** object. **Example** - ```js +```js let rationalNumber = new util.RationalNumber(); - ``` +``` ### parseRationalNumber9+ -parseRationalNumber(numerator: number,denominator: number) +parseRationalNumber(numerator: number,denominator: number): RationalNumber Parses a rational number. Previously, this processing is an internal action of the deprecated constructor. @@ -656,35 +690,9 @@ Parses a rational number. Previously, this processing is an internal action of t **Example** - ```js -let rationalNumber = new util.RationalNumber(); -rationalNumber.parseRationalNumber(1,2) - ``` - -### constructor(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. - -constructor(numerator: number,denominator: number) - -A constructor used to create a **RationalNumber** object. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| numerator | number | Yes| Numerator, which is an integer.| -| denominator | number | Yes| Denominator, which is an integer.| - -**Example** - - ```js - let rationalNumber = new util.RationalNumber(1,2); - ``` +```js +let rationalNumber = util.RationalNumber.parseRationalNumber(1,2) +``` ### createRationalFromString8+ @@ -707,10 +715,11 @@ Creates a **RationalNumber** object based on the given string. | object | **RationalNumber** object created.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +``` ### compare9+ @@ -740,37 +749,6 @@ let rational = util.RationalNumber.createRationalFromString("3/4"); let result = rationalNumber.compare(rational); ``` -### compareTo8+(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. - -compareTo​(another: RationalNumber): number​ - -Compares this **RationalNumber** object with a given object. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| - -**Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - let result = rationalNumber.compareTo(rational); - ``` - ### valueOf8+ valueOf(): number @@ -786,10 +764,11 @@ Obtains the value of this **RationalNumber** object as an integer or a floating- | number | An integer or a floating-point number.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.valueOf(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.valueOf(); +``` ### equals8+ @@ -812,11 +791,12 @@ Checks whether this **RationalNumber** object equals the given object. | boolean | Returns **true** if the two objects are equal; returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let rational = util.RationalNumber.createRationalFromString("3/4"); - let result = rationalNumber.equals(rational); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.equals(rational); +``` ### getCommonFactor9+ @@ -841,40 +821,10 @@ Obtains the greatest common divisor of two specified integers. **Example** - ```js +```js let rationalNumber = new util.RationalNumber(1,2); let result = util.RationalNumber.getCommonFactor(4,6); - ``` - -### getCommonDivisor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. - -static getCommonDivisor​(number1: number,number2: number): number - -Obtains the greatest common divisor of two specified integers. - -**System capability**: SystemCapability.Utils.Lang - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| number1 | number | Yes| The first integer used to get the greatest common divisor.| -| number2 | number | Yes| The second integer used to get the greatest common divisor.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Greatest common divisor obtained.| - -**Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = util.RationalNumber.getCommonDivisor(4,6); - ``` +``` ### getNumerator8+ @@ -891,10 +841,11 @@ Obtains the numerator of this **RationalNumber** object. | number | Numerator of this **RationalNumber** object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.getNumerator(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.getNumerator(); +``` ### getDenominator8+ @@ -911,10 +862,11 @@ Obtains the denominator of this **RationalNumber** object. | number | Denominator of this **RationalNumber** object.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.getDenominator(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.getDenominator(); +``` ### isZero8+ @@ -931,10 +883,11 @@ Checks whether this **RationalNumber** object is **0**. | boolean | Returns **true** if the value of this **RationalNumber** object is **0**; returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isZero(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isZero(); +``` ### isNaN8+ @@ -951,10 +904,11 @@ Checks whether this **RationalNumber** object is a Not a Number (NaN). | boolean | Returns **true** if this **RationalNumber** object is a NaN (the denominator and numerator are both **0**); returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isNaN(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isNaN(); +``` ### isFinite8+ @@ -971,10 +925,11 @@ Checks whether this **RationalNumber** object represents a finite value. | boolean | Returns **true** if this **RationalNumber** object represents a finite value (the denominator is not **0**); returns **false** otherwise.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.isFinite(); - ``` + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.isFinite(); +``` ### toString8+ @@ -991,13 +946,102 @@ Obtains the string representation of this **RationalNumber** object. | string | Returns **NaN** if the numerator and denominator of this object are both **0**; returns a string in Numerator/Denominator format otherwise, for example, **3/5**.| **Example** - ```js - let rationalNumber = new util.RationalNumber(1,2); - let result = rationalNumber.toString(); - ``` +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = rationalNumber.toString(); +``` -## LRUCache9+ +### constructor(deprecated) + +constructor(numerator: number,denominator: number) + +A constructor used to create a **RationalNumber** object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| numerator | number | Yes| Numerator, which is an integer.| +| denominator | number | Yes| Denominator, which is an integer.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +``` + +### compareTo(deprecated) + +compareTo​(another: RationalNumber): number​ + +Compares this **RationalNumber** object with a given object. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [compare9+](#compare9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| another | RationalNumber | Yes| Object used to compare with this **RationalNumber** object.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Returns **0** if the two objects are equal; returns **1** if the given object is less than this object; return **-1** if the given object is greater than this object.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +let rational = util.RationalNumber.createRationalFromString("3/4"); +let result = rationalNumber.compareTo(rational); +``` + +### getCommonDivisor(deprecated) + +static getCommonDivisor​(number1: number,number2: number): number + +Obtains the greatest common divisor of two specified integers. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCommonFactor9+](#getcommonfactor9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| number1 | number | Yes| The first integer used to get the greatest common divisor.| +| number2 | number | Yes| The second integer used to get the greatest common divisor.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Greatest common divisor obtained.| + +**Example** + +```js +let rationalNumber = new util.RationalNumber(1,2); +let result = util.RationalNumber.getCommonDivisor(4,6); +``` + +## LRUCache9+ ### Attributes @@ -1005,22 +1049,22 @@ Obtains the string representation of this **RationalNumber** object. | Name | Type | Readable| Writable| Description | | ------ | ------ | ---- | ---- | ---------------------- | -| length | number | Yes | No | Total number of values in this buffer. | +| length | number | Yes | No | Total number of values in this cache.| **Example** - ```js +```js let pro = new util.LRUCache(); pro.put(2,10); pro.put(1,8); let result = pro.length; - ``` +``` ### constructor9+ constructor(capacity?: number) -A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +A constructor used to create a **LruCache** instance. The default capacity of the cache is 64. **System capability**: SystemCapability.Utils.Lang @@ -1028,20 +1072,20 @@ A constructor used to create a **LruBuffer** instance. The default capacity of t | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ---------------------------- | -| capacity | number | No | Capacity of the **LruBuffer** to create.| +| capacity | number | No | Capacity of the **LruCache** to create.| **Example** - ```js +```js let lrubuffer= new util.LRUCache(); - ``` +``` ### updateCapacity9+ updateCapacity(newCapacity: number): void -Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +Changes the **LruCache** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. **System capability**: SystemCapability.Utils.Lang @@ -1049,21 +1093,21 @@ Changes the **LruBuffer** capacity. If the new capacity is less than or equal to | Name | Type | Mandatory| Description | | ----------- | ------ | ---- | ---------------------------- | -| newCapacity | number | Yes | New capacity of the **LruBuffer**.| +| newCapacity | number | Yes | New capacity of the **LruCache**.| **Example** - ```js +```js let pro = new util.LRUCache(); let result = pro.updateCapacity(100); - ``` +``` ### toString9+ toString(): string -Obtains the string representation of this **LruBuffer** object. +Obtains the string representation of this **LruCache** object. **System capability**: SystemCapability.Utils.Lang @@ -1071,24 +1115,24 @@ Obtains the string representation of this **LruBuffer** object. | Type | Description | | ------ | -------------------------- | -| string | String representation of this **LruBuffer** object.| +| string | String representation of this **LruCache** object.| **Example** - ```js +```js let pro = new util.LRUCache(); pro.put(2,10); pro.get(2); pro.remove(20); let result = pro.toString(); - ``` +``` ### getCapacity9+ getCapacity(): number -Obtains the capacity of this buffer. +Obtains the capacity of this cache. **System capability**: SystemCapability.Utils.Lang @@ -1096,7 +1140,7 @@ Obtains the capacity of this buffer. | Type | Description | | ------ | ---------------------- | -| number | Capacity of this buffer.| +| number | Capacity of this cache.| **Example** @@ -1110,7 +1154,7 @@ let result = pro.getCapacity(); clear(): void -Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +Clears key-value pairs from this cache. The **afterRemoval()** method will be called to perform subsequent operations. **System capability**: SystemCapability.Utils.Lang @@ -1175,7 +1219,7 @@ let result = pro.getMissCount(); getRemovalCount(): number -Obtains the number of removals from this buffer. +Obtains the number of removals from this cache. **System capability**: SystemCapability.Utils.Lang @@ -1183,7 +1227,7 @@ Obtains the number of removals from this buffer. | Type | Description | | ------ | -------------------------- | -| number | Number of removals from the buffer.| +| number | Number of removals from the cache.| **Example** @@ -1224,7 +1268,7 @@ let result = pro.getMatchCount(); getPutCount(): number -Obtains the number of additions to this buffer. +Obtains the number of additions to this cache. **System capability**: SystemCapability.Utils.Lang @@ -1232,7 +1276,7 @@ Obtains the number of additions to this buffer. | Type | Description | | ------ | ---------------------------- | -| number | Number of additions to the buffer.| +| number | Number of additions to the cache.| **Example** @@ -1247,7 +1291,7 @@ let result = pro.getPutCount(); isEmpty(): boolean -Checks whether this buffer is empty. +Checks whether this cache is empty. **System capability**: SystemCapability.Utils.Lang @@ -1255,7 +1299,7 @@ Checks whether this buffer is empty. | Type | Description | | ------- | ---------------------------------------- | -| boolean | Returns **true** if the buffer does not contain any value.| +| boolean | Returns **true** if the cache does not contain any value.| **Example** @@ -1284,7 +1328,7 @@ Obtains the value of the specified key. | Type | Description | | ------------------------ | ------------------------------------------------------------ | -| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| +| V \| undefined | Returns the value of the key if a match is found in the cache; returns **undefined** otherwise.| **Example** @@ -1299,7 +1343,7 @@ let result = pro.get(2); put(key: K,value: V): V -Adds a key-value pair to this buffer. +Adds a key-value pair to this cache. **System capability**: SystemCapability.Utils.Lang @@ -1327,7 +1371,7 @@ let result = pro.put(2,10); values(): V[] -Obtains all values in this buffer, listed from the most to the least recently accessed. +Obtains all values in this cache, listed from the most to the least recently accessed. **System capability**: SystemCapability.Utils.Lang @@ -1335,7 +1379,7 @@ Obtains all values in this buffer, listed from the most to the least recently ac | Type | Description | | --------- | ------------------------------------------------------------ | -| V [] | All values in the buffer, listed from the most to the least recently accessed.| +| V [] | All values in the cache, listed from the most to the least recently accessed.| **Example** @@ -1352,7 +1396,7 @@ let result = pro.values(); keys(): K[] -Obtains all keys in this buffer, listed from the most to the least recently accessed. +Obtains all keys in this cache, listed from the most to the least recently accessed. **System capability**: SystemCapability.Utils.Lang @@ -1360,7 +1404,7 @@ Obtains all keys in this buffer, listed from the most to the least recently acce | Type | Description | | --------- | ------------------------------------------------------------ | -| K [] | All keys in the buffer, listed from the most to the least recently accessed.| +| K [] | All keys in the cache, listed from the most to the least recently accessed.| **Example** @@ -1375,7 +1419,7 @@ let result = pro.keys(); remove(key: K): V | undefined -Removes the specified key and its value from this buffer. +Removes the specified key and its value from this cache. **System capability**: SystemCapability.Utils.Lang @@ -1389,7 +1433,7 @@ Removes the specified key and its value from this buffer. | Type | Description | | ------------------------ | ------------------------------------------------------------ | -| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the cache; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| **Example** @@ -1412,10 +1456,10 @@ Performs subsequent operations after a value is removed. | Name | Type | Mandatory| Description | | -------- | ------- | ---- | ------------------------------------------------------------ | -| isEvict | boolean | No | Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity. | +| isEvict | boolean | Yes | Whether the cache capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity. | | key | K | Yes | Key removed. | | value | V | Yes | Value removed. | -| newValue | V | No | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| newValue | V | Yes | New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** @@ -1444,28 +1488,29 @@ lru.afterRemoval(false,10,30,null); contains(key: K): boolean -Checks whether this buffer contains the specified key. +Checks whether this cache contains the specified key. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description | -| ------ | ---- | ---- | ---------------- | -| key | K | Yes | Key to check.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| key | K | Yes | Key to check.| **Return value** | Type | Description | | ------- | ------------------------------------------ | -| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| +| boolean | Returns **true** if the cache contains the specified key; returns **false** otherwise.| **Example** ```js let pro = new util.LRUCache(); pro.put(2,10); -let result = pro.contains(20); +let obj = {1:"key"}; +let result = pro.contains(obj); ``` @@ -1541,1004 +1586,1044 @@ pro.put(2,10); let result = pro[Symbol.iterator](); ``` -## LruBuffer(deprecated) +## ScopeComparable8+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. +The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. -### Attributes +**System capability**: SystemCapability.Utils.Lang + +### compareTo8+ + +compareTo(other: ScopeComparable): boolean; + +Compares two values and returns a Boolean value. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| length | number | Yes| No| Total number of values in this buffer.| +**Parameters** -**Example** - ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(1,8); - let result = pro.length; - ``` +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | -------------- | +| other | [ScopeComparable](#scopecomparable8) | Yes | The other value to be compared with the current value.| -### constructor(deprecated) +**Return value** -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +| Type| Description | +| ---- | ------------------ | +| boolean | If the current value is greater than or equal to the input value, **true** is returned. Otherwise, **false** is returned.| -constructor(capacity?: number) +**Example** -A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. +Create a class to implement the **compareTo** method. The **Temperature** class is used as an example in the following sample code. -**System capability**: SystemCapability.Utils.Lang +```js +class Temperature{ + constructor(value){ + // If TS is used for development, add the following code: + // private readonly _temp: Temperature; + this._temp = value; + } + compareTo(value){ + return this._temp >= value.getTemp(); + } + getTemp(){ + return this._temp; + } + toString(){ + return this._temp.toString(); + } +} +``` -**Parameters** +## ScopeType8+ -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| capacity | number | No| Capacity of the **LruBuffer** to create.| +Defines the type of values in a **Scope** object. -**Example** - ```js - let lrubuffer= new util.LruBuffer(); - ``` +**System capability**: SystemCapability.Utils.Lang -### updateCapacity(deprecated) +| Type| Description| +| -------- | -------- | +| number | The value type is a number.| +| [ScopeComparable](#scopecomparable8) | The value type is ScopeComparable.| -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. +## ScopeHelper9+ -updateCapacity(newCapacity: number): void +### constructor9+ -Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +A constructor used to create a **ScopeHelper** object with the specified upper and lower limits. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| newCapacity | number | Yes| New capacity of the **LruBuffer**.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit of the **Scope** object.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit of the **Scope** object.| **Example** + ```js - let pro = new util.LruBuffer(); - let result = pro.updateCapacity(100); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); ``` -### toString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +### toString9+ toString(): string -Obtains the string representation of this **LruBuffer** object. +Obtains a string representation that contains this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| string | String representation of this **LruBuffer** object.| +| Type | Description | +| ------ | -------------------------------------- | +| string | String representation containing the **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - pro.remove(20); - let result = pro.toString(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.toString(); ``` -### getCapacity(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. +### intersect9+ -getCapacity(): number +intersect(range: ScopeHelper): ScopeHelper -Obtains the capacity of this buffer. +Obtains the intersection of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Capacity of this buffer.| +| Type | Description | +| ------------------------------ | ------------------------------ | +| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - let result = pro.getCapacity(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +range.intersect(rangeFir); ``` -### clear(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. +### intersect9+ -clear(): void +intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper -Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. +Obtains the intersection of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| + +**Return value** + +| Type | Description | +| ---------------------------- | ---------------------------------------- | +| [ScopeHelper](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| + **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.length; - pro.clear(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.intersect(tempMiDF, tempMidS); ``` -### getCreateCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. +### getUpper9+ -getCreateCount(): number +getUpper(): ScopeType -Obtains the number of return values for **createDefault()**. +Obtains the upper limit of this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of return values for **createDefault()**.| +| Type | Description | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(1,8); - let result = pro.getCreateCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getUpper(); ``` -### getMissCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. +### getLower9+ -getMissCount(): number +getLower(): ScopeType -Obtains the number of times that the queried values are mismatched. +Obtains the lower limit of this **Scope**. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of times that the queried values are mismatched.| +| Type | Description | +| ------------------------ | ---------------------- | +| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMissCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.getLower(); ``` -### getRemovalCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. +### expand9+ -getRemovalCount(): number +expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper -Obtains the number of removals from this buffer. +Obtains the union set of this **Scope** and the given lower and upper limits. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------ | ---- | ---------------- | +| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of removals from the buffer.| +| Type | Description | +| ---------------------------- | ------------------------------------ | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.updateCapacity(2); - pro.put(50,22); - let result = pro.getRemovalCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF, tempMidS); ``` -### getMatchCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. +### expand9+ -getMatchCount(): number +expand(range: ScopeHelper): ScopeHelper -Obtains the number of times that the queried values are matched. +Obtains the union set of this **Scope** and the given **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of times that the queried values are matched.| +| Type | Description | +| ---------------------------- | ---------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.get(2); - let result = pro.getMatchCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let tempMidS = new Temperature(39); +let range = new util.ScopeHelper(tempLower, tempUpper); +let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); +let result = range.expand(rangeFir); ``` -### getPutCount(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. +### expand9+ -getPutCount(): number +expand(value: ScopeType): ScopeHelper -Obtains the number of additions to this buffer. +Obtains the union set of this **Scope** and the given value. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| number | Number of additions to the buffer.| +| Type | Description | +| ---------------------------- | -------------------------------- | +| [ScopeHelper](#scopehelper9) | Union set of this **Scope** and the given value.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.getPutCount(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.expand(tempMiDF); ``` -### isEmpty(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. +### contains9+ -isEmpty(): boolean +contains(value: ScopeType): boolean -Checks whether this buffer is empty. +Checks whether a value is within this **Scope**. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | ---------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| + **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the buffer does not contain any value.| +| Type | Description | +| ------- | --------------------------------------------------- | +| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.isEmpty(); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +range.contains(tempMiDF); ``` -### get(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [get9+](#get9) instead. +### contains9+ -get(key: K): V | undefined +contains(range: ScopeHelper): boolean -Obtains the value of the specified key. +Checks whether a range is within this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key based on which the value is queried.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------- | ---- | ------------------ | +| range | [ScopeHelper](#scopehelper9) | Yes | **Scope** specified.| **Return value** -| Type| Description| -| -------- | -------- | -| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| +| Type | Description | +| ------- | ----------------------------------------------------- | +| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.get(2); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let range = new util.ScopeHelper(tempLower, tempUpper); +let tempLess = new Temperature(20); +let tempMore = new Temperature(45); +let rangeSec = new util.ScopeHelper(tempLess, tempMore); +let result = range.contains(rangeSec); ``` -### put(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [put9+](#put9) instead. +### clamp9+ -put(key: K,value: V): V +clamp(value: ScopeType): ScopeType -Adds a key-value pair to this buffer. +Limits a value to this **Scope**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key of the key-value pair to add.| -| value | V | Yes| Value of the key-value pair to add.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------ | ---- | -------------- | +| value | [ScopeType](#scopetype8) | Yes | Value specified.| **Return value** -| Type| Description| -| -------- | -------- | -| V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | +| Type | Description | +| ------------------------ | ------------------------------------------------------------ | +| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** + ```js - let pro = new util.LruBuffer(); - let result = pro.put(2,10); +let tempLower = new Temperature(30); +let tempUpper = new Temperature(40); +let tempMiDF = new Temperature(35); +let range = new util.ScopeHelper(tempLower, tempUpper); +let result = range.clamp(tempMiDF); ``` -### values(deprecated) +## Base64Helper9+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [values9+](#values9) instead. +### constructor9+ -values(): V[] +constructor() -Obtains all values in this buffer, listed from the most to the least recently accessed. +A constructor used to create a **Base64Helper** instance. **System capability**: SystemCapability.Utils.Lang -**Return value** - -| Type| Description| -| -------- | -------- | -| V [] | All values in the buffer, listed from the most to the least recently accessed.| - **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - pro.put(2,"anhu"); - pro.put("afaf","grfb"); - let result = pro.values(); +let base64 = new util.Base64Helper(); ``` -### keys(deprecated) - -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. +### encodeSync9+ -keys(): K[] +encodeSync(src: Uint8Array): Uint8Array -Obtains all keys in this buffer, listed from the most to the least recently accessed. +Encodes the input content. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | Yes | Uint8Array to encode.| + **Return value** -| Type| Description| -| -------- | -------- | -| K [] | All keys in the buffer, listed from the most to the least recently accessed.| +| Type | Description | +| ---------- | ----------------------------- | +| Uint8Array | Uint8Array encoded.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.keys(); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeSync(array); ``` -### remove(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. +### encodeToStringSync9+ -remove(key: K): V | undefined +encodeToStringSync(src: Uint8Array): string -Removes the specified key and its value from this buffer. +Encodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key to remove.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ------------------- | +| src | Uint8Array | Yes | Uint8Array to encode.| **Return value** -| Type| Description| -| -------- | -------- | -| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| +| Type | Description | +| ------ | -------------------- | +| string | String encoded from the Uint8Array.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.remove(20); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let result = that.encodeToStringSync(array); ``` -### afterRemoval(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. +### decodeSync9+ -afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void +decodeSync(src: Uint8Array | string): Uint8Array -Performs subsequent operations after a value is removed. +Decodes the input content. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isEvict | boolean | No| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| -| key | K | Yes| Key removed.| -| value | V | Yes| Value removed.| -| newValue | V | No| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ----------------------------- | +| src | Uint8Array \| string | Yes | Uint8Array or string to decode.| + +**Return value** + +| Type | Description | +| ---------- | ----------------------------- | +| Uint8Array | Uint8Array decoded.| **Example** + ```js - let arr = []; - class ChildLruBuffer extends util.LruBuffer - { - constructor() - { - super(); - } - afterRemoval(isEvict, key, value, newValue) - { - if (isEvict === false) - { - arr = [key, value, newValue]; - } - } - } - let lru = new ChildLruBuffer(); - lru.afterRemoval(false,10,30,null); +let that = new util.Base64Helper(); +let buff = 'czEz'; +let result = that.decodeSync(buff); ``` -### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +### encode9+ -contains(key: K): boolean +encode(src: Uint8Array): Promise<Uint8Array> -Checks whether this buffer contains the specified key. +Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key to check.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| +| Type | Description | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.contains(20); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +let rarray = new Uint8Array([99,122,69,122]); +that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) ``` -### createDefault(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. +### encodeToString9+ -createDefault(key: K): V +encodeToString(src: Uint8Array): Promise<string> -Creates a value if the value of the specified key is not available. +Encodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | K | Yes| Key of which the value is missing.| +| Name| Type | Mandatory| Description | +| ------ | ---------- | ---- | ----------------------- | +| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| **Return value** -| Type| Description| -| -------- | -------- | -| V | Value of the key.| +| Type | Description | +| --------------------- | ------------------------ | +| Promise<string> | String obtained after asynchronous encoding.| **Example** + ```js - let pro = new util.LruBuffer(); - let result = pro.createDefault(50); +let that = new util.Base64Helper(); +let array = new Uint8Array([115,49,51]); +that.encodeToString(array).then(val=>{ + console.log(val) +}) ``` -### entries(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. +### decode9+ -entries(): IterableIterator<[K,V]> +decode(src: Uint8Array | string): Promise<Uint8Array> -Obtains a new iterator object that contains all key-value pairs in this object. +Decodes the input content asynchronously. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | --------------------------------- | +| src | Uint8Array \| string | Yes | Uint8Array or string to decode asynchronously.| + **Return value** -| Type| Description| -| -------- | -------- | -| [K, V] | Iterable array.| +| Type | Description | +| ------------------------- | --------------------------------- | +| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro.entries(); +let that = new util.Base64Helper(); +let array = new Uint8Array([99,122,69,122]); +let rarray = new Uint8Array([115,49,51]); +that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } +}) ``` -### [Symbol.iterator](deprecated) +## types8+ -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. +### constructor8+ -[Symbol.iterator]\(): IterableIterator<[K, V]> +constructor() -Obtains a two-dimensional array in key-value pairs. +A constructor used to create a **Types** object. **System capability**: SystemCapability.Utils.Lang +**Example** + + ```js + let type = new util.types(); + ``` + + +### isAnyArrayBuffer8+ + +isAnyArrayBuffer(value: Object): boolean + +Checks whether the input value is of the **ArrayBuffer** type. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [K, V] | Two-dimensional array in key-value pairs.| +| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** + ```js - let pro = new util.LruBuffer(); - pro.put(2,10); - let result = pro[Symbol.iterator](); + let that = new util.types(); + let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); ``` -### ScopeType8+ -Defines the type of values in a **Scope** object. The value type can be **ScopeComparable** or **number**. +### isArrayBufferView8+ -The values of the **ScopeComparable** type are used to implement the **compareTo** method. Therefore, ensure that the input parameters are comparable. -```js -interface ScopeComparable{ - compareTo(other: ScopeComparable): boolean; -} -type ScopeType = ScopeComparable | number; -``` +isArrayBufferView(value: Object): boolean +Checks whether the input value is of the **ArrayBufferView** type. -Create a class to implement the **compareTo** method. In the subsequent sample code, **Temperature** is used as an example of the [ScopeType](#scopetype8) object. +**ArrayBufferView** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. +**System capability**: SystemCapability.Utils.Lang -Example -```js -class Temperature{ - constructor(value){ - // If TS is used for development, add the following code: - // private readonly _temp: Temperature; - this._temp = value; - } - compareTo(value){ - return this._temp >= value.getTemp(); - } - getTemp(){ - return this._temp; - } - toString(){ - return this._temp.toString(); - } -} -``` +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| -## ScopeHelper9+ +**Return value** -### constructor9+ +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| -constructor(lowerObj: ScopeType, upperObj: ScopeType) +**Example** -A constructor used to create a **ScopeHelper** object with the specified upper and lower limits. + ```js + let that = new util.types(); + let result = that.isArrayBufferView(new Int8Array([])); + ``` + + +### isArgumentsObject8+ + +isArgumentsObject(value: Object): boolean + +Checks whether the input value is of the **arguments** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit of the **Scope** object.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit of the **Scope** object.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); + let that = new util.types(); + function foo() { + var result = that.isArgumentsObject(arguments); + } + let f = foo(); ``` -### toString9+ +### isArrayBuffer8+ -toString(): string +isArrayBuffer(value: Object): boolean -Obtains a string representation that contains this **Scope**. +Checks whether the input value is of the **ArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------ | -------------------------------------- | -| string | String representation containing the **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.toString(); + let that = new util.types(); + let result = that.isArrayBuffer(new ArrayBuffer(0)); ``` -### intersect9+ +### isAsyncFunction8+ -intersect(range: ScopeHelper): ScopeHelper +isAsyncFunction(value: Object): boolean -Obtains the intersection of this **Scope** and the given **Scope**. +Checks whether the input value is an asynchronous function. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------------ | ------------------------------ | -| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); -range.intersect(rangeFir ); + let that = new util.types(); + let result = that.isAsyncFunction(async function foo() {}); ``` -### intersect9+ +### isBooleanObject8+ -intersect(lowerObj:ScopeType,upperObj:ScopeType):ScopeHelper +isBooleanObject(value: Object): boolean -Obtains the intersection of this **Scope** and the given lower and upper limits. +Checks whether the input value is of the **Boolean** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------------ | ---------------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Intersection of this **Scope** and the given lower and upper limits.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.intersect(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isBooleanObject(new Boolean(true)); ``` -### getUpper9+ +### isBoxedPrimitive8+ -getUpper(): ScopeType +isBoxedPrimitive(value: Object): boolean -Obtains the upper limit of this **Scope**. +Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------------------------ | ---------------------- | -| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.getUpper(); + let that = new util.types(); + let result = that.isBoxedPrimitive(new Boolean(false)); ``` -### getLower9+ +### isDataView8+ -getLower(): ScopeType +isDataView(value: Object): boolean -Obtains the lower limit of this **Scope**. +Checks whether the input value is of the **DataView** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** -| Type | Description | -| ------------------------ | ---------------------- | -| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.getLower(); + let that = new util.types(); + const ab = new ArrayBuffer(20); + let result = that.isDataView(new DataView(ab)); ``` -### expand9+ +### isDate8+ -expand(lowerObj: ScopeType,upperObj: ScopeType): ScopeHelper +isDate(value: Object): boolean -Obtains the union set of this **Scope** and the given lower and upper limits. +Checks whether the input value is of the **Date** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------ | ---- | ---------------- | -| lowerObj | [ScopeType](#scopetype8) | Yes | Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes | Upper limit.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------------ | ------------------------------------ | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given lower and upper limits.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.expand(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isDate(new Date()); ``` -### expand9+ +### isExternal8+ -expand(range: ScopeHelper): ScopeHelper +isExternal(value: Object): boolean -Obtains the union set of this **Scope** and the given **Scope**. +Checks whether the input value is of the **native external** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------------ | ---------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let tempMidS = new Temperature(39); -let range = new util.ScopeHelper(tempLower, tempUpper); -let rangeFir = new util.ScopeHelper(tempMiDF, tempMidS); -let result = range.expand(rangeFir); + let that = new util.types(); + let result = that.isExternal(true); ``` -### expand9+ +### isFloat32Array8+ -expand(value: ScopeType): ScopeHelper +isFloat32Array(value: Object): boolean -Obtains the union set of this **Scope** and the given value. +Checks whether the input value is of the **Float32Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | ---------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------------ | -------------------------------- | -| [ScopeHelper9+](#scopehelper9) | Union set of this **Scope** and the given value.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.expand(tempMiDF); + let that = new util.types(); + let result = that.isFloat32Array(new Float32Array()); ``` -### contains9+ +### isFloat64Array8+ -contains(value: ScopeType): boolean +isFloat64Array(value: Object): boolean -Checks whether a value is within this **Scope**. +Checks whether the input value is of the **Float64Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | ---------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------- | --------------------------------------------------- | -| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -range.contains(tempMiDF); + let that = new util.types(); + let result = that.isFloat64Array(new Float64Array()); ``` -### contains9+ +### isGeneratorFunction8+ -contains(range: ScopeHelper): boolean +isGeneratorFunction(value: Object): boolean -Checks whether a range is within this **Scope**. +Checks whether the input value is a generator function. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ------------------ | -| range | [ScopeHelper9+](#scopehelper9) | Yes | **Scope** specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------- | ----------------------------------------------------- | -| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let range = new util.ScopeHelper(tempLower, tempUpper); -let tempLess = new Temperature(20); -let tempMore = new Temperature(45); -let rangeSec = new util.ScopeHelper(tempLess, tempMore); -let result = range.contains(rangeSec); + let that = new util.types(); + let result = that.isGeneratorFunction(function* foo() {}); ``` -### clamp9+ +### isGeneratorObject8+ -clamp(value: ScopeType): ScopeType +isGeneratorObject(value: Object): boolean -Limits a value to this **Scope**. +Checks whether the input value is a generator object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------ | ---- | -------------- | -| value | [ScopeType](#scopetype8) | Yes | Value specified.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------ | ------------------------------------------------------------ | -| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| **Example** ```js -let tempLower = new Temperature(30); -let tempUpper = new Temperature(40); -let tempMiDF = new Temperature(35); -let range = new util.ScopeHelper(tempLower, tempUpper); -let result = range.clamp(tempMiDF); + let that = new util.types(); + function* foo() {} + const generator = foo(); + let result = that.isGeneratorObject(generator); ``` -## Scope(deprecated) - -> **NOTE** -> -> This class is deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. - -### constructor(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +### isInt8Array8+ -constructor(lowerObj: ScopeType, upperObj: ScopeType) +isInt8Array(value: Object): boolean -A constructor used to create a **Scope** object with the specified upper and lower limits. +Checks whether the input value is of the **Int8Array** type. **System capability**: SystemCapability.Utils.Lang @@ -2546,51 +2631,55 @@ A constructor used to create a **Scope** object with the specified upper and low | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit of the **Scope** object.| +| value | Object | Yes| Object to check.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); + let that = new util.types(); + let result = that.isInt8Array(new Int8Array([])); ``` -### toString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. +### isInt16Array8+ -toString(): string +isInt16Array(value: Object): boolean -Obtains a string representation that contains this **Scope**. +Checks whether the input value is of the **Int16Array** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| string | String representation containing the **Scope**.| +| boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.toString(); + let that = new util.types(); + let result = that.isInt16Array(new Int16Array([])); ``` -### intersect(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +### isInt32Array8+ -intersect(range: Scope): Scope +isInt32Array(value: Object): boolean -Obtains the intersection of this **Scope** and the given **Scope**. +Checks whether the input value is of the **Int32Array** type. **System capability**: SystemCapability.Utils.Lang @@ -2598,35 +2687,27 @@ Obtains the intersection of this **Scope** and the given **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given **Scope**.| +| boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let rangeFir = new util.Scope(tempMiDF, tempMidS); - range.intersect(rangeFir ); + let that = new util.types(); + let result = that.isInt32Array(new Int32Array([])); ``` -### intersect(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. +### isMap8+ -intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope +isMap(value: Object): boolean -Obtains the intersection of this **Scope** and the given lower and upper limits. +Checks whether the input value is of the **Map** type. **System capability**: SystemCapability.Utils.Lang @@ -2634,86 +2715,85 @@ Obtains the intersection of this **Scope** and the given lower and upper limits. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| +| boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let result = range.intersect(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isMap(new Map()); ``` -### getUpper(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. +### isMapIterator8+ -getUpper(): ScopeType +isMapIterator(value: Object): boolean -Obtains the upper limit of this **Scope**. +Checks whether the input value is of the **MapIterator** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| +| boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.getUpper(); + let that = new util.types(); + const map = new Map(); + let result = that.isMapIterator(map.keys()); ``` -### getLower(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. +### isNativeError8+ -getLower(): ScopeType +isNativeError(value: Object): boolean -Obtains the lower limit of this **Scope**. +Checks whether the input value is of the **Error** type. **System capability**: SystemCapability.Utils.Lang +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| + **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| +| boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let result = range.getLower(); + let that = new util.types(); + let result = that.isNativeError(new TypeError()); ``` -### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +### isNumberObject8+ -expand(lowerObj: ScopeType,upperObj: ScopeType): Scope +isNumberObject(value: Object): boolean -Obtains the union set of this **Scope** and the given lower and upper limits. +Checks whether the input value is a number object. **System capability**: SystemCapability.Utils.Lang @@ -2721,35 +2801,27 @@ Obtains the union set of this **Scope** and the given lower and upper limits. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| -| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given lower and upper limits.| +| boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let result = range.expand(tempMiDF, tempMidS); + let that = new util.types(); + let result = that.isNumberObject(new Number(0)); ``` -### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +### isPromise8+ -expand(range: Scope): Scope +isPromise(value: Object): boolean -Obtains the union set of this **Scope** and the given **Scope**. +Checks whether the input value is a promise. **System capability**: SystemCapability.Utils.Lang @@ -2757,34 +2829,27 @@ Obtains the union set of this **Scope** and the given **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| +| boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let tempMidS = new Temperature(39); - let range = new util.Scope(tempLower, tempUpper); - let rangeFir = new util.Scope(tempMiDF, tempMidS); - let result = range.expand(rangeFir); + let that = new util.types(); + let result = that.isPromise(Promise.resolve(1)); ``` -### expand(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. +### isProxy8+ -expand(value: ScopeType): Scope +isProxy(value: Object): boolean -Obtains the union set of this **Scope** and the given value. +Checks whether the input value is a proxy. **System capability**: SystemCapability.Utils.Lang @@ -2792,32 +2857,29 @@ Obtains the union set of this **Scope** and the given value. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| +| boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - let result = range.expand(tempMiDF); + let that = new util.types(); + const target = {}; + const proxy = new Proxy(target, {}); + let result = that.isProxy(proxy); ``` -### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +### isRegExp8+ -contains(value: ScopeType): boolean +isRegExp(value: Object): boolean -Checks whether a value is within this **Scope**. +Checks whether the input value is of the **RegExp** type. **System capability**: SystemCapability.Utils.Lang @@ -2825,32 +2887,27 @@ Checks whether a value is within this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| +| boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| **Example** + ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - range.contains(tempMiDF); + let that = new util.types(); + let result = that.isRegExp(new RegExp('abc')); ``` -### contains(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. +### isSet8+ -contains(range: Scope): boolean +isSet(value: Object): boolean -Checks whether a range is within this **Scope**. +Checks whether the input value is of the **Set** type. **System capability**: SystemCapability.Utils.Lang @@ -2858,35 +2915,27 @@ Checks whether a range is within this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| +| boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| **Example** ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let range = new util.Scope(tempLower, tempUpper); - let tempLess = new Temperature(20); - let tempMore = new Temperature(45); - let rangeSec = new util.Scope(tempLess, tempMore); - let result = range.contains(rangeSec); + let that = new util.types(); + let result = that.isSet(new Set()); ``` -### clamp(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. +### isSetIterator8+ -clamp(value: ScopeType): ScopeType +isSetIterator(value: Object): boolean -Limits a value to this **Scope**. +Checks whether the input value is of the **SetIterator** type. **System capability**: SystemCapability.Utils.Lang @@ -2894,257 +2943,227 @@ Limits a value to this **Scope**. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | [ScopeType](#scopetype8) | Yes| Value specified.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| - -**Example** - ```js - let tempLower = new Temperature(30); - let tempUpper = new Temperature(40); - let tempMiDF = new Temperature(35); - let range = new util.Scope(tempLower, tempUpper); - let result = range.clamp(tempMiDF); - ``` - -## Base64Helper9+ - -### constructor9+ - -constructor() - -A constructor used to create a **Base64Helper** instance. - -**System capability**: SystemCapability.Utils.Lang +| boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| **Example** ```js -let base64 = new util.Base64Helper(); + let that = new util.types(); + const set = new Set(); + let result = that.isSetIterator(set.keys()); ``` -### encodeSync9+ -encodeSync(src: Uint8Array): Uint8Array +### isStringObject8+ -Encodes the input content. +isStringObject(value: Object): boolean + +Checks whether the input value is a string object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------------- | -| src | Uint8Array | Yes | Uint8Array to encode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------- | ----------------------------- | -| Uint8Array | Uint8Array encoded.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeSync(array); + let that = new util.types(); + let result = that.isStringObject(new String('foo')); ``` -### encodeToStringSync9+ +### isSymbolObjec8+ -encodeToStringSync(src: Uint8Array): string +isSymbolObject(value: Object): boolean -Encodes the input content. +Checks whether the input value is a symbol object. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ------------------- | -| src | Uint8Array | Yes | Uint8Array to encode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------ | -------------------- | -| string | String encoded from the Uint8Array.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let result = that.encodeToStringSync(array); + let that = new util.types(); + const symbols = Symbol('foo'); + let result = that.isSymbolObject(Object(symbols)); ``` -### decodeSync9+ +### isTypedArray8+ -decodeSync(src: Uint8Array | string): Uint8Array +isTypedArray(value: Object): boolean -Decodes the input content. +Checks whether the input value is of the **TypedArray** type. + +**TypedArray** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint16Array**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | ----------------------------- | -| src | Uint8Array \| string | Yes | Uint8Array or string to decode.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ---------- | ----------------------------- | -| Uint8Array | Uint8Array decoded.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let buff = 'czEz'; -let result = that.decodeSync(buff); + let that = new util.types(); + let result = that.isTypedArray(new Float64Array([])); ``` -### encode9+ +### isUint8Array8+ -encode(src: Uint8Array): Promise<Uint8Array> +isUint8Array(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is of the **Uint8Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ----------------------- | -| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------- | --------------------------------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -let rarray = new Uint8Array([99,122,69,122]); -that.encode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } -}) + let that = new util.types(); + let result = that.isUint8Array(new Uint8Array([])); ``` -### encodeToString9+ +### isUint8ClampedArray8+ -encodeToString(src: Uint8Array): Promise<string> +isUint8ClampedArray(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is of the **Uint8ClampedArray** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------- | ---- | ----------------------- | -| src | Uint8Array | Yes | Uint8Array to encode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| --------------------- | ------------------------ | -| Promise<string> | String obtained after asynchronous encoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([115,49,51]); -that.encodeToString(array).then(val=>{ - console.log(val) -}) + let that = new util.types(); + let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); ``` -### decode9+ +### isUint16Array8+ -decode(src: Uint8Array | string): Promise<Uint8Array> +isUint16Array(value: Object): boolean -Decodes the input content asynchronously. +Checks whether the input value is of the **Uint16Array** type. **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ------------------------------ | ---- | --------------------------------- | -| src | Uint8Array \| string | Yes | Uint8Array or string to decode asynchronously.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| **Return value** -| Type | Description | -| ------------------------- | --------------------------------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| **Example** ```js -let that = new util.Base64Helper(); -let array = new Uint8Array([99,122,69,122]); -let rarray = new Uint8Array([115,49,51]); -that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } -}) + let that = new util.types(); + let result = that.isUint16Array(new Uint16Array([])); ``` -## Base64(deprecated) +### isUint32Array8+ -> **NOTE** -> -> This class is deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. +isUint32Array(value: Object): boolean -### constructor(deprecated) +Checks whether the input value is of the **Uint32Array** type. -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. +**System capability**: SystemCapability.Utils.Lang -constructor() +**Parameters** -A constructor used to create a **Base64** object. +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | Object | Yes| Object to check.| -**System capability**: SystemCapability.Utils.Lang +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| **Example** + ```js - let base64 = new util.Base64(); + let that = new util.types(); + let result = that.isUint32Array(new Uint32Array([])); ``` -### encodeSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. +### isWeakMap8+ -encodeSync(src: Uint8Array): Uint8Array +isWeakMap(value: Object): boolean -Encodes the input content. +Checks whether the input value is of the **WeakMap** type. **System capability**: SystemCapability.Utils.Lang @@ -3152,31 +3171,27 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Uint8Array | Uint8Array encoded.| +| boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| **Example** ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let result = that.encodeSync(array); + let that = new util.types(); + let result = that.isWeakMap(new WeakMap()); ``` -### encodeToStringSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. +### isWeakSet8+ -encodeToStringSync(src: Uint8Array): string +isWeakSet(value: Object): boolean -Encodes the input content. +Checks whether the input value is of the **WeakSet** type. **System capability**: SystemCapability.Utils.Lang @@ -3184,30 +3199,27 @@ Encodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| string | String encoded from the Uint8Array.| +| boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| **Example** + ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let result = that.encodeToStringSync(array); + let that = new util.types(); + let result = that.isWeakSet(new WeakSet()); ``` -### decodeSync(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. +### isBigInt64Array8+ -decodeSync(src: Uint8Array | string): Uint8Array +isBigInt64Array(value: Object): boolean -Decodes the input content. +Checks whether the input value is of the **BigInt64Array** type. **System capability**: SystemCapability.Utils.Lang @@ -3215,30 +3227,27 @@ Decodes the input content. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array \| string | Yes| Uint8Array or string to decode.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Uint8Array | Uint8Array decoded.| +| boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| **Example** + ```js - let that = new util.Base64(); - let buff = 'czEz'; - let result = that.decodeSync(buff); + let that = new util.types(); + let result = that.isBigInt64Array(new BigInt64Array([])); ``` -### encode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. +### isBigUint64Array8+ -encode(src: Uint8Array): Promise<Uint8Array> +isBigUint64Array(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is of the **BigUint64Array** type. **System capability**: SystemCapability.Utils.Lang @@ -3246,35 +3255,27 @@ Encodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| +| boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| **Example** + ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - let rarray = new Uint8Array([99,122,69,122]); - that.encode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } - }) + let that = new util.types(); + let result = that.isBigUint64Array(new BigUint64Array([])); ``` -### encodeToString(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. +### isModuleNamespaceObject8+ -encodeToString(src: Uint8Array): Promise<string> +isModuleNamespaceObject(value: Object): boolean -Encodes the input content asynchronously. +Checks whether the input value is a module namespace object. **System capability**: SystemCapability.Utils.Lang @@ -3282,32 +3283,28 @@ Encodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<string> | String obtained after asynchronous encoding.| +| boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| **Example** + ```js - let that = new util.Base64(); - let array = new Uint8Array([115,49,51]); - that.encodeToString(array).then(val=>{ - console.log(val) - }) + import url from '@ohos.url' + let that = new util.types(); + let result = that.isModuleNamespaceObject(url); ``` -### decode(deprecated) -> **NOTE** -> -> This API is deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. +### isSharedArrayBuffer8+ -decode(src: Uint8Array | string): Promise<Uint8Array> +isSharedArrayBuffer(value: Object): boolean -Decodes the input content asynchronously. +Checks whether the input value is of the **SharedArrayBuffer** type. **System capability**: SystemCapability.Utils.Lang @@ -3315,48 +3312,53 @@ Decodes the input content asynchronously. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| +| value | Object | Yes| Object to check.| **Return value** | Type| Description| | -------- | -------- | -| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| +| boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| **Example** + ```js - let that = new util.Base64(); - let array = new Uint8Array([99,122,69,122]); - let rarray = new Uint8Array([115,49,51]); - that.decode(array).then(val=>{ - for (var i = 0; i < rarray.length; i++) { - console.log(val[i].toString()) - } - }) + let that = new util.types(); + let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); ``` -## types8+ - - -### constructor8+ +## LruBuffer(deprecated) -constructor() +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [LRUCache9+](#lrucache9) instead. -A constructor used to create a **Types** object. +### Attributes **System capability**: SystemCapability.Utils.Lang +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Total number of values in this buffer.| + **Example** + ```js - let type = new util.types(); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(1,8); + let result = pro.length; ``` +### constructor(deprecated) -### isAnyArrayBuffer8+ +constructor(capacity?: number) -isAnyArrayBuffer(value: Object): boolean +A constructor used to create a **LruBuffer** instance. The default capacity of the buffer is 64. -Checks whether the input value is of the **ArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3364,28 +3366,23 @@ Checks whether the input value is of the **ArrayBuffer** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| +| capacity | number | No| Capacity of the **LruBuffer** to create.| **Example** + ```js - let that = new util.types(); - let result = that.isAnyArrayBuffer(new ArrayBuffer(0)); + let lrubuffer= new util.LruBuffer(); ``` +### updateCapacity(deprecated) -### isArrayBufferView8+ - -isArrayBufferView(value: Object): boolean +updateCapacity(newCapacity: number): void -Checks whether the input value is of the **ArrayBufferView** type. +Changes the **LruBuffer** capacity. If the new capacity is less than or equal to **0**, an exception will be thrown. -**ArrayBufferView** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [updateCapacity9+](#updatecapacity9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3393,246 +3390,257 @@ Checks whether the input value is of the **ArrayBufferView** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBufferView** type; returns **false** otherwise.| +| newCapacity | number | Yes| New capacity of the **LruBuffer**.| **Example** + ```js - let that = new util.types(); - let result = that.isArrayBufferView(new Int8Array([])); + let pro = new util.LruBuffer(); + let result = pro.updateCapacity(100); ``` +### toString(deprecated) -### isArgumentsObject8+ +toString(): string -isArgumentsObject(value: Object): boolean +Obtains the string representation of this **LruBuffer** object. -Checks whether the input value is of the **arguments** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **arguments** type; returns **false** otherwise.| +| string | String representation of this **LruBuffer** object.| **Example** + ```js - let that = new util.types(); - function foo() { - var result = that.isArgumentsObject(arguments); - } - let f = foo(); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + pro.remove(20); + let result = pro.toString(); ``` +### getCapacity(deprecated) -### isArrayBuffer8+ +getCapacity(): number -isArrayBuffer(value: Object): boolean +Obtains the capacity of this buffer. -Checks whether the input value is of the **ArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCapacity9+](#getcapacity9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **ArrayBuffer** type; returns **false** otherwise.| +| number | Capacity of this buffer.| **Example** ```js - let that = new util.types(); - let result = that.isArrayBuffer(new ArrayBuffer(0)); + let pro = new util.LruBuffer(); + let result = pro.getCapacity(); ``` +### clear(deprecated) -### isAsyncFunction8+ +clear(): void -isAsyncFunction(value: Object): boolean +Clears key-value pairs from this buffer. The **afterRemoval()** method will be called to perform subsequent operations. -Checks whether the input value is an asynchronous function. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clear9+](#clear9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** +**Example** + + ```js + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.length; + pro.clear(); + ``` + +### getCreateCount(deprecated) + +getCreateCount(): number + +Obtains the number of return values for **createDefault()**. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getCreateCount9+](#getcreatecount9) instead. -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +**System capability**: SystemCapability.Utils.Lang **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is an asynchronous function; returns **false** otherwise.| +| number | Number of return values for **createDefault()**.| **Example** + ```js - let that = new util.types(); - let result = that.isAsyncFunction(async function foo() {}); + let pro = new util.LruBuffer(); + pro.put(1,8); + let result = pro.getCreateCount(); ``` +### getMissCount(deprecated) -### isBooleanObject8+ +getMissCount(): number -isBooleanObject(value: Object): boolean +Obtains the number of times that the queried values are mismatched. -Checks whether the input value is of the **Boolean** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMissCount9+](#getmisscount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Boolean** type; returns **false** otherwise.| +| number | Number of times that the queried values are mismatched.| **Example** + ```js - let that = new util.types(); - let result = that.isBooleanObject(new Boolean(true)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMissCount(); ``` +### getRemovalCount(deprecated) -### isBoxedPrimitive8+ +getRemovalCount(): number -isBoxedPrimitive(value: Object): boolean +Obtains the number of removals from this buffer. -Checks whether the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getRemovalCount9+](#getremovalcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Boolean**, **Number**, **String**, or **Symbol** type; returns **false** otherwise.| +| number | Number of removals from the buffer.| **Example** + ```js - let that = new util.types(); - let result = that.isBoxedPrimitive(new Boolean(false)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.updateCapacity(2); + pro.put(50,22); + let result = pro.getRemovalCount(); ``` +### getMatchCount(deprecated) -### isDataView8+ +getMatchCount(): number -isDataView(value: Object): boolean +Obtains the number of times that the queried values are matched. -Checks whether the input value is of the **DataView** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getMatchCount9+](#getmatchcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **DataView** type; returns **false** otherwise.| +| number | Number of times that the queried values are matched.| **Example** + ```js - let that = new util.types(); - const ab = new ArrayBuffer(20); - let result = that.isDataView(new DataView(ab)); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.get(2); + let result = pro.getMatchCount(); ``` +### getPutCount(deprecated) -### isDate8+ +getPutCount(): number -isDate(value: Object): boolean +Obtains the number of additions to this buffer. -Checks whether the input value is of the **Date** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getPutCount9+](#getputcount9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Date** type; returns **false** otherwise.| +| number | Number of additions to the buffer.| **Example** + ```js - let that = new util.types(); - let result = that.isDate(new Date()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.getPutCount(); ``` +### isEmpty(deprecated) -### isExternal8+ +isEmpty(): boolean -isExternal(value: Object): boolean +Checks whether this buffer is empty. -Checks whether the input value is of the **native external** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [isEmpty9+](#isempty9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **native external** type; returns **false** otherwise.| +| boolean | Returns **true** if the buffer does not contain any value.| **Example** + ```js - let that = new util.types(); - let result = that.isExternal(true); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.isEmpty(); ``` +### get(deprecated) -### isFloat32Array8+ +get(key: K): V | undefined -isFloat32Array(value: Object): boolean +Obtains the value of the specified key. -Checks whether the input value is of the **Float32Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [get9+](#get9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3640,26 +3648,31 @@ Checks whether the input value is of the **Float32Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key based on which the value is queried.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Float32Array** type; returns **false** otherwise.| +| V \| undefined | Returns the value of the key if a match is found in the buffer; returns **undefined** otherwise.| **Example** + ```js - let that = new util.types(); - let result = that.isFloat32Array(new Float32Array()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.get(2); ``` +### put(deprecated) -### isFloat64Array8+ +put(key: K,value: V): V -isFloat64Array(value: Object): boolean +Adds a key-value pair to this buffer. -Checks whether the input value is of the **Float64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [put9+](#put9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3667,82 +3680,84 @@ Checks whether the input value is of the **Float64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key of the key-value pair to add.| +| value | V | Yes| Value of the key-value pair to add.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Float64Array** type; returns **false** otherwise.| +| V | Returns the existing value if the key already exists; returns the value added otherwise. If the key or value is null, an exception will be thrown. | **Example** + ```js - let that = new util.types(); - let result = that.isFloat64Array(new Float64Array()); + let pro = new util.LruBuffer(); + let result = pro.put(2,10); ``` +### values(deprecated) -### isGeneratorFunction8+ +values(): V[] -isGeneratorFunction(value: Object): boolean +Obtains all values in this buffer, listed from the most to the least recently accessed. -Checks whether the input value is a generator function. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [values9+](#values9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a generator function; returns **false** otherwise.| +| V [] | All values in the buffer, listed from the most to the least recently accessed.| **Example** + ```js - let that = new util.types(); - let result = that.isGeneratorFunction(function* foo() {}); + let pro = new util.LruBuffer(); + pro.put(2,10); + pro.put(2,"anhu"); + pro.put("afaf","grfb"); + let result = pro.values(); ``` +### keys(deprecated) -### isGeneratorObject8+ +keys(): K[] -isGeneratorObject(value: Object): boolean +Obtains all keys in this buffer, listed from the most to the least recently accessed. -Checks whether the input value is a generator object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [keys9+](#keys9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a generator object; returns **false** otherwise.| +| K [] | All keys in the buffer, listed from the most to the least recently accessed.| **Example** ```js - let that = new util.types(); - function* foo() {} - const generator = foo(); - let result = that.isGeneratorObject(generator); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.keys(); ``` +### remove(deprecated) -### isInt8Array8+ +remove(key: K): V | undefined -isInt8Array(value: Object): boolean +Removes the specified key and its value from this buffer. -Checks whether the input value is of the **Int8Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [remove9+](#remove9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3750,26 +3765,30 @@ Checks whether the input value is of the **Int8Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key to remove.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int8Array** type; returns **false** otherwise.| +| V \| undefined | Returns an **Optional** object containing the removed key-value pair if the key exists in the buffer; returns an empty **Optional** object otherwise. If the key is null, an exception will be thrown.| **Example** ```js - let that = new util.types(); - let result = that.isInt8Array(new Int8Array([])); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.remove(20); ``` +### afterRemoval(deprecated) -### isInt16Array8+ +afterRemoval(isEvict: boolean,key: K,value: V,newValue: V): void -isInt16Array(value: Object): boolean +Performs subsequent operations after a value is removed. -Checks whether the input value is of the **Int16Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [afterRemoval9+](#afterremoval9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3777,26 +3796,43 @@ Checks whether the input value is of the **Int16Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int16Array** type; returns **false** otherwise.| +| isEvict | boolean | Yes| Whether the buffer capacity is insufficient. If the value is **true**, this method is called due to insufficient capacity.| +| key | K | Yes| Key removed.| +| value | V | Yes| Value removed.| +| newValue | V | Yes| New value for the key if the **put()** method is called and the key to be added already exists. In other cases, this parameter is left blank.| **Example** + ```js - let that = new util.types(); - let result = that.isInt16Array(new Int16Array([])); + let arr = []; + class ChildLruBuffer extends util.LruBuffer + { + constructor() + { + super(); + } + afterRemoval(isEvict, key, value, newValue) + { + if (isEvict === false) + { + arr = [key, value, newValue]; + } + } + } + let lru = new ChildLruBuffer(); + lru.afterRemoval(false,10,30,null); ``` +### contains(deprecated) -### isInt32Array8+ +contains(key: K): boolean -isInt32Array(value: Object): boolean +Checks whether this buffer contains the specified key. -Checks whether the input value is of the **Int32Array** type. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3804,26 +3840,31 @@ Checks whether the input value is of the **Int32Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key to check.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Int32Array** type; returns **false** otherwise.| +| boolean | Returns **true** if the buffer contains the specified key; returns **false** otherwise.| **Example** + ```js - let that = new util.types(); - let result = that.isInt32Array(new Int32Array([])); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.contains(20); ``` +### createDefault(deprecated) -### isMap8+ +createDefault(key: K): V -isMap(value: Object): boolean +Creates a value if the value of the specified key is not available. -Checks whether the input value is of the **Map** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [createDefault9+](#createdefault9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3831,81 +3872,89 @@ Checks whether the input value is of the **Map** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| key | K | Yes| Key of which the value is missing.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Map** type; returns **false** otherwise.| +| V | Value of the key.| **Example** + ```js - let that = new util.types(); - let result = that.isMap(new Map()); + let pro = new util.LruBuffer(); + let result = pro.createDefault(50); ``` +### entries(deprecated) -### isMapIterator8+ +entries(): IterableIterator<[K,V]> -isMapIterator(value: Object): boolean +Obtains a new iterator object that contains all key-value pairs in this object. -Checks whether the input value is of the **MapIterator** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [entries9+](#entries9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **MapIterator** type; returns **false** otherwise.| +| [K, V] | Iterable array.| **Example** + ```js - let that = new util.types(); - const map = new Map(); - let result = that.isMapIterator(map.keys()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro.entries(); ``` +### [Symbol.iterator](deprecated) -### isNativeError8+ +[Symbol.iterator]\(): IterableIterator<[K, V]> -isNativeError(value: Object): boolean +Obtains a two-dimensional array in key-value pairs. -Checks whether the input value is of the **Error** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Symbol.iterator9+](#symboliterator9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Error** type; returns **false** otherwise.| +| [K, V] | Two-dimensional array in key-value pairs.| **Example** + ```js - let that = new util.types(); - let result = that.isNativeError(new TypeError()); + let pro = new util.LruBuffer(); + pro.put(2,10); + let result = pro[Symbol.iterator](); ``` +## Scope(deprecated) -### isNumberObject8+ +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [ScopeHelper9+](#scopehelper9) instead. -isNumberObject(value: Object): boolean +### constructor(deprecated) + +constructor(lowerObj: ScopeType, upperObj: ScopeType) + +A constructor used to create a **Scope** object with the specified upper and lower limits. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. -Checks whether the input value is a number object. **System capability**: SystemCapability.Utils.Lang @@ -3913,53 +3962,52 @@ Checks whether the input value is a number object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is a number object; returns **false** otherwise.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit of the **Scope** object.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit of the **Scope** object.| **Example** ```js - let that = new util.types(); - let result = that.isNumberObject(new Number(0)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); ``` +### toString(deprecated) -### isPromise8+ +toString(): string -isPromise(value: Object): boolean +Obtains a string representation that contains this **Scope**. -Checks whether the input value is a promise. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [toString9+](#tostring9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a promise; returns **false** otherwise.| +| string | String representation containing the **Scope**.| **Example** + ```js - let that = new util.types(); - let result = that.isPromise(Promise.resolve(1)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.toString(); ``` +### intersect(deprecated) -### isProxy8+ +intersect(range: Scope): Scope -isProxy(value: Object): boolean +Obtains the intersection of this **Scope** and the given **Scope**. -Checks whether the input value is a proxy. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3967,28 +4015,35 @@ Checks whether the input value is a proxy. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a proxy; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given **Scope**.| **Example** + ```js - let that = new util.types(); - const target = {}; - const proxy = new Proxy(target, {}); - let result = that.isProxy(proxy); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let rangeFir = new util.Scope(tempMiDF, tempMidS); + range.intersect(rangeFir ); ``` +### intersect(deprecated) -### isRegExp8+ +intersect(lowerObj:ScopeType,upperObj:ScopeType):Scope -isRegExp(value: Object): boolean +Obtains the intersection of this **Scope** and the given lower and upper limits. -Checks whether the input value is of the **RegExp** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [intersect9+](#intersect9) instead. **System capability**: SystemCapability.Utils.Lang @@ -3996,81 +4051,89 @@ Checks whether the input value is of the **RegExp** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **RegExp** type; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Intersection of this **Scope** and the given lower and upper limits.| **Example** + ```js - let that = new util.types(); - let result = that.isRegExp(new RegExp('abc')); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.intersect(tempMiDF, tempMidS); ``` +### getUpper(deprecated) -### isSet8+ +getUpper(): ScopeType -isSet(value: Object): boolean +Obtains the upper limit of this **Scope**. -Checks whether the input value is of the **Set** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getUpper9+](#getupper9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Set** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Upper limit of this **Scope**.| **Example** + ```js - let that = new util.types(); - let result = that.isSet(new Set()); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getUpper(); ``` +### getLower(deprecated) -### isSetIterator8+ +getLower(): ScopeType -isSetIterator(value: Object): boolean +Obtains the lower limit of this **Scope**. -Checks whether the input value is of the **SetIterator** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getLower9+](#getlower9) instead. **System capability**: SystemCapability.Utils.Lang -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| - **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **SetIterator** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Lower limit of this **Scope**.| **Example** + ```js - let that = new util.types(); - const set = new Set(); - let result = that.isSetIterator(set.keys()); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let result = range.getLower(); ``` +### expand(deprecated) -### isStringObject8+ +expand(lowerObj: ScopeType,upperObj: ScopeType): Scope -isStringObject(value: Object): boolean +Obtains the union set of this **Scope** and the given lower and upper limits. -Checks whether the input value is a string object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4078,26 +4141,35 @@ Checks whether the input value is a string object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| lowerObj | [ScopeType](#scopetype8) | Yes| Lower limit.| +| upperObj | [ScopeType](#scopetype8) | Yes| Upper limit.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a string object; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given lower and upper limits.| **Example** + ```js - let that = new util.types(); - let result = that.isStringObject(new String('foo')); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF, tempMidS); ``` +### expand(deprecated) -### isSymbolObjec8+ +expand(range: Scope): Scope -isSymbolObject(value: Object): boolean +Obtains the union set of this **Scope** and the given **Scope**. -Checks whether the input value is a symbol object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4105,29 +4177,35 @@ Checks whether the input value is a symbol object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a symbol object; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given **Scope**.| **Example** + ```js - let that = new util.types(); - const symbols = Symbol('foo'); - let result = that.isSymbolObject(Object(symbols)); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let tempMidS = new Temperature(39); + let range = new util.Scope(tempLower, tempUpper); + let rangeFir = new util.Scope(tempMiDF, tempMidS); + let result = range.expand(rangeFir); ``` +### expand(deprecated) -### isTypedArray8+ - -isTypedArray(value: Object): boolean +expand(value: ScopeType): Scope -Checks whether the input value is of the **TypedArray** type. +Obtains the union set of this **Scope** and the given value. -**TypedArray** is a helper type representing any of the following: **Int8Array**, **Int16Array**, **Int32Array**, **Uint8Array**, **Uint8ClampedArray**, **Uint16Array**, **Uint32Array**, **Float32Array**, **Float64Array**, and **DataView**. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [expand9+](#expand9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4135,26 +4213,33 @@ Checks whether the input value is of the **TypedArray** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **TypedArray** type; returns **false** otherwise.| +| [Scope](#scopedeprecated) | Union set of this **Scope** and the given value.| **Example** + ```js - let that = new util.types(); - let result = that.isTypedArray(new Float64Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.expand(tempMiDF); ``` +### contains(deprecated) -### isUint8Array8+ +contains(value: ScopeType): boolean -isUint8Array(value: Object): boolean +Checks whether a value is within this **Scope**. -Checks whether the input value is of the **Uint8Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4162,26 +4247,33 @@ Checks whether the input value is of the **Uint8Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint8Array** type; returns **false** otherwise.| +| boolean | Returns **true** if the value is within this **Scope**; returns **false** otherwise.| **Example** + ```js - let that = new util.types(); - let result = that.isUint8Array(new Uint8Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + range.contains(tempMiDF); ``` +### contains(deprecated) -### isUint8ClampedArray8+ +contains(range: Scope): boolean -isUint8ClampedArray(value: Object): boolean +Checks whether a range is within this **Scope**. -Checks whether the input value is of the **Uint8ClampedArray** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [contains9+](#contains9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4189,26 +4281,36 @@ Checks whether the input value is of the **Uint8ClampedArray** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| range | [Scope](#scopedeprecated) | Yes| **Scope** specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint8ClampedArray** type; returns **false** otherwise.| +| boolean | Returns **true** if the range is within this **Scope**; returns **false** otherwise.| **Example** + ```js - let that = new util.types(); - let result = that.isUint8ClampedArray(new Uint8ClampedArray([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let range = new util.Scope(tempLower, tempUpper); + let tempLess = new Temperature(20); + let tempMore = new Temperature(45); + let rangeSec = new util.Scope(tempLess, tempMore); + let result = range.contains(rangeSec); ``` +### clamp(deprecated) -### isUint16Array8+ -isUint16Array(value: Object): boolean +clamp(value: ScopeType): ScopeType -Checks whether the input value is of the **Uint16Array** type. +Limits a value to this **Scope**. + +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [clamp9+](#clamp9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4216,53 +4318,58 @@ Checks whether the input value is of the **Uint16Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| value | [ScopeType](#scopetype8) | Yes| Value specified.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint16Array** type; returns **false** otherwise.| +| [ScopeType](#scopetype8) | Returns **lowerObj** if the specified value is less than the lower limit; returns **upperObj** if the specified value is greater than the upper limit; returns the specified value if it is within this **Scope**.| **Example** + ```js - let that = new util.types(); - let result = that.isUint16Array(new Uint16Array([])); + let tempLower = new Temperature(30); + let tempUpper = new Temperature(40); + let tempMiDF = new Temperature(35); + let range = new util.Scope(tempLower, tempUpper); + let result = range.clamp(tempMiDF); ``` -### isUint32Array8+ - -isUint32Array(value: Object): boolean +## Base64(deprecated) -Checks whether the input value is of the **Uint32Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [Base64Helper9+](#base64helper9) instead. -**System capability**: SystemCapability.Utils.Lang +### constructor(deprecated) -**Parameters** +constructor() -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +A constructor used to create a **Base64** object. -**Return value** +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [constructor9+](#constructor9) instead. -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the input value is of the **Uint32Array** type; returns **false** otherwise.| +**System capability**: SystemCapability.Utils.Lang **Example** + ```js - let that = new util.types(); - let result = that.isUint32Array(new Uint32Array([])); + let base64 = new util.Base64(); ``` +### encodeSync(deprecated) -### isWeakMap8+ +encodeSync(src: Uint8Array): Uint8Array -isWeakMap(value: Object): boolean +Encodes the input content. -Checks whether the input value is of the **WeakMap** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeSync9+](#encodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4270,26 +4377,31 @@ Checks whether the input value is of the **WeakMap** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **WeakMap** type; returns **false** otherwise.| +| Uint8Array | Uint8Array encoded.| **Example** + ```js - let that = new util.types(); - let result = that.isWeakMap(new WeakMap()); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeSync(array); ``` +### encodeToStringSync(deprecated) -### isWeakSet8+ +encodeToStringSync(src: Uint8Array): string -isWeakSet(value: Object): boolean +Encodes the input content. -Checks whether the input value is of the **WeakSet** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToStringSync9+](#encodetostringsync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4297,26 +4409,31 @@ Checks whether the input value is of the **WeakSet** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **WeakSet** type; returns **false** otherwise.| +| string | String encoded from the Uint8Array.| **Example** + ```js - let that = new util.types(); - let result = that.isWeakSet(new WeakSet()); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let result = that.encodeToStringSync(array); ``` +### decodeSync(deprecated) -### isBigInt64Array8+ +decodeSync(src: Uint8Array | string): Uint8Array -isBigInt64Array(value: Object): boolean +Decodes the input content. -Checks whether the input value is of the **BigInt64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decodeSync9+](#decodesync9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4324,26 +4441,31 @@ Checks whether the input value is of the **BigInt64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array \| string | Yes| Uint8Array or string to decode.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **BigInt64Array** type; returns **false** otherwise.| +| Uint8Array | Uint8Array decoded.| **Example** + ```js - let that = new util.types(); - let result = that.isBigInt64Array(new BigInt64Array([])); + let that = new util.Base64(); + let buff = 'czEz'; + let result = that.decodeSync(buff); ``` +### encode(deprecated) -### isBigUint64Array8+ +encode(src: Uint8Array): Promise<Uint8Array> -isBigUint64Array(value: Object): boolean +Encodes the input content asynchronously. -Checks whether the input value is of the **BigUint64Array** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encode9+](#encode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4351,26 +4473,36 @@ Checks whether the input value is of the **BigUint64Array** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **BigUint64Array** type; returns **false** otherwise.| +| Promise<Uint8Array> | Uint8Array obtained after asynchronous encoding.| **Example** + ```js - let that = new util.types(); - let result = that.isBigUint64Array(new BigUint64Array([])); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + let rarray = new Uint8Array([99,122,69,122]); + that.encode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } + }) ``` +### encodeToString(deprecated) -### isModuleNamespaceObject8+ +encodeToString(src: Uint8Array): Promise<string> -isModuleNamespaceObject(value: Object): boolean +Encodes the input content asynchronously. -Checks whether the input value is a module namespace object. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [encodeToString9+](#encodetostring9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4378,27 +4510,34 @@ Checks whether the input value is a module namespace object. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array | Yes| Uint8Array to encode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is a module namespace object; returns **false** otherwise.| +| Promise<string> | String obtained after asynchronous encoding.| **Example** + ```js - import url from '@ohos.url' - let that = new util.types(); - let result = that.isModuleNamespaceObject(url); + let that = new util.Base64(); + let array = new Uint8Array([115,49,51]); + that.encodeToString(array).then(val=>{ + console.log(val) + }) ``` +### decode(deprecated) + -### isSharedArrayBuffer8+ +decode(src: Uint8Array | string): Promise<Uint8Array> -isSharedArrayBuffer(value: Object): boolean +Decodes the input content asynchronously. -Checks whether the input value is of the **SharedArrayBuffer** type. +> **NOTE** +> +> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [decode9+](#decode9) instead. **System capability**: SystemCapability.Utils.Lang @@ -4406,17 +4545,25 @@ Checks whether the input value is of the **SharedArrayBuffer** type. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| value | Object | Yes| Object to check.| +| src | Uint8Array \| string | Yes| Uint8Array or string to decode asynchronously.| **Return value** | Type| Description| | -------- | -------- | -| boolean | Returns **true** if the input value is of the **SharedArrayBuffer** type; returns **false** otherwise.| +| Promise<Uint8Array> | Uint8Array obtained after asynchronous decoding.| **Example** + ```js - let that = new util.types(); - let result = that.isSharedArrayBuffer(new SharedArrayBuffer(0)); + let that = new util.Base64(); + let array = new Uint8Array([99,122,69,122]); + let rarray = new Uint8Array([115,49,51]); + that.decode(array).then(val=>{ + for (var i = 0; i < rarray.length; i++) { + console.log(val[i].toString()) + } + }) ``` + diff --git a/en/application-dev/reference/apis/js-apis-vector.md b/en/application-dev/reference/apis/js-apis-vector.md index 57b38f31c7e609fb59e1ff5266713e59d588c247..302b8223c0b720390c82cb28afa921b439fef7fd 100644 --- a/en/application-dev/reference/apis/js-apis-vector.md +++ b/en/application-dev/reference/apis/js-apis-vector.md @@ -1,4 +1,4 @@ -# Linear Container Vector +# @ohos.util.Vector (Linear Container Vector) > **NOTE** > @@ -290,7 +290,7 @@ vector.removeByRange(2,4); ### replaceAllElements -replaceAllElements(callbackfn: (value: T, index?: number, vector?: Vector<T>) => T, +replaceAllElements(callbackFn: (value: T, index?: number, vector?: Vector<T>) => T, thisArg?: Object): void Replaces all elements in this container with new elements, and returns the new ones. @@ -301,7 +301,7 @@ Replaces all elements in this container with new elements, and returns the new o | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for replacement.| +| callbackFn | function | Yes| Callback invoked for replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn @@ -330,7 +330,7 @@ vector.replaceAllElements((value: number, index: number) => { ### forEach -forEach(callbackfn: (value: T, index?: number, vector?: Vector<T>) => void, +forEach(callbackFn: (value: T, index?: number, vector?: Vector<T>) => void, thisArg?: Object): void Uses a callback to traverse the elements in this container and obtain their position indexes. @@ -341,7 +341,7 @@ Uses a callback to traverse the elements in this container and obtain their posi | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callbackfn | function | Yes| Callback invoked for replacement.| +| callbackFn | function | Yes| Callback invoked for replacement.| | thisArg | Object | No| Value to use when the callback is invoked.| callbackfn diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 95654a5829967c3e6f3be2be8c5daf3baf527386..f99f74149b06752ec0d1edf51ba5c46e40e3e43e 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -1,6 +1,6 @@ -# Vibrator +# @ohos.vibrator (Vibrator) -The **Vibrator** module provides APIs for triggering or stopping vibration. +The **vibrator** module provides APIs for starting or stopping vibration. > **NOTE** > @@ -17,7 +17,7 @@ import vibrator from '@ohos.vibrator'; startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void -Triggers vibration with the specified effect and attribute. This API uses a promise to return the result. +Starts vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.VIBRATE @@ -29,35 +29,35 @@ Triggers vibration with the specified effect and attribute. This API uses a prom | --------- | -------------------------------------- | ---- | :--------------------------------------------------------- | | effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. | | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | -| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback used to return 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.| +| ID| Error Message | +| -------- | ------------------------ | +| 14600101 | Device operation failed. | **Example** ```js try { vibrator.startVibration({ - type:'time', - duration:1000, - },{ - id:0, + type: 'time', + duration: 1000, + }, { + id: 0, usage: 'alarm' - }, (error)=>{ - if(error){ - console.log('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - }else{ - console.log('Callback returned to indicate a successful vibration.'); + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return; } + console.log('Callback returned to indicate a successful vibration.'); }); -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -65,7 +65,7 @@ try { startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> -Triggers vibration with the specified effect and attribute. This API uses a promise to return the result. +Starts vibration with the specified effect and attribute. This API uses a promise to return the result. **Required permissions**: ohos.permission.VIBRATE @@ -88,27 +88,27 @@ Triggers vibration with the specified effect and attribute. This API uses a prom For details about the error codes, see [Vibrator Error Codes](../errorcodes/errorcode-vibrator.md). -| ID| Error Message | -| -------- | ------------------------- | -| 14600101 | Device operation failed.| +| ID| Error Message | +| -------- | ------------------------ | +| 14600101 | Device operation failed. | **Example** ```js try { vibrator.startVibration({ - type: 'time', - duration: 1000 + type: 'time', + duration: 1000 }, { id: 0, usage: 'alarm' - }).then(()=>{ + }).then(() => { console.log('Promise returned to indicate a successful vibration'); - }).catch((error)=>{ - console.log('error.code' + error.code + 'error.message' + error.message); - }) -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); + }, (error) => { + console.error('error.code' + error.code + 'error.message' + error.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -116,7 +116,7 @@ try { stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void -Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. +Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.VIBRATE @@ -127,21 +127,41 @@ Stops the vibration with the specified **stopMode**. This API uses a promise to | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | -| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. If the vibration stops, **err** is **undefined**; otherwise, **err** is an error object.| **Example** ```js try { - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ - if(error){ + // Start vibration at a fixed duration. + vibrator.startVibration({ + type: 'time', + duration: 1000, + }, { + id: 0, + usage: 'alarm' + }, (error) => { + if (error) { + console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + return; + } + console.log('Callback returned to indicate a successful vibration.'); + }); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); +} + +try { + // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_TIME, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ - console.log('Callback returned to indicate successful.'); + return; } + console.log('Callback returned to indicate successful.'); }) -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} catch (err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` @@ -149,7 +169,7 @@ try { stopVibration(stopMode: VibratorStopMode): Promise<void> -Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. +Stops vibration in the specified mode. This API uses a promise to return the result. **Required permissions**: ohos.permission.VIBRATE @@ -171,25 +191,43 @@ Stops the vibration with the specified **stopMode**. This API uses a promise to ```js try { - vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ - console.log('Promise returned to indicate a successful vibration.'); - }, (error)=>{ + // Start vibration at a fixed duration. + vibrator.startVibration({ + type: 'time', + duration: 1000 + }, { + id: 0, + usage: 'alarm' + }).then(() => { + console.log('Promise returned to indicate a successful vibration'); + }, (error) => { + console.error('error.code' + error.code + 'error.message' + error.message); + }); +} catch (err) { + console.error('errCode: ' + err.code + ' ,msg: ' + err.message); +} + +try { + // Stop vibration in VIBRATOR_STOP_MODE_TIME mode. + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { + console.log('Promise returned to indicate a successful vibration.'); + }, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); -} catch(err) { - console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} catch (err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); } ``` ## EffectId -Describes the vibration effect ID. +Describes the preset vibration effect ID. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Default Value | Description | -| ------------------ | -------------------- | ------------------ | -| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Preset vibration effect ID.| +| Name | Value | Description | +| ------------------ | -------------------- | -------------------------------- | +| EFFECT_CLOCK_TIMER | "haptic.clock.timer" | Vibration effect of the vibrator when a user adjusts the timer.| ## VibratorStopMode @@ -198,10 +236,10 @@ Enumerates the modes available to stop the vibration. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Default Value | Description | -| ------------------------- | -------- | ------------------------------------------------------------ | -| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode. This vibration is triggered with the parameter **duration** of the **number** type.| -| VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode. This vibration is triggered with the parameter **effectId** of the **EffectId** type.| +| Name | Value | Description | +| ------------------------- | -------- | ------------------------------ | +| VIBRATOR_STOP_MODE_TIME | "time" | The vibration to stop is in **duration** mode.| +| VIBRATOR_STOP_MODE_PRESET | "preset" | The vibration to stop is in **EffectId** mode.| ## VibrateEffect9+ @@ -220,7 +258,7 @@ Describes the vibration with the specified duration. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Default Value| Description | +| Name | Value| Description | | -------- | ------ | ------------------------------ | | type | "time" | Vibration with the specified duration.| | duration | - | Vibration duration, in ms. | @@ -231,7 +269,7 @@ Describes the vibration with a preset effect. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Default Value | Description | +| Name | Value | Description | | -------- | -------- | ------------------------------ | | type | "preset" | Vibration with the specified effect.| | effectId | - | Preset vibration effect ID. | @@ -243,7 +281,7 @@ Describes the vibration attribute. **System capability**: SystemCapability.Sensors.MiscDevice -| Name | Default Value| Description | +| Name | Value| Description | | ----- | ------ | -------------- | | id | 0 | Vibrator ID. | | usage | - | Vibration scenario.| @@ -293,9 +331,9 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta **Example** ```js -vibrator.vibrate(1000).then(()=>{ +vibrator.vibrate(1000).then(() => { console.log('Promise returned to indicate a successful vibration.'); -}, (error)=>{ +}, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); ``` @@ -317,15 +355,15 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------------- | | duration | number | Yes | Vibration duration, in ms. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | No | Callback used to return the result. If the vibration starts, **err** is **undefined**; otherwise, **err** is an error object.| **Example** ```js -vibrator.vibrate(1000,function(error){ - if(error){ +vibrator.vibrate(1000, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ + } else { console.log('Callback returned to indicate a successful vibration.'); } }) @@ -359,9 +397,9 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta **Example** ```js -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(() => { console.log('Promise returned to indicate a successful vibration.'); -}, (error)=>{ +}, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); ``` @@ -384,15 +422,15 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sta | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------------- | | effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | No | Callback used to return the result. If the vibration starts, **err** is **undefined**; otherwise, **err** is an error object.| **Example** ```js -vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ - if(error){ +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ + } else { console.log('Callback returned to indicate a successful vibration.'); } }) @@ -402,7 +440,7 @@ vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ stop(stopMode: VibratorStopMode): Promise<void> -Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. +Stops vibration in the specified mode. This API uses a promise to return the result. This API is deprecated since API version 9. You are advised to use [vibrator.stopVibration](#vibratorstopvibration9-1) instead. @@ -425,9 +463,18 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sto **Example** ```js -vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ +// Start vibration based on the specified effect ID. +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + } else { + console.log('Callback returned to indicate a successful vibration.'); + } +}) +// Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(() => { console.log('Promise returned to indicate a successful vibration.'); -}, (error)=>{ +}, (error) => { console.log('error.code' + error.code + 'error.message' + error.message); }); ``` @@ -437,7 +484,7 @@ vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void -Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. +Stops vibration in the specified mode. This API uses an asynchronous callback to return the result. This API is deprecated since API version 9. You are advised to use [vibrator.stopVibration](#vibratorstopvibration9) instead. @@ -450,15 +497,24 @@ This API is deprecated since API version 9. You are advised to use [vibrator.sto | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| +| callback | AsyncCallback<void> | No | Callback used to return the result. If the vibration stops, **err** is **undefined**; otherwise, **err** is an error object.| **Example** ```js -vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ - if(error){ +// Start vibration based on the specified effect ID. +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function (error) { + if (error) { + console.log('error.code' + error.code + 'error.message' + error.message); + } else { + console.log('Callback returned to indicate a successful vibration.'); + } +}) +// Stop vibration in VIBRATOR_STOP_MODE_PRESET mode. +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function (error) { + if (error) { console.log('error.code' + error.code + 'error.message' + error.message); - }else{ + } else { console.log('Callback returned to indicate successful.'); } }) diff --git a/en/application-dev/reference/apis/js-apis-wallpaper.md b/en/application-dev/reference/apis/js-apis-wallpaper.md index b7a9bad454b15ce99e38ff407df3aa4dc5e7b653..c7f4c94d54cc19d3a95ff40784af886d28f1e3ff 100644 --- a/en/application-dev/reference/apis/js-apis-wallpaper.md +++ b/en/application-dev/reference/apis/js-apis-wallpaper.md @@ -1,20 +1,19 @@ -# Wallpaper +# @ohos.wallpaper -The **wallpaper** module is part of the theme framework and provides the system-level wallpaper management service in OpenHarmony. You can use the APIs of this module to show, set, and switch between wallpapers. +The **wallpaper** module is a system service module in OpenHarmony that provides the wallpaper management service. You can use the APIs of this module to show, set, and switch between wallpapers. > **NOTE** -> +> > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -``` +```js import wallpaper from '@ohos.wallpaper'; ``` - ## WallpaperType Enumerates the wallpaper types. @@ -27,15 +26,25 @@ Enumerates the wallpaper types. | WALLPAPER_LOCKSCREEN | 1 |Lock screen wallpaper.| -## wallpaper.getColors +## RgbaColor -getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void +Defines the RGBA color space for the wallpaper. -Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.MiscServices.Wallpaper -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| +| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.| +| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.| +| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| + + +## wallpaper.getColorsSync9+ + +getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> + +Obtains the main color information of the wallpaper of the specified type. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -44,30 +53,29 @@ Obtains the main color information of the wallpaper of the specified type. This | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes| Callback used to return the main color information of the wallpaper.| -**Example** +**Return value** - ```js - wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getColors because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getColors.`); - }); - ``` +| Type| Description| +| -------- | -------- | +| Array<[RgbaColor](#rgbacolor)> | Promise used to return the main color information of the wallpaper.| +**Example** -## wallpaper.getColors +```js +try { + let colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); + console.log(`success to getColorsSync: ${JSON.stringify(colors)}`); +} catch (error) { + console.error(`failed to getColorsSync because: ${JSON.stringify(error)}`); +} +``` -getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> +## wallpaper.getIdSync9+ -Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. +getIdSync(wallpaperType: WallpaperType): number -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. +Obtains the ID of the wallpaper of the specified type. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -81,24 +89,135 @@ Obtains the main color information of the wallpaper of the specified type. This | Type| Description| | -------- | -------- | -| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper.| +| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to (2^31-1).| **Example** - ```js - wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getColors.`); - }).catch((error) => { - console.error(`failed to getColors because: ` + JSON.stringify(error)); - }); - ``` +```js +try { + let id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); + console.log(`success to getIdSync: ${JSON.stringify(id)}`); +} catch (error) { + console.error(`failed to getIdSync because: ${JSON.stringify(error)}`); +} +``` +## wallpaper.getMinHeightSync9+ -## wallpaper.getColorsSync9+ +getMinHeightSync(): number -getColorsSync(wallpaperType: WallpaperType): Array<RgbaColor> +Obtains the minimum height of this wallpaper. -Obtains the main color information of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| + +**Example** + +```js +let minHeight = wallpaper.getMinHeightSync(); +``` + +## wallpaper.getMinWidthSync9+ + +getMinWidthSync(): number + +Obtains the minimum width of this wallpaper. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| + +**Example** + +```js +let minWidth = wallpaper.getMinWidthSync(); +``` + +## wallpaper.isChangeAllowed9+ + +isChangeAllowed(): boolean + +Checks whether to allow the application to change the wallpaper for the current user. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| + +**Example** + +```js +let isChangeAllowed = wallpaper.isChangeAllowed(); +``` + +## wallpaper.isUserChangeAllowed9+ + +isUserChangeAllowed(): boolean + +Checks whether the user is allowed to set wallpapers. + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Return value** + +| Type| Description| +| -------- | -------- | +| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| + +**Example** + +```js +let isUserChangeAllowed = wallpaper.isUserChangeAllowed(); +``` + +## wallpaper.restore9+ + +restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void + +Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER + +**System capability**: SystemCapability.MiscServices.Wallpaper + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is reset, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + +```js +wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to restore because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to restore.`); +}); +``` + +## wallpaper.restore9+ + +restore(wallpaperType: WallpaperType): Promise<void> + +Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -112,24 +231,25 @@ Obtains the main color information of the wallpaper of the specified type. This | Type| Description| | -------- | -------- | -| Array<[RgbaColor](#rgbacolor)> | Promise used to return the main color information of the wallpaper.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - var colors = wallpaper.getColorsSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - +```js +wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to restore.`); + }).catch((error) => { + console.error(`failed to restore because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getId +## wallpaper.setImage9+ -getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void +setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -137,31 +257,52 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<number> | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** - ```js - wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getId because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getId: ` + JSON.stringify(data)); - }); - ``` - +```js +// The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setImage.`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getId +## wallpaper.setImage9+ -getId(wallpaperType: WallpaperType): Promise<number> +setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -Obtains the ID of the wallpaper of the specified type. This API uses a promise to return the result. +Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. +**Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -169,30 +310,53 @@ Obtains the ID of the wallpaper of the specified type. This API uses a promise t | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getId: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to getId because: ` + JSON.stringify(error)); - }); - ``` +```js +// The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); +}).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setImage.`); + }).catch((error) => { + console.error(`failed to setImage because: ${JSON.stringify(error)}`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.getFileSync9+ -## wallpaper.getIdSync9+ +getFileSync(wallpaperType: WallpaperType): number; -getIdSync(wallpaperType: WallpaperType): number +Obtains the wallpaper of the specified type. -Obtains the ID of the wallpaper of the specified type. This API uses an asynchronous callback to return the result. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -206,105 +370,118 @@ Obtains the ID of the wallpaper of the specified type. This API uses an asynchro | Type| Description| | -------- | -------- | -| number | ID of the wallpaper. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to 2^31-1.| +| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| **Example** - ```js - var id = wallpaper.getIdSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - +```js +try { + let file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); + console.log(`success to getFileSync: ${JSON.stringify(file)}`); +} catch (error) { + console.error(`failed to getFileSync because: ${JSON.stringify(error)}`); +} +``` -## wallpaper.getMinHeight +## wallpaper.getImage9+ -getMinHeight(callback: AsyncCallback<number>): void +getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; -Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. +Obtains the pixel map for the wallpaper of the specified type. 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 [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes| Callback used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| **Example** - ```js - wallpaper.getMinHeight((error, data) => { - if (error) { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinHeight: ` + JSON.stringify(data)); - }); - ``` +```js +wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) { + if (error) { + console.error(`failed to getImage because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getImage: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.getMinHeight +## wallpaper.getImage9+ -getMinHeight(): Promise<number> +getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> -Obtains the minimum height of this wallpaper. This API uses a promise to return the result. +Obtains the pixel map for the wallpaper of the specified type. 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 [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. +**Required permissions**: ohos.permission.GET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper +**System API**: This is a system API. + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| **Example** - ```js - wallpaper.getMinHeight().then((data) => { - console.log(`success to getMinHeight: ` + JSON.stringify(data)); +```js +wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getImage: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to getMinHeight because: ` + JSON.stringify(error)); - }); - ``` - + console.error(`failed to getImage because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getMinHeightSync9+ +## wallpaper.on('colorChange')9+ -getMinHeightSync(): number +on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void -Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. +Subscribes to the wallpaper color change event. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| number | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.| +| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** - ```js - var minHeight = wallpaper.getMinHeightSync(); - ``` - - -## wallpaper.getMinWidth +```js +try { + let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); + }; + wallpaper.on('colorChange', listener); +} catch (error) { + console.error(`failed to on because: ${JSON.stringify(error)}`); +} +``` -getMinWidth(callback: AsyncCallback<number>): void +## wallpaper.off('colorChange')9+ -Obtains the minimum width of this wallpaper. This API uses an asynchronous callback to return the result. +off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void -> **NOTE** -> -> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +Unsubscribes from the wallpaper color change event. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -312,80 +489,110 @@ Obtains the minimum width of this wallpaper. This API uses an asynchronous callb | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| type | string | Yes| Type of the event to unsubscribe from. The value **'colorChange'** indicates unsubscribing from the wallpaper color change event.| +| callback | function | No| Callback for the wallpaper color change event. If this parameter is not set, this API unsubscribes from all callbacks corresponding to **type**.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| **Example** - ```js - wallpaper.getMinWidth((error, data) => { - if (error) { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getMinWidth: ` + JSON.stringify(data)); - }); - ``` - +```js +let listener = (colors, wallpaperType) => { + console.log(`wallpaper color changed.`); +}; +try { + wallpaper.on('colorChange', listener); +} catch (error) { + console.error(`failed to on because: ${JSON.stringify(error)}`); +} + +try { + // Unsubscribe from the listener. + wallpaper.off('colorChange', listener); +} catch (error) { + console.error(`failed to off because: ${JSON.stringify(error)}`); +} + +try { + // Unsubscribe from all subscriptions of the colorChange type. + wallpaper.off('colorChange'); +} catch (error) { + console.error(`failed to off because: ${JSON.stringify(error)}`); +} +``` -## wallpaper.getMinWidth +## wallpaper.getColors(deprecated) -getMinWidth(): Promise<number> +getColors(wallpaperType: WallpaperType, callback: AsyncCallback<Array<RgbaColor>>): void -Obtains the minimum width of this wallpaper. This API uses a promise to return the result. +Obtains the main color information of the wallpaper of the specified type. 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 [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| Promise<number> | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<Array<[RgbaColor](#rgbacolor)>> | Yes| Callback used to return the main color information of the wallpaper.| **Example** - ```js - wallpaper.getMinWidth().then((data) => { - console.log(`success to getMinWidth: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to getMinWidth because: ` + JSON.stringify(error)); - }); - ``` +```js +wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getColors because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getColors: ${JSON.stringify(data)}`); +}); +``` +## wallpaper.getColors(deprecated) -## wallpaper.getMinWidthSync9+ +getColors(wallpaperType: WallpaperType): Promise<Array<RgbaColor>> -getMinWidthSync(): number +Obtains the main color information of the wallpaper of the specified type. This API uses a promise to return the result. -Obtains the minimum width of this wallpaper. 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 [wallpaper.getColorsSync9+](#wallpapergetcolorssync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| number | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| +| Promise<Array<[RgbaColor](#rgbacolor)>> | Promise used to return the main color information of the wallpaper.| **Example** - ```js - var minWidth = wallpaper.getMinWidthSync(); - ``` - +```js +wallpaper.getColors(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getColors: ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getColors because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.isChangePermitted +## wallpaper.getId(deprecated) -isChangePermitted(callback: AsyncCallback<boolean>): void +getId(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void -Checks whether to allow the application to change the wallpaper for the current user. This API uses an asynchronous callback to return the result. +Obtains the ID of the wallpaper of the specified type. 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 [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -393,136 +600,152 @@ Checks whether to allow the application to change the wallpaper for the current | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| +| callback | AsyncCallback<number> | Yes| Callback used to return the wallpaper ID. If the wallpaper of the specified type is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to (2^31-1).| **Example** - ```js - wallpaper.isChangePermitted((error, data) => { - if (error) { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); - }); - ``` - +```js +wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getId because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getId: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.isChangePermitted +## wallpaper.getId(deprecated) -isChangePermitted(): Promise<boolean> +getId(wallpaperType: WallpaperType): Promise<number> -Checks whether to allow the application to change the wallpaper for the current user. This API uses a promise to return the result. +Obtains the ID of the wallpaper of the specified type. 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 [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getIdSync9+](#wallpapergetidsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| + **Return value** | Type| Description| | -------- | -------- | -| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Promise<number> | Promise used to return the wallpaper ID. If this type of wallpaper is configured, a number greater than or equal to **0** is returned. Otherwise, **-1** is returned. The value ranges from -1 to (2^31-1).| **Example** - ```js - wallpaper.isChangePermitted().then((data) => { - console.log(`success to isChangePermitted: ` + JSON.stringify(data)); +```js +wallpaper.getId(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getId: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to isChangePermitted because: ` + JSON.stringify(error)); - }); - ``` + console.error(`failed to getId because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.getMinHeight(deprecated) -## wallpaper.isChangeAllowed9+ +getMinHeight(callback: AsyncCallback<number>): void -isChangeAllowed(): boolean +Obtains the minimum height of this wallpaper. This API uses an asynchronous callback to return the result. -Checks whether to allow the application to change the wallpaper for the current user. 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 [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| boolean | Whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** - ```js - var isChangeAllowed = wallpaper.isChangeAllowed(); - ``` - +```js +wallpaper.getMinHeight((error, data) => { + if (error) { + console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getMinHeight: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.isOperationAllowed +## wallpaper.getMinHeight(deprecated) -isOperationAllowed(callback: AsyncCallback<boolean>): void +getMinHeight(): Promise<number> -Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. +Obtains the minimum height of this wallpaper. 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 [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinHeightSync9+](#wallpapergetminheightsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** +**Return value** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Type| Description| +| -------- | -------- | +| Promise<number> | Promise used to return the minimum wallpaper height, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default height should be used instead.| **Example** - ```js - wallpaper.isOperationAllowed((error, data) => { - if (error) { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - return; - } - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); - }); - ``` - +```js +wallpaper.getMinHeight().then((data) => { + console.log(`success to getMinHeight: ${JSON.stringify(data)}`); +}).catch((error) => { + console.error(`failed to getMinHeight because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.isOperationAllowed +## wallpaper.getMinWidth(deprecated) -isOperationAllowed(): Promise<boolean> +getMinWidth(callback: AsyncCallback<number>): void -Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. +Obtains the minimum width of this wallpaper. 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 [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Return value** +**Parameters** -| Type| Description| -| -------- | -------- | -| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<number> | Yes| Callback used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** - ```js - wallpaper.isOperationAllowed().then((data) => { - console.log(`success to isOperationAllowed: ` + JSON.stringify(data)); - }).catch((error) => { - console.error(`failed to isOperationAllowed because: ` + JSON.stringify(error)); - }); - ``` +```js +wallpaper.getMinWidth((error, data) => { + if (error) { + console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getMinWidth: ${JSON.stringify(data)}`); +}); +``` +## wallpaper.getMinWidth(deprecated) -## wallpaper.isUserChangeAllowed9+ +getMinWidth(): Promise<number> -isUserChangeAllowed(): boolean +Obtains the minimum width of this wallpaper. This API uses a promise to return the result. -Checks whether the user is allowed to set wallpapers. 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 [wallpaper.getMinWidthSync9+](#wallpapergetminwidthsync9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -530,26 +753,27 @@ Checks whether the user is allowed to set wallpapers. This API uses an asynchron | Type| Description| | -------- | -------- | -| boolean | Whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| +| Promise<number> | Promise used to return the minimum wallpaper width, in pixels. If the return value is **0**, no wallpaper is set. In this case, the default width should be used instead.| **Example** - ```js - var isUserChangeAllowed = wallpaper.isUserChangeAllowed(); - ``` - +```js +wallpaper.getMinWidth().then((data) => { + console.log(`success to getMinWidth: ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getMinWidth because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.reset +## wallpaper.isChangePermitted(deprecated) -reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +isChangePermitted(callback: AsyncCallback<boolean>): void -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether to allow the application to change the wallpaper for the current user. 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 [wallpaper.restore9+](#wallpaperrestore9) instead. - -**Required permissions**: ohos.permission.SET_WALLPAPER +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -557,66 +781,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to reset because: ` + JSON.stringify(error)); - return; - } - console.log(`success to reset.`); - }); - ``` - +```js +wallpaper.isChangePermitted((error, data) => { + if (error) { + console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to isChangePermitted: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.reset +## wallpaper.isChangePermitted(deprecated) -reset(wallpaperType: WallpaperType): Promise<void> +isChangePermitted(): Promise<boolean> -Resets the wallpaper of the specified type to the default wallpaper. This API uses a promise to return the result. +Checks whether to allow the application to change the wallpaper for the current user. 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 [wallpaper.restore9+](#wallpaperrestore9) instead. - -**Required permissions**: ohos.permission.SET_WALLPAPER +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isChangeAllowed9+](#wallpaperischangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| Promise<boolean> | Promise used to return whether to allow the application to change the wallpaper for the current user. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to reset.`); - }).catch((error) => { - console.error(`failed to reset because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.isChangePermitted().then((data) => { + console.log(`success to isChangePermitted: ${JSON.stringify(data)}`); +}).catch((error) => { + console.error(`failed to isChangePermitted because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.restore9+ +## wallpaper.isOperationAllowed(deprecated) -restore(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +isOperationAllowed(callback: AsyncCallback<boolean>): void -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether the user is allowed to set wallpapers. This API uses an asynchronous callback to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper @@ -624,64 +839,57 @@ Resets the wallpaper of the specified type to the default wallpaper. This API us | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the result of removal is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<boolean> | Yes| Callback used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to restore because: ` + JSON.stringify(error)); - return; - } - console.log(`success to restore.`); - }); - ``` - +```js +wallpaper.isOperationAllowed((error, data) => { + if (error) { + console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.restore9+ +## wallpaper.isOperationAllowed(deprecated) -restore(wallpaperType: WallpaperType): Promise<void> +isOperationAllowed(): Promise<boolean> -Resets the wallpaper of the specified type to the default wallpaper. This API uses an asynchronous callback to return the result. +Checks whether the user is allowed to set wallpapers. This API uses a promise to return the result. -**Required permissions**: ohos.permission.SET_WALLPAPER +> **NOTE** +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.isUserChangeAllowed9+](#wallpaperisuserchangeallowed9) instead. **System capability**: SystemCapability.MiscServices.Wallpaper -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the result is returned. Otherwise, error information is returned.| +| Promise<boolean> | Promise used to return whether the user is allowed to set wallpapers. The value **true** means that the operation is allowed, and **false** means the opposite.| **Example** - ```js - wallpaper.restore(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to restore.`); +```js +wallpaper.isOperationAllowed().then((data) => { + console.log(`success to isOperationAllowed: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to restore because: ` + JSON.stringify(error)); - }); - ``` - + console.error(`failed to isOperationAllowed because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.setWallpaper +## wallpaper.reset(deprecated) -setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +reset(wallpaperType: WallpaperType, callback: AsyncCallback<void>): void -Sets a specified source as the wallpaper of a specified type. This API uses an asynchronous callback to return the result. +Resets the wallpaper of the specified type to the default wallpaper. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -691,55 +899,30 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is reset, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setWallpaper.`); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to reset because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to reset.`); +}); +``` -## wallpaper.setWallpaper +## wallpaper.reset(deprecated) -setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> +reset(wallpaperType: WallpaperType): Promise<void> -Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. +Resets the wallpaper of the specified type to the default wallpaper. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. +> +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [wallpaper.restore9+](#wallpaperrestore9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -749,53 +932,34 @@ Sets a specified source as the wallpaper of a specified type. This API uses a pr | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); - }).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setWallpaper.`); - }).catch((error) => { - console.error(`failed to setWallpaper because: ` + JSON.stringify(error)); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` - +```js +wallpaper.reset(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to reset.`); +}).catch((error) => { + console.error(`failed to reset because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.setImage9+ +## wallpaper.setWallpaper(deprecated) -setImage(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void +setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType, callback: AsyncCallback<void>): void Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. + **Required permissions**: ohos.permission.SET_WALLPAPER **System capability**: SystemCapability.MiscServices.Wallpaper @@ -804,51 +968,54 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the wallpaper is set, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setImage.`); - }); - - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - return; - } - console.log(`success to setImage.`); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` +```js +// The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setWallpaper.`); +}); + +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error) => { + if (error) { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to setWallpaper.`); + }); +}).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` +## wallpaper.setWallpaper(deprecated) -## wallpaper.setImage9+ +setWallpaper(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> -setImage(source: string | image.PixelMap, wallpaperType: WallpaperType): Promise<void> +Sets a specified source as the wallpaper of a specified type. This API uses a promise to return the result. -Sets a specified source as the wallpaper of a specified type. 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 [wallpaper.setImage9+](#wallpapersetimage9) instead. **Required permissions**: ohos.permission.SET_WALLPAPER @@ -858,48 +1025,48 @@ Sets a specified source as the wallpaper of a specified type. This API uses an a | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| source | string \|[image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or bitmap of a PNG file.| +| source | string \| [image.PixelMap](js-apis-image.md#pixelmap7) | Yes| URI of a JPEG or PNG file, or pixel map of a PNG file.| | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| **Return value** | Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. If the operation is successful, the setting result is returned. Otherwise, error information is returned.| +| Promise<void> | Promise that returns no value.| **Example** - ```js - //The source type is string. - let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; - wallpaper.setImage(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setImage.`); +```js +// The source type is string. +let wallpaperPath = "/data/data/ohos.acts.aafwk.plrdtest.form/files/Cup_ic.jpg"; +wallpaper.setWallpaper(wallpaperPath, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setWallpaper.`); }).catch((error) => { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - }); + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); +}); - // The source type is image.PixelMap. - import image from '@ohos.multimedia.image'; - let imageSource = image.createImageSource("file://" + wallpaperPath); - let opts = { - "desiredSize": { - "height": 3648, - "width": 2736 - } - }; - imageSource.createPixelMap(opts).then((pixelMap) => { - wallpaper.setImage(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to setImage.`); - }).catch((error) => { - console.error(`failed to setImage because: ` + JSON.stringify(error)); - }); - }).catch((error) => { - console.error(`failed to createPixelMap because: ` + JSON.stringify(error)); - }); - ``` +// The source type is image.PixelMap. +import image from '@ohos.multimedia.image'; +let imageSource = image.createImageSource("file://" + wallpaperPath); +let opts = { + "desiredSize": { + "height": 3648, + "width": 2736 + } +}; +imageSource.createPixelMap(opts).then((pixelMap) => { + wallpaper.setWallpaper(pixelMap, wallpaper.WallpaperType.WALLPAPER_SYSTEM).then(() => { + console.log(`success to setWallpaper.`); + }).catch((error) => { + console.error(`failed to setWallpaper because: ${JSON.stringify(error)}`); + }); + }).catch((error) => { + console.error(`failed to createPixelMap because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getFile8+ +## wallpaper.getFile(deprecated) getFile(wallpaperType: WallpaperType, callback: AsyncCallback<number>): void @@ -922,17 +1089,17 @@ Obtains the wallpaper of the specified type. This API uses an asynchronous callb **Example** - ```js - wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { - if (error) { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - return; - } - console.log(`success to getFile: ` + JSON.stringify(data)); - }); - ``` +```js +wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM, (error, data) => { + if (error) { + console.error(`failed to getFile because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getFile: ${JSON.stringify(data)}`); +}); +``` -## wallpaper.getFile8+ +## wallpaper.getFile(deprecated) getFile(wallpaperType: WallpaperType): Promise<number> @@ -960,45 +1127,15 @@ Obtains the wallpaper of the specified type. This API uses a promise to return t **Example** - ```js - wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.log(`success to getFile: ` + JSON.stringify(data)); +```js +wallpaper.getFile(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getFile: ${JSON.stringify(data)}`); }).catch((error) => { - console.error(`failed to getFile because: ` + JSON.stringify(error)); - }); - ``` - - -## wallpaper.getFileSync9+ - -getFileSync(wallpaperType: WallpaperType): number; - -Obtains the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| number | Promise used to return the result. If the operation is successful, the file descriptor ID to the wallpaper is returned. Otherwise, error information is returned.| - -**Example** - - ```js - var file = wallpaper.getFileSync(wallpaper.WallpaperType.WALLPAPER_SYSTEM); - ``` - + console.error(`failed to getFile because: ${JSON.stringify(error)}`); +}); +``` -## wallpaper.getPixelMap +## wallpaper.getPixelMap(deprecated) getPixelMap(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; @@ -1012,26 +1149,28 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an **System capability**: SystemCapability.MiscServices.Wallpaper -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<image.PixelMap> | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| +| callback | AsyncCallback<image.PixelMap> | Yes| Callback used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| **Example** - ```js - wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) { - console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem err : ' + JSON.stringify(err)); - console.info('wallpaperXTS ===> testGetPixelMapCallbackSystem data : ' + JSON.stringify(data)); +```js +wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (error, data) { + if (error) { + console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`); + return; + } + console.log(`success to getPixelMap : ${JSON.stringify(data)}`); }); - ``` - +``` -## wallpaper.getPixelMap +## wallpaper.getPixelMap(deprecated) getPixelMap(wallpaperType: WallpaperType): Promise<image.PixelMap> @@ -1045,73 +1184,7 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses a p **System capability**: SystemCapability.MiscServices.Wallpaper -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| - -**Return value** - -| Type| Description| -| -------- | -------- | -| Promise<image.PixelMap> | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| - -**Example** - - ```js - wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + data); - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem data : ' + JSON.stringify(data)); - }).catch((err) => { - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + err); - console.info('wallpaperXTS ===> testGetPixelMapPromiseSystem err : ' + JSON.stringify(err)); - }); - ``` - - -## wallpaper.getImage9+ - -getImage(wallpaperType: WallpaperType, callback: AsyncCallback<image.PixelMap>): void; - -Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| wallpaperType | [WallpaperType](#wallpapertype) | Yes| Wallpaper type.| -| callback | AsyncCallback<[image.PixelMap](js-apis-image.md#pixelmap7)> | Yes| Callback used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| - -**Example** - - ```js - wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM, function (err, data) { - console.info('wallpaperXTS ===> testgetImageCallbackSystem err : ' + JSON.stringify(err)); - console.info('wallpaperXTS ===> testgetImageCallbackSystem data : ' + JSON.stringify(data)); - }); - ``` - - -## wallpaper.getImage9+ - -getImage(wallpaperType: WallpaperType): Promise<image.PixelMap> - -Obtains the pixel map for the wallpaper of the specified type. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WALLPAPER - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**System API**: This is a system API and cannot be called by third-party applications. +**System API**: This is a system API. **Parameters** @@ -1123,82 +1196,14 @@ Obtains the pixel map for the wallpaper of the specified type. This API uses an | Type| Description| | -------- | -------- | -| Promise<[image.PixelMap](js-apis-image.md#pixelmap7)> | Promise used to return the result. Returns the pixel map size of the wallpaper if the operation is successful; returns an error message otherwise.| - -**Example** - - ```js - wallpaper.getImage(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { - console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + data); - console.info('wallpaperXTS ===> testgetImagePromiseSystem data : ' + JSON.stringify(data)); - }).catch((err) => { - console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + err); - console.info('wallpaperXTS ===> testgetImagePromiseSystem err : ' + JSON.stringify(err)); - }); - ``` - - -## wallpaper.on('colorChange')9+ - -on(type: 'colorChange', callback: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void - -Subscribes to the wallpaper color change event. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to subscribe to. The value **'colorChange'** indicates subscribing to the wallpaper color change event.| -| callback | function | Yes| Callback triggered when the wallpaper color changes. The wallpaper type and main colors are returned.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| - -**Example** - - ```js - let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); - }; - wallpaper.on('colorChange', listener); - ``` - - -## wallpaper.off('colorChange')9+ - -off(type: 'colorChange', callback?: (colors: Array<RgbaColor>, wallpaperType: WallpaperType) => void): void - -Unsubscribes from the wallpaper color change event. - -**System capability**: SystemCapability.MiscServices.Wallpaper - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Type of the event to unsubscribe from. The value **colorChange** indicates unsubscribing from the wallpaper color change event.| -| callback | function | No| Callback for the wallpaper color change event. If this parameter is not specified, all callbacks corresponding to the wallpaper color change event are invoked.
- colors
Main color information of the wallpaper. For details, see [RgbaColor](#rgbacolor).
- wallpaperType
Wallpaper type.| +| Promise<image.PixelMap> | Promise used to return the result. If the operation is successful, the pixel map of the wallpaper is returned. Otherwise, error information is returned.| **Example** - ```js - let listener = (colors, wallpaperType) => { - console.log(`wallpaper color changed.`); - }; - wallpaper.on('colorChange', listener); - // Unsubscribe from the listener. - wallpaper.off('colorChange', listener); - // Unsubscribe from all subscriptions of the colorChange type. - wallpaper.off('colorChange'); - ``` - - -## RgbaColor - -**System capability**: SystemCapability.MiscServices.Wallpaper - -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| red | number | Yes| Yes| Red color. The value ranges from 0 to 255.| -| green | number | Yes| Yes| Green color. The value ranges from 0 to 255.| -| blue | number | Yes| Yes| Blue color. The value ranges from 0 to 255.| -| alpha | number | Yes| Yes| Alpha value. The value ranges from 0 to 255.| +```js +wallpaper.getPixelMap(wallpaper.WallpaperType.WALLPAPER_SYSTEM).then((data) => { + console.log(`success to getPixelMap : ${JSON.stringify(data)}`); + }).catch((error) => { + console.error(`failed to getPixelMap because: ${JSON.stringify(error)}`); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-wantAgent.md b/en/application-dev/reference/apis/js-apis-wantAgent.md index 5421d20c5fc129c726f31deaae6610d2bdc28d2e..215816e358a3c70d147a149db7c9142a15535ec1 100644 --- a/en/application-dev/reference/apis/js-apis-wantAgent.md +++ b/en/application-dev/reference/apis/js-apis-wantAgent.md @@ -1,14 +1,14 @@ -# WantAgent +# @ohos.wantAgent -The **WantAgent** module provides APIs for triggering, canceling, and comparing **WantAgent** objects. You can use the APIs to create a **WantAgent** object, and obtain the user ID, bundle name, and want information of the object. +The **WantAgent** module provides APIs for creating and comparing **WantAgent** objects, and obtaining the user ID and bundle name of a **WantAgent** object. > **NOTE** > -> The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 7 and deprecated since API version 9. You are advised to use [@ohos.app.ability.wantAgent](js-apis-app-ability-wantAgent.md) instead. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```js +```ts import WantAgent from '@ohos.wantAgent'; ``` @@ -22,39 +22,43 @@ Obtains a **WantAgent** object. This API uses an asynchronous callback to return **Parameters** -| Name | Readable| Writable | Type | Mandatory| Description | -| -------- | --- | ---- | -------------------------- | ---- | ----------------------- | -| info | Yes | No | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------- | ---- | ----------------------- | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain. | +| callback | AsyncCallback\ | Yes | Callback used to return the **WantAgent** object.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + if (err.code) { + console.info('getWantAgent Callback err:' + JSON.stringify(err)) + } else { + console.info('getWantAgent Callback success') + } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -64,11 +68,9 @@ var wantAgentInfo = { wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] } -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) +WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback); ``` - - ## WantAgent.getWantAgent getWantAgent(info: WantAgentInfo): Promise\ @@ -79,9 +81,9 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. **Parameters** -| Name| Readable| Writable | Type | Mandatory| Description | -| ---- | --- | ---- | ------------- | ---- | ------------- | -| info | Yes | No | WantAgentInfo | Yes | Information about the **WantAgent** object to obtain.| +| Name| Type | Mandatory| Description | +| ---- | ------------- | ---- | ------------- | +| info | [WantAgentInfo](js-apis-inner-wantAgent-wantAgentInfo.md) | Yes | Information about the **WantAgent** object to obtain.| **Return value** @@ -91,29 +93,29 @@ Obtains a **WantAgent** object. This API uses a promise to return the result. **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -124,12 +126,10 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); }); ``` - - ## WantAgent.getBundleName getBundleName(agent: WantAgent, callback: AsyncCallback\): void @@ -140,23 +140,23 @@ Obtains the bundle name of a **WantAgent** object. This API uses an asynchronous **Parameters** -| Name | Readable| Writable | Type | Mandatory| Description | -| -------- | --- | ---- | ----------------------- | ---- | --------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the bundle name.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | --------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the bundle name.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -164,24 +164,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -195,9 +195,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // getBundleName callback function getBundleNameCallback(err, data) { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); } -WantAgent.getBundleName(wantAgent, getBundleNameCallback) +WantAgent.getBundleName(wantAgent, getBundleNameCallback); ``` @@ -212,44 +212,43 @@ Obtains the bundle name of a **WantAgent** object. This API uses a promise to re **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | +| Type | Description | +| ----------------- | ------------------------------------------------ | | Promise\ | Promise used to return the bundle name.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; - // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -260,12 +259,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getBundleName(wantAgent).then((data) => { - console.info("==========================>getBundleNameCallback=======================>"); + console.info('==========================>getBundleNameCallback=======================>'); }); ``` @@ -281,23 +280,23 @@ Obtains the user ID of a **WantAgent** object. This API uses an asynchronous cal **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | ----------------------- | ---- | ----------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the user ID.| +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ----------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the user ID.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -305,24 +304,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -336,9 +335,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // getUid callback function getUidCallback(err, data) { - console.info("==========================>getUidCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); } -WantAgent.getUid(wantAgent, getUidCallback) +WantAgent.getUid(wantAgent, getUidCallback); ``` @@ -353,9 +352,9 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -365,32 +364,32 @@ Obtains the user ID of a **WantAgent** object. This API uses a promise to return **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -401,162 +400,16 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.getUid(wantAgent).then((data) => { - console.info("==========================>getUidCallback=======================>"); -}); -``` - - - -## WantAgent.getWant - -getWant(agent: WantAgent, callback: AsyncCallback\): void - -Obtains the want in a **WantAgent** object. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | --------------------- | ---- | ------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the want.| - -**Example** - -```js -import WantAgent from '@ohos.wantAgent'; - - -// WantAgent object -var wantAgent; - -// getWantAgent callback -function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); - if (err.code == 0) { - wantAgent = data; - } else { - console.info('----getWantAgent failed!----'); - } -} -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) - -// getWant callback -function getWantCallback(err, data) { - console.info("==========================>getWantCallback=======================>"); -} -WantAgent.getWant(wantAgent, getWantCallback) -``` - - - -## WantAgent.getWant - -getWant(agent: WantAgent): Promise\ - -Obtains the want in a **WantAgent** object. This API uses a promise to return the result. - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| - -**Return value** - -| Type | Description | -| ----------------------------------------------------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the want.| - -**Example** - -```js -import WantAgent from '@ohos.wantAgent'; - - -// WantAgent object -var wantAgent; - -// WantAgentInfo object -var wantAgentInfo = { - wants: [ - { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", - parameters: - { - mykey0: 2222, - mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", - mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], - mykey6: true, - } - } - ], - operationType: WantAgent.OperationType.START_ABILITIES, - requestCode: 0, - wantAgentFlags:[WantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] -} - -WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); - wantAgent = data; -}); - -WantAgent.getWant(wantAgent).then((data) => { - console.info("==========================>getWantCallback=======================>"); + console.info('==========================>getUidCallback=======================>'); }); ``` - ## WantAgent.cancel cancel(agent: WantAgent, callback: AsyncCallback\): void @@ -567,23 +420,23 @@ Cancels a **WantAgent** object. This API uses an asynchronous callback to return **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| -------- | --- | ---- | --------------------- | ---- | --------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | --------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -591,24 +444,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -622,9 +475,9 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // cancel callback function cancelCallback(err, data) { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); } -WantAgent.cancel(wantAgent, cancelCallback) +WantAgent.cancel(wantAgent, cancelCallback); ``` @@ -639,9 +492,9 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ----- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -651,32 +504,32 @@ Cancels a **WantAgent** object. This API uses a promise to return the result. **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -687,12 +540,12 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); WantAgent.cancel(wantAgent).then((data) => { - console.info("==========================>cancelCallback=======================>"); + console.info('==========================>cancelCallback=======================>'); }); ``` @@ -708,24 +561,24 @@ Triggers a **WantAgent** object. This API uses an asynchronous callback to retur **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ----------- | --- | ---- | ----------------------------- | ---- | ------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| triggerInfo | Yes | No | TriggerInfo | Yes | **TriggerInfo** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ----------- | ----------------------------- | ---- | ------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| triggerInfo | [TriggerInfo](js-apis-inner-wantAgent-triggerInfo.md) | Yes | **TriggerInfo** object. | +| callback | AsyncCallback\ | No | Callback used to return the result.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent = data; } else { @@ -733,24 +586,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -764,7 +617,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // trigger callback function triggerCallback(data) { - console.info("==========================>triggerCallback=======================>"); + console.info('==========================>triggerCallback=======================>'); } var triggerInfo = { @@ -779,31 +632,31 @@ WantAgent.trigger(wantAgent, triggerInfo, triggerCallback) equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback\): void -Checks whether two **WantAgent** objects are equal. This API uses an asynchronous callback to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | ------------------------ | ---- | --------------------------------------- | -| agent | Yes | No | WantAgent | Yes | The first **WantAgent** object. | -| otherAgent | Yes | No | WantAgent | Yes | The second **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | The first **WantAgent** object. | +| otherAgent | WantAgent | Yes | The second **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // getWantAgent callback function getWantAgentCallback(err, data) { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); if (err.code == 0) { wantAgent1 = data; wantAgent2 = data; @@ -812,24 +665,24 @@ function getWantAgentCallback(err, data) { } } // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -843,7 +696,7 @@ WantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback) // equal callback function equalCallback(err, data) { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); } WantAgent.equal(wantAgent1, wantAgent2, equalCallback) ``` @@ -854,16 +707,16 @@ WantAgent.equal(wantAgent1, wantAgent2, equalCallback) equal(agent: WantAgent, otherAgent: WantAgent): Promise\ -Checks whether two **WantAgent** objects are equal. This API uses a promise to return the result. +Checks whether two **WantAgent** objects are equal to determine whether the same operation is from the same application. This API uses a promise to return the result. **System capability**: SystemCapability.Ability.AbilityRuntime.Core **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | The first **WantAgent** object.| -| otherAgent | Yes | No | WantAgent | Yes | The second **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | The first **WantAgent** object.| +| otherAgent | WantAgent | Yes | The second **WantAgent** object.| **Return value** @@ -873,33 +726,33 @@ Checks whether two **WantAgent** objects are equal. This API uses a promise to r **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent1; -var wantAgent2; +let wantAgent1; +let wantAgent2; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -910,13 +763,13 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent1 = data; wantAgent2 = data; }); WantAgent.equal(wantAgent1, wantAgent2).then((data) => { - console.info("==========================>equalCallback=======================>"); + console.info('==========================>equalCallback=======================>'); }); ``` @@ -930,38 +783,38 @@ Obtains the operation type of a **WantAgent** object. This API uses an asynchron **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | ------------------------ | ---- | --------------------------------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object. | -| callback | Yes | No | AsyncCallback\ | Yes | Callback used to return the operation type.| +| Name | Type | Mandatory| Description | +| ---------- | ------------------------ | ---- | --------------------------------------- | +| agent | WantAgent | Yes | Target **WantAgent** object. | +| callback | AsyncCallback\ | Yes | Callback used to return the operation type.| **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -972,7 +825,7 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; }); @@ -991,9 +844,9 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to **Parameters** -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | --------- | ---- | ------------- | -| agent | Yes | No | WantAgent | Yes | Target **WantAgent** object.| +| Name | Type | Mandatory| Description | +| ---------- | --------- | ---- | ------------- | +| agent | WantAgent | Yes | Target **WantAgent** object.| **Return value** @@ -1003,31 +856,31 @@ Obtains the operation type of a **WantAgent** object. This API uses a promise to **Example** -```js +```ts import WantAgent from '@ohos.wantAgent'; // WantAgent object -var wantAgent; +let wantAgent; // WantAgentInfo object -var wantAgentInfo = { +let wantAgentInfo = { wants: [ { - deviceId: "deviceId", - bundleName: "com.neu.setResultOnAbilityResultTest1", - abilityName: "com.example.test.MainAbility", - action: "action1", - entities: ["entity1"], - type: "MIMETYPE", - uri: "key={true,true,false}", + deviceId: 'deviceId', + bundleName: 'com.neu.setResultOnAbilityResultTest1', + abilityName: 'com.example.test.EntryAbility', + action: 'action1', + entities: ['entity1'], + type: 'MIMETYPE', + uri: 'key={true,true,false}', parameters: { mykey0: 2222, mykey1: [1, 2, 3], - mykey2: "[1, 2, 3]", - mykey3: "ssssssssssssssssssssssssss", + mykey2: '[1, 2, 3]', + mykey3: 'ssssssssssssssssssssssssss', mykey4: [false, true, false], - mykey5: ["qqqqq", "wwwwww", "aaaaaaaaaaaaaaaaa"], + mykey5: ['qqqqq', 'wwwwww', 'aaaaaaaaaaaaaaaaa'], mykey6: true, } } @@ -1038,51 +891,33 @@ var wantAgentInfo = { } WantAgent.getWantAgent(wantAgentInfo).then((data) => { - console.info("==========================>getWantAgentCallback=======================>"); + console.info('==========================>getWantAgentCallback=======================>'); wantAgent = data; + WantAgent.getOperationType(wantAgent).then((OperationType) => { + console.log('getOperationType success, OperationType: ' + OperationType); + }).catch((err) => { + console.log('getOperationType fail, err: ' + err); + }) }); - -WantAgent.getOperationType(wantAgent).then((OperationType) => { - console.log('getOperationType success, OperationType: ' + OperationType); -}).catch((err) => { - console.log('getOperationType fail, err: ' + err); -}) ``` - -## WantAgentInfo - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | --- | ---- | ------------------------------- | ---- | ---------------------- | -| wants | Yes | Yes | Array\ | Yes | Array of all **Want** objects. | -| operationType | Yes | Yes | wantAgent.OperationType | Yes | Operation type. | -| requestCode | Yes | Yes | number | Yes | Request code defined by the user.| -| wantAgentFlags | Yes | Yes | Array | No | Array of flags for using the **WantAgent** object. | -| extraInfo | Yes | Yes | {[key: string]: any} | No | Extra information. | - - - ## WantAgentFlags **System capability**: SystemCapability.Ability.AbilityRuntime.Core | Name | Value | Description | | ------------------- | -------------- | ------------------------------------------------------------ | -| ONE_TIME_FLAG | WantAgentFlags | The **WantAgent** object can be used only once. | -| NO_BUILD_FLAG | WantAgentFlags | The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned. | -| CANCEL_PRESENT_FLAG | WantAgentFlags | The existing **WantAgent** object should be canceled before a new object is generated.| -| UPDATE_PRESENT_FLAG | WantAgentFlags | Extra information of the existing **WantAgent** object is replaced with that of the new object.| -| CONSTANT_FLAG | WantAgentFlags | The **WantAgent** object is immutable. | -| REPLACE_ELEMENT | WantAgentFlags | The **element** attribute of the current **Want** can be replaced by the **element** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_ACTION | WantAgentFlags | The **action** attribute of the current **Want** can be replaced by the **action** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_URI | WantAgentFlags | The **uri** attribute of the current **Want** can be replaced by the **uri** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_ENTITIES | WantAgentFlags | The **entities** attribute of the current **Want** can be replaced by the **entities** attribute of the **Want** in **WantAgent.trigger()**.| -| REPLACE_BUNDLE | WantAgentFlags | The **bundleName** attribute of the current **Want** can be replaced by the **bundleName** attribute of **Want** in **WantAgent.trigger()**.| - - +| ONE_TIME_FLAG | 0 | The **WantAgent** object can be used only once. | +| NO_BUILD_FLAG | 1 | The **WantAgent** object does not exist and hence it is not created. In this case, **null** is returned. | +| CANCEL_PRESENT_FLAG | 2 | The existing **WantAgent** object should be canceled before a new object is generated.| +| UPDATE_PRESENT_FLAG | 3 | Extra information of the existing **WantAgent** object is replaced with that of the new object.| +| CONSTANT_FLAG | 4 | The **WantAgent** object is immutable. | +| REPLACE_ELEMENT | 5 | The **element** attribute of the current **Want** can be replaced by the **element** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ACTION | 6 | The **action** attribute of the current **Want** can be replaced by the **action** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_URI | 7 | The **uri** attribute of the current **Want** can be replaced by the **uri** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_ENTITIES | 8 | The **entities** attribute of the current **Want** can be replaced by the **entities** attribute of the **Want** in **WantAgent.trigger()**.| +| REPLACE_BUNDLE | 9 | The **bundleName** attribute of the current **Want** can be replaced by the **bundleName** attribute of **Want** in **WantAgent.trigger()**.| ## OperationType @@ -1090,35 +925,20 @@ WantAgent.getOperationType(wantAgent).then((OperationType) => { | Name | Value | Description | | ----------------- | ------------- | ------------------------- | -| UNKNOWN_TYPE | OperationType | Unknown operation type. | -| START_ABILITY | OperationType | Starts an ability with a UI.| -| START_ABILITIES | OperationType | Starts multiple abilities with a UI.| -| START_SERVICE | OperationType | Starts an ability without a UI.| -| SEND_COMMON_EVENT | OperationType | Sends a common event. | - - +| UNKNOWN_TYPE | 0 | Unknown operation type. | +| START_ABILITY | 1 | Starts an ability with a UI.| +| START_ABILITIES | 2 | Starts multiple abilities with a UI.| +| START_SERVICE | 3 | Starts an ability without a UI.| +| SEND_COMMON_EVENT | 4 | Sends a common event. | ## CompleteData **System capability**: SystemCapability.Ability.AbilityRuntime.Core -| Name | Readable| Writable| Type | Mandatory| Description | -| -------------- | --- | ---- | ------------------------------ | ---- | ---------------------- | -| info | Yes | Yes | WantAgent | Yes | A triggered **WantAgent** object. | -| want | Yes | Yes | Want | Yes | An existing triggered **want**. | -| finalCode | Yes | Yes | number | Yes | Request code that triggers the **WantAgent** object.| -| finalData | Yes | Yes | string | No | Final data collected by the common event. | -| extraInfo | Yes | Yes | {[key: string]: any} | No | Extra information. | - - - -## TriggerInfo - -**System capability**: SystemCapability.Ability.AbilityRuntime.Core - -| Name | Readable| Writable| Type | Mandatory| Description | -| ---------- | --- | ---- | -------------------- | ---- | ----------- | -| code | Yes | Yes | number | Yes | Result code.| -| want | Yes | Yes | Want | No | Want. | -| permission | Yes | Yes | string | No | Permission. | -| extraInfo | Yes | Yes | {[key: string]: any} | No | Extra information. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------ | ---- | ---------------------- | +| info | WantAgent | Yes | A triggered **WantAgent** object. | +| want | Want | Yes | An existing triggered **want**. | +| finalCode | number | Yes | Request code that triggers the **WantAgent** object.| +| finalData | string | No | Final data collected by the common event. | +| extraInfo | {[key: string]: any} | No | Extra information. | diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md index bda4ad227b32b18130682bb4fe10db9a446535ec..2b2fa3af70da2fd1725ef0221b8fd7cf5654f531 100644 --- a/en/application-dev/reference/apis/js-apis-webSocket.md +++ b/en/application-dev/reference/apis/js-apis-webSocket.md @@ -1,7 +1,9 @@ -# WebSocket Connection +# @ohos.net.webSocket (WebSocket Connection) ->![](public_sys-resources/icon-note.gif) **NOTE:** ->The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **webSocket** module implements WebSocket connection management and operation. + +> **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. > You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event. diff --git a/en/application-dev/reference/apis/js-apis-webgl.md b/en/application-dev/reference/apis/js-apis-webgl.md index a205de94d8080753ed0305f56fb6fc5ce8534707..455416ed7c1290971e5a797766d35c52ed08b537 100644 --- a/en/application-dev/reference/apis/js-apis-webgl.md +++ b/en/application-dev/reference/apis/js-apis-webgl.md @@ -43,9 +43,9 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); **Table 1** Type -| Name| Type| +| Name| Type| | -------- | -------- | -| GLenum | number | +| GLenum | number | | GLboolean | boolean | | GLbitfield | number | | GLbyte | number | @@ -58,7 +58,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | GLushort | number | | GLuint | number | | GLfloat | number | -| GLclampf | number | +| GLclampf | number | | TexImageSource | ImageData | | Float32List | array | | Int32List | array | @@ -81,7 +81,7 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); | WebGLShader | | WebGLTexture | | WebGLUniformLocation | -| [WebGLActiveInfo](#webglactiveinfo) | +| [WebGLActiveInfo](#webglactiveinfo) | | [WebGLShaderPrecisionFormat](#webglshaderprecisionformat) | | [WebGLRenderingContextBase](#webglrenderingcontextbase) | | [WebGLRenderingContextOverloads](#webglrenderingcontextoverloads) | @@ -92,39 +92,39 @@ gl.clearColor(0.0, 0.0, 0.0, 1.0); WebGLContextAttributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| alpha | boolean | No| -| depth | boolean | No| -| stencil | boolean | No| -| antialias | boolean | No| -| premultipliedAlpha | boolean | No| -| preserveDrawingBuffer | boolean | No| -| powerPreference | WebGLPowerPreference | No| -| failIfMajorPerformanceCaveat | boolean | No| -| desynchronized | boolean | No| +| alpha | boolean | No| +| depth | boolean | No| +| stencil | boolean | No| +| antialias | boolean | No| +| premultipliedAlpha | boolean | No| +| preserveDrawingBuffer | boolean | No| +| powerPreference | WebGLPowerPreference | No| +| failIfMajorPerformanceCaveat | boolean | No| +| desynchronized | boolean | No| ## WebGLActiveInfo WebGLActiveInfo -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| size | GLint | Yes| -| type | GLenum | Yes| -| name | string | Yes| +| size | GLint | Yes| +| type | GLenum | Yes| +| name | string | Yes| ## WebGLShaderPrecisionFormat WebGLShaderPrecisionFormat -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| rangeMin | GLint | Yes| -| rangeMax | GLint | Yes| -| precision | GLint | Yes| +| rangeMin | GLint | Yes| +| rangeMax | GLint | Yes| +| precision | GLint | Yes| ## WebGLRenderingContextBase @@ -134,455 +134,455 @@ WebGLRenderingContextBase ### Attributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| DEPTH_BUFFER_BIT | GLenum | Yes| -| STENCIL_BUFFER_BIT | GLenum | Yes| -| COLOR_BUFFER_BIT | GLenum | Yes| -| POINTS | GLenum | Yes| -| LINES | GLenum | Yes| -| LINE_LOOP | GLenum | Yes| -| LINE_STRIP | GLenum | Yes| -| TRIANGLES | GLenum | Yes| -| TRIANGLE_STRIP | GLenum | Yes| -| TRIANGLE_FAN | GLenum | Yes| -| ZERO | GLenum | Yes| -| ONE | GLenum | Yes| -| SRC_COLOR | GLenum | Yes| -| ONE_MINUS_SRC_COLOR | GLenum | Yes| -| SRC_ALPHA | GLenum | Yes| -| ONE_MINUS_SRC_ALPHA | GLenum | Yes| -| DST_ALPHA | GLenum | Yes| -| ONE_MINUS_DST_ALPHA | GLenum | Yes| -| DST_COLOR | GLenum | Yes| -| ONE_MINUS_DST_COLOR | GLenum | Yes| -| SRC_ALPHA_SATURATE | GLenum | Yes| -| FUNC_ADD | GLenum | Yes| -| BLEND_EQUATION | GLenum | Yes| -| BLEND_EQUATION_RGB | GLenum | Yes| -| BLEND_EQUATION_ALPHA | GLenum | Yes| -| FUNC_SUBTRACT | GLenum | Yes| -| FUNC_REVERSE_SUBTRACT | GLenum | Yes| -| BLEND_DST_RGB | GLenum | Yes| -| BLEND_SRC_RGB | GLenum | Yes| -| BLEND_DST_ALPHA | GLenum | Yes| -| BLEND_SRC_ALPHA | GLenum | Yes| -| CONSTANT_COLOR | GLenum | Yes| -| ONE_MINUS_CONSTANT_COLOR | GLenum | Yes| -| CONSTANT_ALPHA | GLenum | Yes| -| ONE_MINUS_CONSTANT_ALPHA | GLenum | Yes| -| BLEND_COLOR | GLenum | Yes| -| ARRAY_BUFFER | GLenum | Yes| -| ELEMENT_ARRAY_BUFFER | GLenum | Yes| -| ARRAY_BUFFER_BINDING | GLenum | Yes| -| ELEMENT_ARRAY_BUFFER_BINDING | GLenum | Yes| -| STREAM_DRAW | GLenum | Yes| -| STATIC_DRAW | GLenum | Yes| -| DYNAMIC_DRAW | GLenum | Yes| -| BUFFER_SIZE | GLenum | Yes| -| BUFFER_USAGE | GLenum | Yes| -| CURRENT_VERTEX_ATTRIB | GLenum | Yes| -| FRONT | GLenum | Yes| -| BACK | GLenum | Yes| -| FRONT_AND_BACK | GLenum | Yes| -| CULL_FACE | GLenum | Yes| -| BLEND | GLenum | Yes| -| DITHER | GLenum | Yes| -| STENCIL_TEST | GLenum | Yes| -| DEPTH_TEST | GLenum | Yes| -| SCISSOR_TEST | GLenum | Yes| -| POLYGON_OFFSET_FILL | GLenum | Yes| -| SAMPLE_ALPHA_TO_COVERAGE | GLenum | Yes| -| SAMPLE_COVERAGE | GLenum | Yes| -| NO_ERROR | GLenum | Yes| -| INVALID_ENUM | GLenum | Yes| -| INVALID_VALUE | GLenum | Yes| -| INVALID_OPERATION | GLenum | Yes| -| OUT_OF_MEMORY | GLenum | Yes| -| CW | GLenum | Yes| -| CCW | GLenum | Yes| -| LINE_WIDTH | GLenum | Yes| -| ALIASED_POINT_SIZE_RANGE | GLenum | Yes| -| ALIASED_LINE_WIDTH_RANGE | GLenum | Yes| -| CULL_FACE_MODE | GLenum | Yes| -| FRONT_FACE | GLenum | Yes| -| DEPTH_RANGE | GLenum | Yes| -| DEPTH_WRITEMASK | GLenum | Yes| -| DEPTH_CLEAR_VALUE | GLenum | Yes| -| DEPTH_FUNC | GLenum | Yes| -| STENCIL_CLEAR_VALUE | GLenum | Yes| -| STENCIL_FUNC | GLenum | Yes| -| STENCIL_FAIL | GLenum | Yes| -| STENCIL_PASS_DEPTH_FAIL | GLenum | Yes| -| STENCIL_PASS_DEPTH_PASS | GLenum | Yes| -| STENCIL_REF | GLenum | Yes| -| STENCIL_VALUE_MASK | GLenum | Yes| -| STENCIL_WRITEMASK | GLenum | Yes| -| STENCIL_BACK_FUNC | GLenum | Yes| -| STENCIL_BACK_FAIL | GLenum | Yes| -| STENCIL_BACK_PASS_DEPTH_FAIL | GLenum | Yes| -| STENCIL_BACK_PASS_DEPTH_PASS | GLenum | Yes| -| STENCIL_BACK_REF | GLenum | Yes| -| STENCIL_BACK_VALUE_MASK | GLenum | Yes| -| STENCIL_BACK_WRITEMASK | GLenum | Yes| -| VIEWPORT | GLenum | Yes| -| SCISSOR_BOX | GLenum | Yes| -| COLOR_CLEAR_VALUE | GLenum | Yes| -| COLOR_WRITEMASK | GLenum | Yes| -| UNPACK_ALIGNMENT | GLenum | Yes| -| PACK_ALIGNMENT | GLenum | Yes| -| MAX_TEXTURE_SIZE | GLenum | Yes| -| MAX_VIEWPORT_DIMS | GLenum | Yes| -| SUBPIXEL_BITS | GLenum | Yes| -| RED_BITS | GLenum | Yes| -| GREEN_BITS | GLenum | Yes| -| BLUE_BITS | GLenum | Yes| -| ALPHA_BITS | GLenum | Yes| -| DEPTH_BITS | GLenum | Yes| -| STENCIL_BITS | GLenum | Yes| -| POLYGON_OFFSET_UNITS | GLenum | Yes| -| POLYGON_OFFSET_FACTOR | GLenum | Yes| -| TEXTURE_BINDING_2D | GLenum | Yes| -| SAMPLE_BUFFERS | GLenum | Yes| -| SAMPLES | GLenum | Yes| -| SAMPLE_COVERAGE_VALUE | GLenum | Yes| -| SAMPLE_COVERAGE_INVERT | GLenum | Yes| -| COMPRESSED_TEXTURE_FORMATS | GLenum | Yes| -| DONT_CARE | GLenum | Yes| -| FASTEST | GLenum | Yes| -| NICEST | GLenum | Yes| -| GENERATE_MIPMAP_HINT | GLenum | Yes| -| BYTE | GLenum | Yes| -| UNSIGNED_BYTE | GLenum | Yes| -| SHORT | GLenum | Yes| -| UNSIGNED_SHORT | GLenum | Yes| -| INT | GLenum | Yes| -| UNSIGNED_INT | GLenum | Yes| -| FLOAT | GLenum | Yes| -| DEPTH_COMPONENT | GLenum | Yes| -| ALPHA | GLenum | Yes| -| RGB | GLenum | Yes| -| RGBA | GLenum | Yes| -| LUMINANCE | GLenum | Yes| -| LUMINANCE_ALPHA | GLenum | Yes| -| UNSIGNED_SHORT_4_4_4_4 | GLenum | Yes| -| UNSIGNED_SHORT_5_5_5_1 | GLenum | Yes| -| UNSIGNED_SHORT_5_6_5 | GLenum | Yes| -| FRAGMENT_SHADER | GLenum | Yes| -| VERTEX_SHADER | GLenum | Yes| -| MAX_VERTEX_ATTRIBS | GLenum | Yes| -| MAX_VERTEX_UNIFORM_VECTORS | GLenum | Yes| -| MAX_VARYING_VECTORS | GLenum | Yes| -| MAX_COMBINED_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_VERTEX_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_TEXTURE_IMAGE_UNITS | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_VECTORS | GLenum | Yes| -| SHADER_TYPE | GLenum | Yes| -| DELETE_STATUS | GLenum | Yes| -| LINK_STATUS | GLenum | Yes| -| VALIDATE_STATUS | GLenum | Yes| -| ATTACHED_SHADERS | GLenum | Yes| -| ACTIVE_UNIFORMS | GLenum | Yes| -| ACTIVE_ATTRIBUTES | GLenum | Yes| -| SHADING_LANGUAGE_VERSION | GLenum | Yes| -| CURRENT_PROGRAM | GLenum | Yes| -| NEVER | GLenum | Yes| -| LESS | GLenum | Yes| -| EQUAL | GLenum | Yes| -| LEQUAL | GLenum | Yes| -| GREATER | GLenum | Yes| -| NOTEQUAL | GLenum | Yes| -| GEQUAL | GLenum | Yes| -| ALWAYS | GLenum | Yes| -| KEEP | GLenum | Yes| -| REPLACE | GLenum | Yes| -| INCR | GLenum | Yes| -| DECR | GLenum | Yes| -| INVERT | GLenum | Yes| -| INCR_WRAP | GLenum | Yes| -| DECR_WRAP | GLenum | Yes| -| VENDOR | GLenum | Yes| -| RENDERER | GLenum | Yes| -| VERSION | GLenum | Yes| -| NEAREST | GLenum | Yes| -| LINEAR | GLenum | Yes| -| NEAREST_MIPMAP_NEAREST | GLenum | Yes| -| LINEAR_MIPMAP_NEAREST | GLenum | Yes| -| NEAREST_MIPMAP_LINEAR | GLenum | Yes| -| LINEAR_MIPMAP_LINEAR | GLenum | Yes| -| TEXTURE_MIN_FILTER | GLenum | Yes| -| TEXTURE_WRAP_S | GLenum | Yes| -| TEXTURE_WRAP_T | GLenum | Yes| -| TEXTURE_2D | GLenum | Yes| -| TEXTURE | GLenum | Yes| -| TEXTURE_CUBE_MAP | GLenum | Yes| -| TEXTURE_BINDING_CUBE_MAP | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_X | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_X | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_Y | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_Y | GLenum | Yes| -| TEXTURE_CUBE_MAP_POSITIVE_Z | GLenum | Yes| -| TEXTURE_CUBE_MAP_NEGATIVE_Z | GLenum | Yes| -| MAX_CUBE_MAP_TEXTURE_SIZE | GLenum | Yes| -| TEXTURE0 | GLenum | Yes| -| TEXTURE1 | GLenum | Yes| -| TEXTURE2 | GLenum | Yes| -| TEXTURE3 | GLenum | Yes| -| TEXTURE4 | GLenum | Yes| -| TEXTURE5 | GLenum | Yes| -| TEXTURE6 | GLenum | Yes| -| TEXTURE7 | GLenum | Yes| -| TEXTURE8 | GLenum | Yes| -| TEXTURE9 | GLenum | Yes| -| TEXTURE10 | GLenum | Yes| -| TEXTURE11 | GLenum | Yes| -| TEXTURE12 | GLenum | Yes| -| TEXTURE13 | GLenum | Yes| -| TEXTURE14 | GLenum | Yes| -| TEXTURE15 | GLenum | Yes| -| TEXTURE16 | GLenum | Yes| -| TEXTURE17 | GLenum | Yes| -| TEXTURE18 | GLenum | Yes| -| TEXTURE19 | GLenum | Yes| -| TEXTURE20 | GLenum | Yes| -| TEXTURE21 | GLenum | Yes| -| TEXTURE22 | GLenum | Yes| -| TEXTURE23 | GLenum | Yes| -| TEXTURE24 | GLenum | Yes| -| TEXTURE25 | GLenum | Yes| -| TEXTURE26 | GLenum | Yes| -| TEXTURE27 | GLenum | Yes| -| TEXTURE28 | GLenum | Yes| -| TEXTURE29 | GLenum | Yes| -| TEXTURE30 | GLenum | Yes| -| TEXTURE31 | GLenum | Yes| -| ACTIVE_TEXTURE | GLenum | Yes| -| REPEAT | GLenum | Yes| -| CLAMP_TO_EDGE | GLenum | Yes| -| MIRRORED_REPEAT | GLenum | Yes| -| FLOAT_VEC2 | GLenum | Yes| -| FLOAT_VEC3 | GLenum | Yes| -| FLOAT_VEC4 | GLenum | Yes| -| INT_VEC2 | GLenum | Yes| -| INT_VEC3 | GLenum | Yes| -| INT_VEC4 | GLenum | Yes| -| BOOL | GLenum | Yes| -| BOOL_VEC2 | GLenum | Yes| -| BOOL_VEC3 | GLenum | Yes| -| BOOL_VEC4 | GLenum | Yes| -| FLOAT_MAT2 | GLenum | Yes| -| FLOAT_MAT3 | GLenum | Yes| -| FLOAT_MAT4 | GLenum | Yes| -| SAMPLER_2D | GLenum | Yes| -| SAMPLER_CUBE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_ENABLED | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_SIZE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_STRIDE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_TYPE | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_NORMALIZED | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_POINTER | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_BUFFER_BINDING | GLenum | Yes| -| IMPLEMENTATION_COLOR_READ_TYPE | GLenum | Yes| -| IMPLEMENTATION_COLOR_READ_FORMAT | GLenum | Yes| -| COMPILE_STATUS | GLenum | Yes| -| LOW_FLOAT | GLenum | Yes| -| MEDIUM_FLOAT | GLenum | Yes| -| HIGH_FLOAT | GLenum | Yes| -| LOW_INT | GLenum | Yes| -| MEDIUM_INT | GLenum | Yes| -| HIGH_INT | GLenum | Yes| -| FRAMEBUFFER | GLenum | Yes| -| RENDERBUFFER | GLenum | Yes| -| RGBA4 | GLenum | Yes| -| RGB5_A1 | GLenum | Yes| -| RGB565 | GLenum | Yes| -| DEPTH_COMPONENT16 | GLenum | Yes| -| STENCIL_INDEX8 | GLenum | Yes| -| DEPTH_STENCIL | GLenum | Yes| -| RENDERBUFFER_WIDTH | GLenum | Yes| -| RENDERBUFFER_HEIGHT | GLenum | Yes| -| RENDERBUFFER_INTERNAL_FORMAT | GLenum | Yes| -| RENDERBUFFER_RED_SIZE | GLenum | Yes| -| RENDERBUFFER_GREEN_SIZE | GLenum | Yes| -| RENDERBUFFER_BLUE_SIZE | GLenum | Yes| -| RENDERBUFFER_ALPHA_SIZE | GLenum | Yes| -| RENDERBUFFER_DEPTH_SIZE | GLenum | Yes| -| RENDERBUFFER_STENCIL_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE | GLenum | Yes| -| COLOR_ATTACHMENT0 | GLenum | Yes| -| DEPTH_ATTACHMENT | GLenum | Yes| -| STENCIL_ATTACHMENT | GLenum | Yes| -| DEPTH_STENCIL_ATTACHMENT | GLenum | Yes| -| NONE | GLenum | Yes| -| FRAMEBUFFER_COMPLETE | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_ATTACHMENT | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_DIMENSIONS | GLenum | Yes| -| FRAMEBUFFER_UNSUPPORTED | GLenum | Yes| -| FRAMEBUFFER_BINDING | GLenum | Yes| -| RENDERBUFFER_BINDING | GLenum | Yes| -| MAX_RENDERBUFFER_SIZE | GLenum | Yes| -| INVALID_FRAMEBUFFER_OPERATION | GLenum | Yes| -| UNPACK_FLIP_Y_WEBGL | GLenum | Yes| -| UNPACK_PREMULTIPLY_ALPHA_WEBGL | GLenum | Yes| -| CONTEXT_LOST_WEBGL | GLenum | Yes| -| UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| -| BROWSER_DEFAULT_WEBGL | GLenum | Yes| -| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| -| drawingBufferWidth | GLsizei | Yes| -| drawingBufferHeight | GLsizei | Yes| +| DEPTH_BUFFER_BIT | GLenum | Yes| +| STENCIL_BUFFER_BIT | GLenum | Yes| +| COLOR_BUFFER_BIT | GLenum | Yes| +| POINTS | GLenum | Yes| +| LINES | GLenum | Yes| +| LINE_LOOP | GLenum | Yes| +| LINE_STRIP | GLenum | Yes| +| TRIANGLES | GLenum | Yes| +| TRIANGLE_STRIP | GLenum | Yes| +| TRIANGLE_FAN | GLenum | Yes| +| ZERO | GLenum | Yes| +| ONE | GLenum | Yes| +| SRC_COLOR | GLenum | Yes| +| ONE_MINUS_SRC_COLOR | GLenum | Yes| +| SRC_ALPHA | GLenum | Yes| +| ONE_MINUS_SRC_ALPHA | GLenum | Yes| +| DST_ALPHA | GLenum | Yes| +| ONE_MINUS_DST_ALPHA | GLenum | Yes| +| DST_COLOR | GLenum | Yes| +| ONE_MINUS_DST_COLOR | GLenum | Yes| +| SRC_ALPHA_SATURATE | GLenum | Yes| +| FUNC_ADD | GLenum | Yes| +| BLEND_EQUATION | GLenum | Yes| +| BLEND_EQUATION_RGB | GLenum | Yes| +| BLEND_EQUATION_ALPHA | GLenum | Yes| +| FUNC_SUBTRACT | GLenum | Yes| +| FUNC_REVERSE_SUBTRACT | GLenum | Yes| +| BLEND_DST_RGB | GLenum | Yes| +| BLEND_SRC_RGB | GLenum | Yes| +| BLEND_DST_ALPHA | GLenum | Yes| +| BLEND_SRC_ALPHA | GLenum | Yes| +| CONSTANT_COLOR | GLenum | Yes| +| ONE_MINUS_CONSTANT_COLOR | GLenum | Yes| +| CONSTANT_ALPHA | GLenum | Yes| +| ONE_MINUS_CONSTANT_ALPHA | GLenum | Yes| +| BLEND_COLOR | GLenum | Yes| +| ARRAY_BUFFER | GLenum | Yes| +| ELEMENT_ARRAY_BUFFER | GLenum | Yes| +| ARRAY_BUFFER_BINDING | GLenum | Yes| +| ELEMENT_ARRAY_BUFFER_BINDING | GLenum | Yes| +| STREAM_DRAW | GLenum | Yes| +| STATIC_DRAW | GLenum | Yes| +| DYNAMIC_DRAW | GLenum | Yes| +| BUFFER_SIZE | GLenum | Yes| +| BUFFER_USAGE | GLenum | Yes| +| CURRENT_VERTEX_ATTRIB | GLenum | Yes| +| FRONT | GLenum | Yes| +| BACK | GLenum | Yes| +| FRONT_AND_BACK | GLenum | Yes| +| CULL_FACE | GLenum | Yes| +| BLEND | GLenum | Yes| +| DITHER | GLenum | Yes| +| STENCIL_TEST | GLenum | Yes| +| DEPTH_TEST | GLenum | Yes| +| SCISSOR_TEST | GLenum | Yes| +| POLYGON_OFFSET_FILL | GLenum | Yes| +| SAMPLE_ALPHA_TO_COVERAGE | GLenum | Yes| +| SAMPLE_COVERAGE | GLenum | Yes| +| NO_ERROR | GLenum | Yes| +| INVALID_ENUM | GLenum | Yes| +| INVALID_VALUE | GLenum | Yes| +| INVALID_OPERATION | GLenum | Yes| +| OUT_OF_MEMORY | GLenum | Yes| +| CW | GLenum | Yes| +| CCW | GLenum | Yes| +| LINE_WIDTH | GLenum | Yes| +| ALIASED_POINT_SIZE_RANGE | GLenum | Yes| +| ALIASED_LINE_WIDTH_RANGE | GLenum | Yes| +| CULL_FACE_MODE | GLenum | Yes| +| FRONT_FACE | GLenum | Yes| +| DEPTH_RANGE | GLenum | Yes| +| DEPTH_WRITEMASK | GLenum | Yes| +| DEPTH_CLEAR_VALUE | GLenum | Yes| +| DEPTH_FUNC | GLenum | Yes| +| STENCIL_CLEAR_VALUE | GLenum | Yes| +| STENCIL_FUNC | GLenum | Yes| +| STENCIL_FAIL | GLenum | Yes| +| STENCIL_PASS_DEPTH_FAIL | GLenum | Yes| +| STENCIL_PASS_DEPTH_PASS | GLenum | Yes| +| STENCIL_REF | GLenum | Yes| +| STENCIL_VALUE_MASK | GLenum | Yes| +| STENCIL_WRITEMASK | GLenum | Yes| +| STENCIL_BACK_FUNC | GLenum | Yes| +| STENCIL_BACK_FAIL | GLenum | Yes| +| STENCIL_BACK_PASS_DEPTH_FAIL | GLenum | Yes| +| STENCIL_BACK_PASS_DEPTH_PASS | GLenum | Yes| +| STENCIL_BACK_REF | GLenum | Yes| +| STENCIL_BACK_VALUE_MASK | GLenum | Yes| +| STENCIL_BACK_WRITEMASK | GLenum | Yes| +| VIEWPORT | GLenum | Yes| +| SCISSOR_BOX | GLenum | Yes| +| COLOR_CLEAR_VALUE | GLenum | Yes| +| COLOR_WRITEMASK | GLenum | Yes| +| UNPACK_ALIGNMENT | GLenum | Yes| +| PACK_ALIGNMENT | GLenum | Yes| +| MAX_TEXTURE_SIZE | GLenum | Yes| +| MAX_VIEWPORT_DIMS | GLenum | Yes| +| SUBPIXEL_BITS | GLenum | Yes| +| RED_BITS | GLenum | Yes| +| GREEN_BITS | GLenum | Yes| +| BLUE_BITS | GLenum | Yes| +| ALPHA_BITS | GLenum | Yes| +| DEPTH_BITS | GLenum | Yes| +| STENCIL_BITS | GLenum | Yes| +| POLYGON_OFFSET_UNITS | GLenum | Yes| +| POLYGON_OFFSET_FACTOR | GLenum | Yes| +| TEXTURE_BINDING_2D | GLenum | Yes| +| SAMPLE_BUFFERS | GLenum | Yes| +| SAMPLES | GLenum | Yes| +| SAMPLE_COVERAGE_VALUE | GLenum | Yes| +| SAMPLE_COVERAGE_INVERT | GLenum | Yes| +| COMPRESSED_TEXTURE_FORMATS | GLenum | Yes| +| DONT_CARE | GLenum | Yes| +| FASTEST | GLenum | Yes| +| NICEST | GLenum | Yes| +| GENERATE_MIPMAP_HINT | GLenum | Yes| +| BYTE | GLenum | Yes| +| UNSIGNED_BYTE | GLenum | Yes| +| SHORT | GLenum | Yes| +| UNSIGNED_SHORT | GLenum | Yes| +| INT | GLenum | Yes| +| UNSIGNED_INT | GLenum | Yes| +| FLOAT | GLenum | Yes| +| DEPTH_COMPONENT | GLenum | Yes| +| ALPHA | GLenum | Yes| +| RGB | GLenum | Yes| +| RGBA | GLenum | Yes| +| LUMINANCE | GLenum | Yes| +| LUMINANCE_ALPHA | GLenum | Yes| +| UNSIGNED_SHORT_4_4_4_4 | GLenum | Yes| +| UNSIGNED_SHORT_5_5_5_1 | GLenum | Yes| +| UNSIGNED_SHORT_5_6_5 | GLenum | Yes| +| FRAGMENT_SHADER | GLenum | Yes| +| VERTEX_SHADER | GLenum | Yes| +| MAX_VERTEX_ATTRIBS | GLenum | Yes| +| MAX_VERTEX_UNIFORM_VECTORS | GLenum | Yes| +| MAX_VARYING_VECTORS | GLenum | Yes| +| MAX_COMBINED_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_VERTEX_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_TEXTURE_IMAGE_UNITS | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_VECTORS | GLenum | Yes| +| SHADER_TYPE | GLenum | Yes| +| DELETE_STATUS | GLenum | Yes| +| LINK_STATUS | GLenum | Yes| +| VALIDATE_STATUS | GLenum | Yes| +| ATTACHED_SHADERS | GLenum | Yes| +| ACTIVE_UNIFORMS | GLenum | Yes| +| ACTIVE_ATTRIBUTES | GLenum | Yes| +| SHADING_LANGUAGE_VERSION | GLenum | Yes| +| CURRENT_PROGRAM | GLenum | Yes| +| NEVER | GLenum | Yes| +| LESS | GLenum | Yes| +| EQUAL | GLenum | Yes| +| LEQUAL | GLenum | Yes| +| GREATER | GLenum | Yes| +| NOTEQUAL | GLenum | Yes| +| GEQUAL | GLenum | Yes| +| ALWAYS | GLenum | Yes| +| KEEP | GLenum | Yes| +| REPLACE | GLenum | Yes| +| INCR | GLenum | Yes| +| DECR | GLenum | Yes| +| INVERT | GLenum | Yes| +| INCR_WRAP | GLenum | Yes| +| DECR_WRAP | GLenum | Yes| +| VENDOR | GLenum | Yes| +| RENDERER | GLenum | Yes| +| VERSION | GLenum | Yes| +| NEAREST | GLenum | Yes| +| LINEAR | GLenum | Yes| +| NEAREST_MIPMAP_NEAREST | GLenum | Yes| +| LINEAR_MIPMAP_NEAREST | GLenum | Yes| +| NEAREST_MIPMAP_LINEAR | GLenum | Yes| +| LINEAR_MIPMAP_LINEAR | GLenum | Yes| +| TEXTURE_MIN_FILTER | GLenum | Yes| +| TEXTURE_WRAP_S | GLenum | Yes| +| TEXTURE_WRAP_T | GLenum | Yes| +| TEXTURE_2D | GLenum | Yes| +| TEXTURE | GLenum | Yes| +| TEXTURE_CUBE_MAP | GLenum | Yes| +| TEXTURE_BINDING_CUBE_MAP | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_X | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_X | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_Y | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_Y | GLenum | Yes| +| TEXTURE_CUBE_MAP_POSITIVE_Z | GLenum | Yes| +| TEXTURE_CUBE_MAP_NEGATIVE_Z | GLenum | Yes| +| MAX_CUBE_MAP_TEXTURE_SIZE | GLenum | Yes| +| TEXTURE0 | GLenum | Yes| +| TEXTURE1 | GLenum | Yes| +| TEXTURE2 | GLenum | Yes| +| TEXTURE3 | GLenum | Yes| +| TEXTURE4 | GLenum | Yes| +| TEXTURE5 | GLenum | Yes| +| TEXTURE6 | GLenum | Yes| +| TEXTURE7 | GLenum | Yes| +| TEXTURE8 | GLenum | Yes| +| TEXTURE9 | GLenum | Yes| +| TEXTURE10 | GLenum | Yes| +| TEXTURE11 | GLenum | Yes| +| TEXTURE12 | GLenum | Yes| +| TEXTURE13 | GLenum | Yes| +| TEXTURE14 | GLenum | Yes| +| TEXTURE15 | GLenum | Yes| +| TEXTURE16 | GLenum | Yes| +| TEXTURE17 | GLenum | Yes| +| TEXTURE18 | GLenum | Yes| +| TEXTURE19 | GLenum | Yes| +| TEXTURE20 | GLenum | Yes| +| TEXTURE21 | GLenum | Yes| +| TEXTURE22 | GLenum | Yes| +| TEXTURE23 | GLenum | Yes| +| TEXTURE24 | GLenum | Yes| +| TEXTURE25 | GLenum | Yes| +| TEXTURE26 | GLenum | Yes| +| TEXTURE27 | GLenum | Yes| +| TEXTURE28 | GLenum | Yes| +| TEXTURE29 | GLenum | Yes| +| TEXTURE30 | GLenum | Yes| +| TEXTURE31 | GLenum | Yes| +| ACTIVE_TEXTURE | GLenum | Yes| +| REPEAT | GLenum | Yes| +| CLAMP_TO_EDGE | GLenum | Yes| +| MIRRORED_REPEAT | GLenum | Yes| +| FLOAT_VEC2 | GLenum | Yes| +| FLOAT_VEC3 | GLenum | Yes| +| FLOAT_VEC4 | GLenum | Yes| +| INT_VEC2 | GLenum | Yes| +| INT_VEC3 | GLenum | Yes| +| INT_VEC4 | GLenum | Yes| +| BOOL | GLenum | Yes| +| BOOL_VEC2 | GLenum | Yes| +| BOOL_VEC3 | GLenum | Yes| +| BOOL_VEC4 | GLenum | Yes| +| FLOAT_MAT2 | GLenum | Yes| +| FLOAT_MAT3 | GLenum | Yes| +| FLOAT_MAT4 | GLenum | Yes| +| SAMPLER_2D | GLenum | Yes| +| SAMPLER_CUBE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_ENABLED | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_SIZE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_STRIDE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_TYPE | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_NORMALIZED | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_POINTER | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_BUFFER_BINDING | GLenum | Yes| +| IMPLEMENTATION_COLOR_READ_TYPE | GLenum | Yes| +| IMPLEMENTATION_COLOR_READ_FORMAT | GLenum | Yes| +| COMPILE_STATUS | GLenum | Yes| +| LOW_FLOAT | GLenum | Yes| +| MEDIUM_FLOAT | GLenum | Yes| +| HIGH_FLOAT | GLenum | Yes| +| LOW_INT | GLenum | Yes| +| MEDIUM_INT | GLenum | Yes| +| HIGH_INT | GLenum | Yes| +| FRAMEBUFFER | GLenum | Yes| +| RENDERBUFFER | GLenum | Yes| +| RGBA4 | GLenum | Yes| +| RGB5_A1 | GLenum | Yes| +| RGB565 | GLenum | Yes| +| DEPTH_COMPONENT16 | GLenum | Yes| +| STENCIL_INDEX8 | GLenum | Yes| +| DEPTH_STENCIL | GLenum | Yes| +| RENDERBUFFER_WIDTH | GLenum | Yes| +| RENDERBUFFER_HEIGHT | GLenum | Yes| +| RENDERBUFFER_INTERNAL_FORMAT | GLenum | Yes| +| RENDERBUFFER_RED_SIZE | GLenum | Yes| +| RENDERBUFFER_GREEN_SIZE | GLenum | Yes| +| RENDERBUFFER_BLUE_SIZE | GLenum | Yes| +| RENDERBUFFER_ALPHA_SIZE | GLenum | Yes| +| RENDERBUFFER_DEPTH_SIZE | GLenum | Yes| +| RENDERBUFFER_STENCIL_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE | GLenum | Yes| +| COLOR_ATTACHMENT0 | GLenum | Yes| +| DEPTH_ATTACHMENT | GLenum | Yes| +| STENCIL_ATTACHMENT | GLenum | Yes| +| DEPTH_STENCIL_ATTACHMENT | GLenum | Yes| +| NONE | GLenum | Yes| +| FRAMEBUFFER_COMPLETE | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_ATTACHMENT | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_DIMENSIONS | GLenum | Yes| +| FRAMEBUFFER_UNSUPPORTED | GLenum | Yes| +| FRAMEBUFFER_BINDING | GLenum | Yes| +| RENDERBUFFER_BINDING | GLenum | Yes| +| MAX_RENDERBUFFER_SIZE | GLenum | Yes| +| INVALID_FRAMEBUFFER_OPERATION | GLenum | Yes| +| UNPACK_FLIP_Y_WEBGL | GLenum | Yes| +| UNPACK_PREMULTIPLY_ALPHA_WEBGL | GLenum | Yes| +| CONTEXT_LOST_WEBGL | GLenum | Yes| +| UNPACK_COLORSPACE_CONVERSION_WEBGL | GLenum | Yes| +| BROWSER_DEFAULT_WEBGL | GLenum | Yes| +| canvas | HTMLCanvasElement \| OffscreenCanvas | Yes| +| drawingBufferWidth | GLsizei | Yes| +| drawingBufferHeight | GLsizei | Yes| ### Methods -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| getContextAttributes() | WebGLContextAttributes \| null | -| isContextLost() | boolean | -| getSupportedExtensions() | string[] \| null | -| getExtension(name: string) | any | -| activeTexture(texture: GLenum) | void | -| attachShader(program: WebGLProgram, shader: WebGLShader) | void | -| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | -| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | -| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | -| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | -| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| blendEquation(mode: GLenum) | void | -| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | -| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | -| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | -| checkFramebufferStatus(target: GLenum) | GLenum | -| clear(mask: GLbitfield) | void | -| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | -| clearDepth(depth: GLclampf) | void | -| clearStencil(s: GLint) | void | -| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | -| compileShader(shader: WebGLShader) | void | -| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | -| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| createBuffer() | WebGLBuffer \| null | -| createFramebuffer() | WebGLFramebuffer \| null | -| createProgram() | WebGLProgram \| null | -| createRenderbuffer() | WebGLRenderbuffer \| null | -| createShader(type: GLenum) | WebGLShader \| null | -| createTexture() | WebGLTexture \| null | -| cullFace(mode: GLenum) | void | -| deleteBuffer(buffer: WebGLBuffer \| null) | void | -| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | -| deleteProgram(program: WebGLProgram \| null) | void | -| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | -| deleteShader(shader: WebGLShader \| null) | void | -| deleteTexture(texture: WebGLTexture \| null) | void | -| depthFunc(func: GLenum) | void | -| depthMask(flag: GLboolean) | void | -| depthRange(zNear: GLclampf, zFar: GLclampf) | void | -| detachShader(program: WebGLProgram, shader: WebGLShader) | void | -| disable(cap: GLenum) | void | -| disableVertexAttribArray(index: GLuint) | void | -| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | -| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| enable(cap: GLenum) | void | -| enableVertexAttribArray(index: GLuint) | void | -| finish() | void | -| flush() | void | -| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | -| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | -| frontFace(mode: GLenum) | void | -| generateMipmap(target: GLenum) | void | -| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | -| getAttribLocation(program: WebGLProgram, name: string) | GLint | -| getBufferParameter(target: GLenum, pname: GLenum) | any | -| getParameter(pname: GLenum) | any | -| getError() | GLenum | -| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | -| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | -| getProgramInfoLog(program: WebGLProgram) | string \| null | -| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | -| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | -| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | -| getShaderInfoLog(shader: WebGLShader) | string \| null | -| getShaderSource(shader: WebGLShader) | string \| null | -| getTexParameter(target: GLenum, pname: GLenum) | any | -| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | -| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | -| getVertexAttrib(index: GLuint, pname: GLenum) | any | -| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | -| hint(target: GLenum, mode: GLenum) | void | -| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | -| isEnabled(cap: GLenum) | GLboolean | -| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | -| isProgram(program: WebGLProgram \| null) | GLboolean | -| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | -| isShader(shader: WebGLShader \| null) | GLboolean | -| isTexture(texture: WebGLTexture \| null) | GLboolean | -| lineWidth(width: GLfloat) | void | -| linkProgram(program: WebGLProgram) | void | -| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | -| polygonOffset(factor: GLfloat, units: GLfloat) | void | -| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| sampleCoverage(value: GLclampf, invert: GLboolean) | void | -| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| shaderSource(shader: WebGLShader, source: string) | void | -| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | -| stencilMask(mask: GLuint) | void | -| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | -| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | -| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | -| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | -| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | -| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | -| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | -| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | -| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | -| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| useProgram(program: WebGLProgram \| null) | void | -| validateProgram(program: WebGLProgram) | void | -| vertexAttrib1f(index: GLuint, x: GLfloat) | void | -| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | -| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | -| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | -| vertexAttrib1fv(index: GLuint, values: Float32List) | void | -| vertexAttrib2fv(index: GLuint, values: Float32List) | void | -| vertexAttrib3fv(index: GLuint, values: Float32List) | void | -| vertexAttrib4fv(index: GLuint, values: Float32List) | void | -| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | -| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| getContextAttributes() | WebGLContextAttributes \| null | +| isContextLost() | boolean | +| getSupportedExtensions() | string[] \| null | +| getExtension(name: string) | any | +| activeTexture(texture: GLenum) | void | +| attachShader(program: WebGLProgram, shader: WebGLShader) | void | +| bindAttribLocation(program: WebGLProgram, index: GLuint, name: string) | void | +| bindBuffer(target: GLenum, buffer: WebGLBuffer \| null) | void | +| bindFramebuffer(target: GLenum, framebuffer: WebGLFramebuffer \| null) | void | +| bindRenderbuffer(target: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| bindTexture(target: GLenum, texture: WebGLTexture \| null) | void | +| blendColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| blendEquation(mode: GLenum) | void | +| blendEquationSeparate(modeRGB: GLenum, modeAlpha: GLenum) | void | +| blendFunc(sfactor: GLenum, dfactor: GLenum) | void | +| blendFuncSeparate(srcRGB: GLenum, dstRGB: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) | void | +| checkFramebufferStatus(target: GLenum) | GLenum | +| clear(mask: GLbitfield) | void | +| clearColor(red: GLclampf, green: GLclampf, blue: GLclampf, alpha: GLclampf) | void | +| clearDepth(depth: GLclampf) | void | +| clearStencil(s: GLint) | void | +| colorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) | void | +| compileShader(shader: WebGLShader) | void | +| copyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) | void | +| copyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| createBuffer() | WebGLBuffer \| null | +| createFramebuffer() | WebGLFramebuffer \| null | +| createProgram() | WebGLProgram \| null | +| createRenderbuffer() | WebGLRenderbuffer \| null | +| createShader(type: GLenum) | WebGLShader \| null | +| createTexture() | WebGLTexture \| null | +| cullFace(mode: GLenum) | void | +| deleteBuffer(buffer: WebGLBuffer \| null) | void | +| deleteFramebuffer(framebuffer: WebGLFramebuffer \| null) | void | +| deleteProgram(program: WebGLProgram \| null) | void | +| deleteRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | void | +| deleteShader(shader: WebGLShader \| null) | void | +| deleteTexture(texture: WebGLTexture \| null) | void | +| depthFunc(func: GLenum) | void | +| depthMask(flag: GLboolean) | void | +| depthRange(zNear: GLclampf, zFar: GLclampf) | void | +| detachShader(program: WebGLProgram, shader: WebGLShader) | void | +| disable(cap: GLenum) | void | +| disableVertexAttribArray(index: GLuint) | void | +| drawArrays(mode: GLenum, first: GLint, count: GLsizei) | void | +| drawElements(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| enable(cap: GLenum) | void | +| enableVertexAttribArray(index: GLuint) | void | +| finish() | void | +| flush() | void | +| framebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: WebGLRenderbuffer \| null) | void | +| framebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: WebGLTexture \| null, level: GLint) | void | +| frontFace(mode: GLenum) | void | +| generateMipmap(target: GLenum) | void | +| getActiveAttrib(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getActiveUniform(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| getAttachedShaders(program: WebGLProgram) | WebGLShader[] \| null | +| getAttribLocation(program: WebGLProgram, name: string) | GLint | +| getBufferParameter(target: GLenum, pname: GLenum) | any | +| getParameter(pname: GLenum) | any | +| getError() | GLenum | +| getFramebufferAttachmentParameter(target: GLenum, attachment: GLenum, pname: GLenum) | any | +| getProgramParameter(program: WebGLProgram, pname: GLenum) | any | +| getProgramInfoLog(program: WebGLProgram) | string \| null | +| getRenderbufferParameter(target: GLenum, pname: GLenum) | any | +| getShaderParameter(shader: WebGLShader, pname: GLenum) | any | +| getShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum) | WebGLShaderPrecisionFormat \| null | +| getShaderInfoLog(shader: WebGLShader) | string \| null | +| getShaderSource(shader: WebGLShader) | string \| null | +| getTexParameter(target: GLenum, pname: GLenum) | any | +| getUniform(program: WebGLProgram, location: WebGLUniformLocation) | any | +| getUniformLocation(program: WebGLProgram, name: string) | WebGLUniformLocation \| null | +| getVertexAttrib(index: GLuint, pname: GLenum) | any | +| getVertexAttribOffset(index: GLuint, pname: GLenum) | GLintptr | +| hint(target: GLenum, mode: GLenum) | void | +| isBuffer(buffer: WebGLBuffer \| null) | GLboolean | +| isEnabled(cap: GLenum) | GLboolean | +| isFramebuffer(framebuffer: WebGLFramebuffer \| null) | GLboolean | +| isProgram(program: WebGLProgram \| null) | GLboolean | +| isRenderbuffer(renderbuffer: WebGLRenderbuffer \| null) | GLboolean | +| isShader(shader: WebGLShader \| null) | GLboolean | +| isTexture(texture: WebGLTexture \| null) | GLboolean | +| lineWidth(width: GLfloat) | void | +| linkProgram(program: WebGLProgram) | void | +| pixelStorei(pname: GLenum, param: GLint \| GLboolean) | void | +| polygonOffset(factor: GLfloat, units: GLfloat) | void | +| renderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| sampleCoverage(value: GLclampf, invert: GLboolean) | void | +| scissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| shaderSource(shader: WebGLShader, source: string) | void | +| stencilFunc(func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilFuncSeparate(face: GLenum, func: GLenum, ref: GLint, mask: GLuint) | void | +| stencilMask(mask: GLuint) | void | +| stencilMaskSeparate(face: GLenum, mask: GLuint) | void | +| stencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| stencilOpSeparate(face: GLenum, fail: GLenum, zfail: GLenum, zpass: GLenum) | void | +| texParameterf(target: GLenum, pname: GLenum, param: GLfloat) | void | +| texParameteri(target: GLenum, pname: GLenum, param: GLint) | void | +| uniform1f(location: WebGLUniformLocation \| null, x: GLfloat) | void | +| uniform2f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat) | void | +| uniform3f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| uniform4f(location: WebGLUniformLocation \| null, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| uniform1i(location: WebGLUniformLocation \| null, x: GLint) | void | +| uniform2i(location: WebGLUniformLocation \| null, x: GLint, y: GLint) | void | +| uniform3i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint) | void | +| uniform4i(location: WebGLUniformLocation \| null, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| useProgram(program: WebGLProgram \| null) | void | +| validateProgram(program: WebGLProgram) | void | +| vertexAttrib1f(index: GLuint, x: GLfloat) | void | +| vertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) | void | +| vertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) | void | +| vertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) | void | +| vertexAttrib1fv(index: GLuint, values: Float32List) | void | +| vertexAttrib2fv(index: GLuint, values: Float32List) | void | +| vertexAttrib3fv(index: GLuint, values: Float32List) | void | +| vertexAttrib4fv(index: GLuint, values: Float32List) | void | +| vertexAttribPointer(index: GLuint, size: GLint, type: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) | void | +| viewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | ## WebGLRenderingContextOverloads WebGLRenderingContextOverloads -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | -| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, data: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, offset: GLintptr, data: BufferSource) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, data: ArrayBufferView) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, data: ArrayBufferView) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| uniform1fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform2fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform3fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform4fv(location: WebGLUniformLocation \| null, v: Float32List) | void | +| uniform1iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform2iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform3iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniform4iv(location: WebGLUniformLocation \| null, v: Int32List) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, value: Float32List) | void | diff --git a/en/application-dev/reference/apis/js-apis-webgl2.md b/en/application-dev/reference/apis/js-apis-webgl2.md index 6fc36366d38b7d65484822911e8acdf926b8e931..dc19039007c1f8207e2dd3ac026c67bdac169d9f 100644 --- a/en/application-dev/reference/apis/js-apis-webgl2.md +++ b/en/application-dev/reference/apis/js-apis-webgl2.md @@ -75,409 +75,409 @@ WebGL2RenderingContextBase ### Attributes -| Name| Type| Mandatory| + | Name| Type| Mandatory| | -------- | -------- | -------- | -| READ_BUFFER | GLenum | Yes| -| UNPACK_ROW_LENGTH | GLenum | Yes| -| UNPACK_SKIP_ROWS | GLenum | Yes| -| UNPACK_SKIP_PIXELS | GLenum | Yes| -| PACK_ROW_LENGTH | GLenum | Yes| -| PACK_SKIP_ROWS | GLenum | Yes| -| PACK_SKIP_PIXELS | GLenum | Yes| -| COLOR | GLenum | Yes| -| DEPTH | GLenum | Yes| -| STENCIL | GLenum | Yes| -| RED | GLenum | Yes| -| RGB8 | GLenum | Yes| -| RGBA8 | GLenum | Yes| -| RGB10_A2 | GLenum | Yes| -| TEXTURE_BINDING_3D | GLenum | Yes| -| UNPACK_SKIP_IMAGES | GLenum | Yes| -| UNPACK_IMAGE_HEIGHT | GLenum | Yes| -| TEXTURE_3D | GLenum | Yes| -| TEXTURE_WRAP_R | GLenum | Yes| -| MAX_3D_TEXTURE_SIZE | GLenum | Yes| -| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| -| MAX_ELEMENTS_VERTICES | GLenum | Yes| -| MAX_ELEMENTS_INDICES | GLenum | Yes| -| TEXTURE_MIN_LOD | GLenum | Yes| -| TEXTURE_MAX_LOD | GLenum | Yes| -| TEXTURE_BASE_LEVEL | GLenum | Yes| -| TEXTURE_MAX_LEVEL | GLenum | Yes| -| MIN | GLenum | Yes| -| MAX | GLenum | Yes| -| DEPTH_COMPONENT24 | GLenum | Yes| -| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| -| TEXTURE_COMPARE_MODE | GLenum | Yes| -| TEXTURE_COMPARE_FUNC | GLenum | Yes| -| CURRENT_QUERY | GLenum | Yes| -| QUERY_RESULT | GLenum | Yes| -| QUERY_RESULT_AVAILABLE | GLenum | Yes| -| STREAM_READ | GLenum | Yes| -| STREAM_COPY | GLenum | Yes| -| STATIC_READ | GLenum | Yes| -| STATIC_COPY | GLenum | Yes| -| DYNAMIC_READ | GLenum | Yes| -| DYNAMIC_COPY | GLenum | Yes| -| MAX_DRAW_BUFFERS | GLenum | Yes| -| DRAW_BUFFER0 | GLenum | Yes| -| DRAW_BUFFER1 | GLenum | Yes| -| DRAW_BUFFER2 | GLenum | Yes| -| DRAW_BUFFER3 | GLenum | Yes| -| DRAW_BUFFER4 | GLenum | Yes| -| DRAW_BUFFER5 | GLenum | Yes| -| DRAW_BUFFER6 | GLenum | Yes| -| DRAW_BUFFER7 | GLenum | Yes| -| DRAW_BUFFER8 | GLenum | Yes| -| DRAW_BUFFER9 | GLenum | Yes| -| DRAW_BUFFER10 | GLenum | Yes| -| DRAW_BUFFER11 | GLenum | Yes| -| DRAW_BUFFER12 | GLenum | Yes| -| DRAW_BUFFER13 | GLenum | Yes| -| DRAW_BUFFER14 | GLenum | Yes| -| DRAW_BUFFER15 | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| SAMPLER_3D | GLenum | Yes| -| SAMPLER_2D_SHADOW | GLenum | Yes| -| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| -| PIXEL_PACK_BUFFER | GLenum | Yes| -| PIXEL_UNPACK_BUFFER | GLenum | Yes| -| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| -| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| -| FLOAT_MAT2x3 | GLenum | Yes| -| FLOAT_MAT2x4 | GLenum | Yes| -| FLOAT_MAT3x2 | GLenum | Yes| -| FLOAT_MAT3x4 | GLenum | Yes| -| FLOAT_MAT4x2 | GLenum | Yes| -| FLOAT_MAT4x3 | GLenum | Yes| -| SRGB | GLenum | Yes| -| SRGB8 | GLenum | Yes| -| SRGB8_ALPHA8 | GLenum | Yes| -| COMPARE_REF_TO_TEXTURE | GLenum | Yes| -| RGBA32F | GLenum | Yes| -| RGB32F | GLenum | Yes| -| RGBA16F | GLenum | Yes| -| RGB16F | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| -| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| -| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| -| MAX_VARYING_COMPONENTS | GLenum | Yes| -| TEXTURE_2D_ARRAY | GLenum | Yes| -| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| -| R11F_G11F_B10F | GLenum | Yes| -| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| -| RGB9_E5 | GLenum | Yes| -| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| -| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| -| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| -| RASTERIZER_DISCARD | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| -| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| -| INTERLEAVED_ATTRIBS | GLenum | Yes| -| SEPARATE_ATTRIBS | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| -| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| -| RGBA32UI | GLenum | Yes| -| RGB32UI | GLenum | Yes| -| RGBA16UI | GLenum | Yes| -| RGB16UI | GLenum | Yes| -| RGBA8UI | GLenum | Yes| -| RGB8UI | GLenum | Yes| -| RGBA32I | GLenum | Yes| -| RGB32I | GLenum | Yes| -| RGBA16I | GLenum | Yes| -| RGB16I | GLenum | Yes| -| RGBA8I | GLenum | Yes| -| RGB8I | GLenum | Yes| -| RED_INTEGER | GLenum | Yes| -| RGB_INTEGER | GLenum | Yes| -| RGBA_INTEGER | GLenum | Yes| -| SAMPLER_2D_ARRAY | GLenum | Yes| -| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| -| SAMPLER_CUBE_SHADOW | GLenum | Yes| -| UNSIGNED_INT_VEC2 | GLenum | Yes| -| UNSIGNED_INT_VEC3 | GLenum | Yes| -| UNSIGNED_INT_VEC4 | GLenum | Yes| -| INT_SAMPLER_2D | GLenum | Yes| -| INT_SAMPLER_3D | GLenum | Yes| -| INT_SAMPLER_CUBE | GLenum | Yes| -| INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| -| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| -| DEPTH_COMPONENT32F | GLenum | Yes| -| DEPTH32F_STENCIL8 | GLenum | Yes| -| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| -| FRAMEBUFFER_DEFAULT | GLenum | Yes| -| UNSIGNED_INT_24_8 | GLenum | Yes| -| DEPTH24_STENCIL8 | GLenum | Yes| -| UNSIGNED_NORMALIZED | GLenum | Yes| -| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| -| READ_FRAMEBUFFER | GLenum | Yes| -| DRAW_FRAMEBUFFER | GLenum | Yes| -| READ_FRAMEBUFFER_BINDING | GLenum | Yes| -| RENDERBUFFER_SAMPLES | GLenum | Yes| -| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| -| MAX_COLOR_ATTACHMENTS | GLenum | Yes| -| COLOR_ATTACHMENT1 | GLenum | Yes| -| COLOR_ATTACHMENT2 | GLenum | Yes| -| COLOR_ATTACHMENT3 | GLenum | Yes| -| COLOR_ATTACHMENT4 | GLenum | Yes| -| COLOR_ATTACHMENT5 | GLenum | Yes| -| COLOR_ATTACHMENT6 | GLenum | Yes| -| COLOR_ATTACHMENT7 | GLenum | Yes| -| COLOR_ATTACHMENT8 | GLenum | Yes| -| COLOR_ATTACHMENT9 | GLenum | Yes| -| COLOR_ATTACHMENT10 | GLenum | Yes| -| COLOR_ATTACHMENT11 | GLenum | Yes| -| COLOR_ATTACHMENT12 | GLenum | Yes| -| COLOR_ATTACHMENT13 | GLenum | Yes| -| COLOR_ATTACHMENT14 | GLenum | Yes| -| COLOR_ATTACHMENT15 | GLenum | Yes| -| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| -| MAX_SAMPLES | GLenum | Yes| -| HALF_FLOAT | GLenum | Yes| -| RG | GLenum | Yes| -| RG_INTEGER | GLenum | Yes| -| R8 | GLenum | Yes| -| RG8 | GLenum | Yes| -| R16F | GLenum | Yes| -| R32F | GLenum | Yes| -| RG16F | GLenum | Yes| -| RG32F | GLenum | Yes| -| R8I | GLenum | Yes| -| R8UI | GLenum | Yes| -| R16I | GLenum | Yes| -| R16UI | GLenum | Yes| -| R32I | GLenum | Yes| -| R32UI | GLenum | Yes| -| RG8I | GLenum | Yes| -| RG8UI | GLenum | Yes| -| RG16I | GLenum | Yes| -| RG16UI | GLenum | Yes| -| RG32I | GLenum | Yes| -| RG32UI | GLenum | Yes| -| VERTEX_ARRAY_BINDING | GLenum | Yes| -| R8_SNORM | GLenum | Yes| -| RG8_SNORM | GLenum | Yes| -| RGB8_SNORM | GLenum | Yes| -| SIGNED_NORMALIZED | GLenum | Yes| -| COPY_READ_BUFFER | GLenum | Yes| -| COPY_WRITE_BUFFER | GLenum | Yes| -| COPY_READ_BUFFER_BINDING | GLenum | Yes| -| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER | GLenum | Yes| -| UNIFORM_BUFFER_BINDING | GLenum | Yes| -| UNIFORM_BUFFER_START | GLenum | Yes| -| UNIFORM_BUFFER_SIZE | GLenum | Yes| -| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| -| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| -| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| -| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| -| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| -| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| -| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| -| UNIFORM_TYPE | GLenum | Yes| -| UNIFORM_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_INDEX | GLenum | Yes| -| UNIFORM_OFFSET | GLenum | Yes| -| UNIFORM_ARRAY_STRIDE | GLenum | Yes| -| UNIFORM_MATRIX_STRIDE | GLenum | Yes| -| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| -| UNIFORM_BLOCK_BINDING | GLenum | Yes| -| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| -| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| -| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| -| INVALID_INDEX | GLenum | Yes| -| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| -| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| -| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| -| OBJECT_TYPE | GLenum | Yes| -| SYNC_CONDITION | GLenum | Yes| -| SYNC_STATUS | GLenum | Yes| -| SYNC_FLAGS | GLenum | Yes| -| SYNC_FENCE | GLenum | Yes| -| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| -| UNSIGNALED | GLenum | Yes| -| SIGNALED | GLenum | Yes| -| ALREADY_SIGNALED | GLenum | Yes| -| TIMEOUT_EXPIRED | GLenum | Yes| -| CONDITION_SATISFIED | GLenum | Yes| -| WAIT_FAILED | GLenum | Yes| -| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| -| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| -| ANY_SAMPLES_PASSED | GLenum | Yes| -| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| -| SAMPLER_BINDING | GLenum | Yes| -| RGB10_A2UI | GLenum | Yes| -| INT_2_10_10_10_REV | GLenum | Yes| -| TRANSFORM_FEEDBACK | GLenum | Yes| -| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| -| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| -| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| -| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| -| MAX_ELEMENT_INDEX | GLenum | Yes| -| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| -| TIMEOUT_IGNORED | GLint64 | Yes| -| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| +| READ_BUFFER | GLenum | Yes| +| UNPACK_ROW_LENGTH | GLenum | Yes| +| UNPACK_SKIP_ROWS | GLenum | Yes| +| UNPACK_SKIP_PIXELS | GLenum | Yes| +| PACK_ROW_LENGTH | GLenum | Yes| +| PACK_SKIP_ROWS | GLenum | Yes| +| PACK_SKIP_PIXELS | GLenum | Yes| +| COLOR | GLenum | Yes| +| DEPTH | GLenum | Yes| +| STENCIL | GLenum | Yes| +| RED | GLenum | Yes| +| RGB8 | GLenum | Yes| +| RGBA8 | GLenum | Yes| +| RGB10_A2 | GLenum | Yes| +| TEXTURE_BINDING_3D | GLenum | Yes| +| UNPACK_SKIP_IMAGES | GLenum | Yes| +| UNPACK_IMAGE_HEIGHT | GLenum | Yes| +| TEXTURE_3D | GLenum | Yes| +| TEXTURE_WRAP_R | GLenum | Yes| +| MAX_3D_TEXTURE_SIZE | GLenum | Yes| +| UNSIGNED_INT_2_10_10_10_REV | GLenum | Yes| +| MAX_ELEMENTS_VERTICES | GLenum | Yes| +| MAX_ELEMENTS_INDICES | GLenum | Yes| +| TEXTURE_MIN_LOD | GLenum | Yes| +| TEXTURE_MAX_LOD | GLenum | Yes| +| TEXTURE_BASE_LEVEL | GLenum | Yes| +| TEXTURE_MAX_LEVEL | GLenum | Yes| +| MIN | GLenum | Yes| +| MAX | GLenum | Yes| +| DEPTH_COMPONENT24 | GLenum | Yes| +| MAX_TEXTURE_LOD_BIAS | GLenum | Yes| +| TEXTURE_COMPARE_MODE | GLenum | Yes| +| TEXTURE_COMPARE_FUNC | GLenum | Yes| +| CURRENT_QUERY | GLenum | Yes| +| QUERY_RESULT | GLenum | Yes| +| QUERY_RESULT_AVAILABLE | GLenum | Yes| +| STREAM_READ | GLenum | Yes| +| STREAM_COPY | GLenum | Yes| +| STATIC_READ | GLenum | Yes| +| STATIC_COPY | GLenum | Yes| +| DYNAMIC_READ | GLenum | Yes| +| DYNAMIC_COPY | GLenum | Yes| +| MAX_DRAW_BUFFERS | GLenum | Yes| +| DRAW_BUFFER0 | GLenum | Yes| +| DRAW_BUFFER1 | GLenum | Yes| +| DRAW_BUFFER2 | GLenum | Yes| +| DRAW_BUFFER3 | GLenum | Yes| +| DRAW_BUFFER4 | GLenum | Yes| +| DRAW_BUFFER5 | GLenum | Yes| +| DRAW_BUFFER6 | GLenum | Yes| +| DRAW_BUFFER7 | GLenum | Yes| +| DRAW_BUFFER8 | GLenum | Yes| +| DRAW_BUFFER9 | GLenum | Yes| +| DRAW_BUFFER10 | GLenum | Yes| +| DRAW_BUFFER11 | GLenum | Yes| +| DRAW_BUFFER12 | GLenum | Yes| +| DRAW_BUFFER13 | GLenum | Yes| +| DRAW_BUFFER14 | GLenum | Yes| +| DRAW_BUFFER15 | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| SAMPLER_3D | GLenum | Yes| +| SAMPLER_2D_SHADOW | GLenum | Yes| +| FRAGMENT_SHADER_DERIVATIVE_HINT | GLenum | Yes| +| PIXEL_PACK_BUFFER | GLenum | Yes| +| PIXEL_UNPACK_BUFFER | GLenum | Yes| +| PIXEL_PACK_BUFFER_BINDING | GLenum | Yes| +| PIXEL_UNPACK_BUFFER_BINDING | GLenum | Yes| +| FLOAT_MAT2x3 | GLenum | Yes| +| FLOAT_MAT2x4 | GLenum | Yes| +| FLOAT_MAT3x2 | GLenum | Yes| +| FLOAT_MAT3x4 | GLenum | Yes| +| FLOAT_MAT4x2 | GLenum | Yes| +| FLOAT_MAT4x3 | GLenum | Yes| +| SRGB | GLenum | Yes| +| SRGB8 | GLenum | Yes| +| SRGB8_ALPHA8 | GLenum | Yes| +| COMPARE_REF_TO_TEXTURE | GLenum | Yes| +| RGBA32F | GLenum | Yes| +| RGB32F | GLenum | Yes| +| RGBA16F | GLenum | Yes| +| RGB16F | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_INTEGER | GLenum | Yes| +| MAX_ARRAY_TEXTURE_LAYERS | GLenum | Yes| +| MIN_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_PROGRAM_TEXEL_OFFSET | GLenum | Yes| +| MAX_VARYING_COMPONENTS | GLenum | Yes| +| TEXTURE_2D_ARRAY | GLenum | Yes| +| TEXTURE_BINDING_2D_ARRAY | GLenum | Yes| +| R11F_G11F_B10F | GLenum | Yes| +| UNSIGNED_INT_10F_11F_11F_REV | GLenum | Yes| +| RGB9_E5 | GLenum | Yes| +| UNSIGNED_INT_5_9_9_9_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_MODE | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS | GLenum | Yes| +| TRANSFORM_FEEDBACK_VARYINGS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_START | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_SIZE | GLenum | Yes| +| TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN | GLenum | Yes| +| RASTERIZER_DISCARD | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS | GLenum | Yes| +| MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS | GLenum | Yes| +| INTERLEAVED_ATTRIBS | GLenum | Yes| +| SEPARATE_ATTRIBS | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER | GLenum | Yes| +| TRANSFORM_FEEDBACK_BUFFER_BINDING | GLenum | Yes| +| RGBA32UI | GLenum | Yes| +| RGB32UI | GLenum | Yes| +| RGBA16UI | GLenum | Yes| +| RGB16UI | GLenum | Yes| +| RGBA8UI | GLenum | Yes| +| RGB8UI | GLenum | Yes| +| RGBA32I | GLenum | Yes| +| RGB32I | GLenum | Yes| +| RGBA16I | GLenum | Yes| +| RGB16I | GLenum | Yes| +| RGBA8I | GLenum | Yes| +| RGB8I | GLenum | Yes| +| RED_INTEGER | GLenum | Yes| +| RGB_INTEGER | GLenum | Yes| +| RGBA_INTEGER | GLenum | Yes| +| SAMPLER_2D_ARRAY | GLenum | Yes| +| SAMPLER_2D_ARRAY_SHADOW | GLenum | Yes| +| SAMPLER_CUBE_SHADOW | GLenum | Yes| +| UNSIGNED_INT_VEC2 | GLenum | Yes| +| UNSIGNED_INT_VEC3 | GLenum | Yes| +| UNSIGNED_INT_VEC4 | GLenum | Yes| +| INT_SAMPLER_2D | GLenum | Yes| +| INT_SAMPLER_3D | GLenum | Yes| +| INT_SAMPLER_CUBE | GLenum | Yes| +| INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_3D | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_CUBE | GLenum | Yes| +| UNSIGNED_INT_SAMPLER_2D_ARRAY | GLenum | Yes| +| DEPTH_COMPONENT32F | GLenum | Yes| +| DEPTH32F_STENCIL8 | GLenum | Yes| +| FLOAT_32_UNSIGNED_INT_24_8_REV | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_RED_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_GREEN_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_BLUE_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE | GLenum | Yes| +| FRAMEBUFFER_DEFAULT | GLenum | Yes| +| UNSIGNED_INT_24_8 | GLenum | Yes| +| DEPTH24_STENCIL8 | GLenum | Yes| +| UNSIGNED_NORMALIZED | GLenum | Yes| +| DRAW_FRAMEBUFFER_BINDING | GLenum | Yes| +| READ_FRAMEBUFFER | GLenum | Yes| +| DRAW_FRAMEBUFFER | GLenum | Yes| +| READ_FRAMEBUFFER_BINDING | GLenum | Yes| +| RENDERBUFFER_SAMPLES | GLenum | Yes| +| FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER | GLenum | Yes| +| MAX_COLOR_ATTACHMENTS | GLenum | Yes| +| COLOR_ATTACHMENT1 | GLenum | Yes| +| COLOR_ATTACHMENT2 | GLenum | Yes| +| COLOR_ATTACHMENT3 | GLenum | Yes| +| COLOR_ATTACHMENT4 | GLenum | Yes| +| COLOR_ATTACHMENT5 | GLenum | Yes| +| COLOR_ATTACHMENT6 | GLenum | Yes| +| COLOR_ATTACHMENT7 | GLenum | Yes| +| COLOR_ATTACHMENT8 | GLenum | Yes| +| COLOR_ATTACHMENT9 | GLenum | Yes| +| COLOR_ATTACHMENT10 | GLenum | Yes| +| COLOR_ATTACHMENT11 | GLenum | Yes| +| COLOR_ATTACHMENT12 | GLenum | Yes| +| COLOR_ATTACHMENT13 | GLenum | Yes| +| COLOR_ATTACHMENT14 | GLenum | Yes| +| COLOR_ATTACHMENT15 | GLenum | Yes| +| FRAMEBUFFER_INCOMPLETE_MULTISAMPLE | GLenum | Yes| +| MAX_SAMPLES | GLenum | Yes| +| HALF_FLOAT | GLenum | Yes| +| RG | GLenum | Yes| +| RG_INTEGER | GLenum | Yes| +| R8 | GLenum | Yes| +| RG8 | GLenum | Yes| +| R16F | GLenum | Yes| +| R32F | GLenum | Yes| +| RG16F | GLenum | Yes| +| RG32F | GLenum | Yes| +| R8I | GLenum | Yes| +| R8UI | GLenum | Yes| +| R16I | GLenum | Yes| +| R16UI | GLenum | Yes| +| R32I | GLenum | Yes| +| R32UI | GLenum | Yes| +| RG8I | GLenum | Yes| +| RG8UI | GLenum | Yes| +| RG16I | GLenum | Yes| +| RG16UI | GLenum | Yes| +| RG32I | GLenum | Yes| +| RG32UI | GLenum | Yes| +| VERTEX_ARRAY_BINDING | GLenum | Yes| +| R8_SNORM | GLenum | Yes| +| RG8_SNORM | GLenum | Yes| +| RGB8_SNORM | GLenum | Yes| +| SIGNED_NORMALIZED | GLenum | Yes| +| COPY_READ_BUFFER | GLenum | Yes| +| COPY_WRITE_BUFFER | GLenum | Yes| +| COPY_READ_BUFFER_BINDING | GLenum | Yes| +| COPY_WRITE_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER | GLenum | Yes| +| UNIFORM_BUFFER_BINDING | GLenum | Yes| +| UNIFORM_BUFFER_START | GLenum | Yes| +| UNIFORM_BUFFER_SIZE | GLenum | Yes| +| MAX_VERTEX_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_FRAGMENT_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_COMBINED_UNIFORM_BLOCKS | GLenum | Yes| +| MAX_UNIFORM_BUFFER_BINDINGS | GLenum | Yes| +| MAX_UNIFORM_BLOCK_SIZE | GLenum | Yes| +| MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS | GLenum | Yes| +| MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS | GLenum | Yes| +| UNIFORM_BUFFER_OFFSET_ALIGNMENT | GLenum | Yes| +| ACTIVE_UNIFORM_BLOCKS | GLenum | Yes| +| UNIFORM_TYPE | GLenum | Yes| +| UNIFORM_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_INDEX | GLenum | Yes| +| UNIFORM_OFFSET | GLenum | Yes| +| UNIFORM_ARRAY_STRIDE | GLenum | Yes| +| UNIFORM_MATRIX_STRIDE | GLenum | Yes| +| UNIFORM_IS_ROW_MAJOR | GLenum | Yes| +| UNIFORM_BLOCK_BINDING | GLenum | Yes| +| UNIFORM_BLOCK_DATA_SIZE | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORMS | GLenum | Yes| +| UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER | GLenum | Yes| +| UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER | GLenum | Yes| +| INVALID_INDEX | GLenum | Yes| +| MAX_VERTEX_OUTPUT_COMPONENTS | GLenum | Yes| +| MAX_FRAGMENT_INPUT_COMPONENTS | GLenum | Yes| +| MAX_SERVER_WAIT_TIMEOUT | GLenum | Yes| +| OBJECT_TYPE | GLenum | Yes| +| SYNC_CONDITION | GLenum | Yes| +| SYNC_STATUS | GLenum | Yes| +| SYNC_FLAGS | GLenum | Yes| +| SYNC_FENCE | GLenum | Yes| +| SYNC_GPU_COMMANDS_COMPLETE | GLenum | Yes| +| UNSIGNALED | GLenum | Yes| +| SIGNALED | GLenum | Yes| +| ALREADY_SIGNALED | GLenum | Yes| +| TIMEOUT_EXPIRED | GLenum | Yes| +| CONDITION_SATISFIED | GLenum | Yes| +| WAIT_FAILED | GLenum | Yes| +| SYNC_FLUSH_COMMANDS_BIT | GLenum | Yes| +| VERTEX_ATTRIB_ARRAY_DIVISOR | GLenum | Yes| +| ANY_SAMPLES_PASSED | GLenum | Yes| +| ANY_SAMPLES_PASSED_CONSERVATIVE | GLenum | Yes| +| SAMPLER_BINDING | GLenum | Yes| +| RGB10_A2UI | GLenum | Yes| +| INT_2_10_10_10_REV | GLenum | Yes| +| TRANSFORM_FEEDBACK | GLenum | Yes| +| TRANSFORM_FEEDBACK_PAUSED | GLenum | Yes| +| TRANSFORM_FEEDBACK_ACTIVE | GLenum | Yes| +| TRANSFORM_FEEDBACK_BINDING | GLenum | Yes| +| TEXTURE_IMMUTABLE_FORMAT | GLenum | Yes| +| MAX_ELEMENT_INDEX | GLenum | Yes| +| TEXTURE_IMMUTABLE_LEVELS | GLenum | Yes| +| TIMEOUT_IGNORED | GLint64 | Yes| +| MAX_CLIENT_WAIT_TIMEOUT_WEBGL | GLenum | Yes| ### Methods -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | -| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | -| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | -| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | -| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | -| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| readBuffer(src: GLenum) | void | -| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | -| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | -| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | -| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | -| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| getFragDataLocation(program: WebGLProgram, name: string) | GLint | -| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | -| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | -| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | -| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | -| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | -| vertexAttribI4iv(index: GLuint, values: Int32List) | void | -| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | -| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | -| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | -| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | -| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | -| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | -| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | -| drawBuffers(buffers: GLenum[]) | void | -| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | -| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | -| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | -| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | -| createQuery() | WebGLQuery \| null | -| deleteQuery(query: WebGLQuery \| null) | void | -| isQuery(query: WebGLQuery \| null) | GLboolean | -| beginQuery(target: GLenum, query: WebGLQuery) | void | -| endQuery(target: GLenum) | void | -| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | -| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | -| createSampler() | WebGLSampler \| null | -| deleteSampler(sampler: WebGLSampler \| null) | void | -| isSampler(sampler: WebGLSampler \| null) | GLboolean | -| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | -| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | -| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | -| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | -| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | -| isSync(sync: WebGLSync \| null) | GLboolean | -| deleteSync(sync: WebGLSync \| null) | void | -| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | -| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | -| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | -| createTransformFeedback() | WebGLTransformFeedback \| null | -| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | -| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | -| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | -| beginTransformFeedback(primitiveMode: GLenum) | void | -| endTransformFeedback() | void | -| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | -| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | -| pauseTransformFeedback() | void | -| resumeTransformFeedback() | void | -| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | -| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | -| getIndexedParameter(target: GLenum, index: GLuint) | any | -| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | -| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | -| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | -| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | -| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | -| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | -| createVertexArray() | WebGLVertexArrayObject \| null | -| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | -| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | -| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | +| copyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) | void | +| getBufferSubData(target: GLenum, srcByteOffset: GLintptr, dstBuffer: ArrayBufferView, dstOffset?: GLuint, length?: GLuint) | void | +| blitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) | void | +| framebufferTextureLayer(target: GLenum, attachment: GLenum, texture: WebGLTexture \| null, level: GLint, layer: GLint) | void | +| invalidateFramebuffer(target: GLenum, attachments: GLenum[]) | void | +| invalidateSubFramebuffer(target: GLenum, attachments: GLenum[], x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| readBuffer(src: GLenum) | void | +| getInternalformatParameter(target: GLenum, internalformat: GLenum, pname: GLenum) | any | +| renderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) | void | +| texStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null) | void | +| texImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView \| null, srcOffset?: GLuint) | void | +| copyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| getFragDataLocation(program: WebGLProgram, name: string) | GLint | +| uniform1ui(location: WebGLUniformLocation \| null, v0: GLuint) | void | +| uniform2ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint) | void | +| uniform3ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint) | void | +| uniform4ui(location: WebGLUniformLocation \| null, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) | void | +| uniform1uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4uiv(location: WebGLUniformLocation \| null, data: Uint32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4x3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3x4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| vertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) | void | +| vertexAttribI4iv(index: GLuint, values: Int32List) | void | +| vertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) | void | +| vertexAttribI4uiv(index: GLuint, values: Uint32List) | void | +| vertexAttribIPointer(index: GLuint, size: GLint, type: GLenum, stride: GLsizei, offset: GLintptr) | void | +| vertexAttribDivisor(index: GLuint, divisor: GLuint) | void | +| drawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instanceCount: GLsizei) | void | +| drawElementsInstanced(mode: GLenum, count: GLsizei, type: GLenum, offset: GLintptr, instanceCount: GLsizei) | void | +| drawRangeElements(mode: GLenum, start: GLuint, end: GLuint, count: GLsizei, type: GLenum, offset: GLintptr) | void | +| drawBuffers(buffers: GLenum[]) | void | +| clearBufferfv(buffer: GLenum, drawbuffer: GLint, values: Float32List, srcOffset?: GLuint) | void | +| clearBufferiv(buffer: GLenum, drawbuffer: GLint, values: Int32List, srcOffset?: GLuint) | void | +| clearBufferuiv(buffer: GLenum, drawbuffer: GLint, values: Uint32List, srcOffset?: GLuint) | void | +| clearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) | void | +| createQuery() | WebGLQuery \| null | +| deleteQuery(query: WebGLQuery \| null) | void | +| isQuery(query: WebGLQuery \| null) | GLboolean | +| beginQuery(target: GLenum, query: WebGLQuery) | void | +| endQuery(target: GLenum) | void | +| getQuery(target: GLenum, pname: GLenum) | WebGLQuery \| null | +| getQueryParameter(query: WebGLQuery, pname: GLenum) | any | +| createSampler() | WebGLSampler \| null | +| deleteSampler(sampler: WebGLSampler \| null) | void | +| isSampler(sampler: WebGLSampler \| null) | GLboolean | +| bindSampler(unit: GLuint, sampler: WebGLSampler \| null) | void | +| samplerParameteri(sampler: WebGLSampler, pname: GLenum, param: GLint) | void | +| samplerParameterf(sampler: WebGLSampler, pname: GLenum, param: GLfloat) | void; | +| getSamplerParameter(sampler: WebGLSampler, pname: GLenum) | any | +| fenceSync(condition: GLenum, flags: GLbitfield) | WebGLSync \| null | +| isSync(sync: WebGLSync \| null) | GLboolean | +| deleteSync(sync: WebGLSync \| null) | void | +| clientWaitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLuint64) | GLenum | +| waitSync(sync: WebGLSync, flags: GLbitfield, timeout: GLint64) | void | +| getSyncParameter(sync: WebGLSync, pname: GLenum) | any | +| createTransformFeedback() | WebGLTransformFeedback \| null | +| deleteTransformFeedback(tf: WebGLTransformFeedback \| null) | void | +| isTransformFeedback(tf: WebGLTransformFeedback \| null) | GLboolean | +| bindTransformFeedback(target: GLenum, tf: WebGLTransformFeedback \| null) | void | +| beginTransformFeedback(primitiveMode: GLenum) | void | +| endTransformFeedback() | void | +| transformFeedbackVaryings(program: WebGLProgram, varyings: string[], bufferMode: GLenum) | void | +| getTransformFeedbackVarying(program: WebGLProgram, index: GLuint) | WebGLActiveInfo \| null | +| pauseTransformFeedback() | void | +| resumeTransformFeedback() | void | +| bindBufferBase(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null) | void | +| bindBufferRange(target: GLenum, index: GLuint, buffer: WebGLBuffer \| null, offset: GLintptr, size: GLsizeiptr) | void | +| getIndexedParameter(target: GLenum, index: GLuint) | any | +| getUniformIndices(program: WebGLProgram, uniformNames: string[]) | GLuint[] \| null | +| getActiveUniforms(program: WebGLProgram, uniformIndices: GLuint[], pname: GLenum) | any | +| getUniformBlockIndex(program: WebGLProgram, uniformBlockName: string) | GLuint | +| getActiveUniformBlockParameter(program: WebGLProgram, uniformBlockIndex: GLuint, pname: GLenum) | any | +| getActiveUniformBlockName(program: WebGLProgram, uniformBlockIndex: GLuint) | string \| null | +| uniformBlockBinding(program: WebGLProgram, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) | void | +| createVertexArray() | WebGLVertexArrayObject \| null | +| deleteVertexArray(vertexArray: WebGLVertexArrayObject \| null) | void | +| isVertexArray(vertexArray: WebGLVertexArrayObject \| null) | GLboolean | +| bindVertexArray(array: WebGLVertexArrayObject \| null) | void | ## WebGL2RenderingContextOverloads WebGL2RenderingContextOverloads -| Method| Return Value Type| + | Method| Return Value Type| | -------- | -------- | -| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | -| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | -| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | -| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | -| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | -| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | -| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | -| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | +| bufferData(target: GLenum, size: GLsizeiptr, usage: GLenum) | void | +| bufferData(target: GLenum, srcData: BufferSource \| null, usage: GLenum) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: BufferSource) | void | +| bufferData(target: GLenum, srcData: ArrayBufferView, usage: GLenum, srcOffset: GLuint, length?: GLuint) | void | +| bufferSubData(target: GLenum, dstByteOffset: GLintptr, srcData: ArrayBufferView, srcOffset: GLuint, length?: GLuint) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pixels: ArrayBufferView \| null) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, pboOffset: GLintptr) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, source: TexImageSource) | void | +| texSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, srcData: ArrayBufferView, srcOffset: GLuint) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, offset: GLintptr) | void | +| compressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, srcData: ArrayBufferView, srcOffset?: GLuint, srcLengthOverride?: GLuint) | void | +| uniform1fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4fv(location: WebGLUniformLocation \| null, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform1iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform2iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform3iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniform4iv(location: WebGLUniformLocation \| null, data: Int32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix2fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix3fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| uniformMatrix4fv(location: WebGLUniformLocation \| null, transpose: GLboolean, data: Float32List, srcOffset?: GLuint, srcLength?: GLuint) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView \| null) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, offset: GLintptr) | void | +| readPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, type: GLenum, dstData: ArrayBufferView, dstOffset: GLuint) | void | diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md new file mode 100644 index 0000000000000000000000000000000000000000..83d89392cd8ade90901018fbe5721ce53ba54f2e --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-webview.md @@ -0,0 +1,4575 @@ + + +# @ohos.web.webview + +The **Webview** module provides APIs for web control. + +> **NOTE** +> +> - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. +> +> - You can preview how the APIs of this module work on a real device. The preview is not yet available in the DevEco Studio Previewer. + +## Required Permissions + +**ohos.permission.INTERNET**, required for accessing online web pages. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md). + +## Modules to Import + +```ts +import web_webview from '@ohos.web.webview'; +``` + +### once + +once(type: string, callback: Callback\): void + +Registers a one-time callback for web events of the specified type. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | -------------------- | +| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | +| headers | Callback\ | Yes | Callback to register.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +web_webview.once("webInited", () => { + console.log("setCookie") + web_webview.WebCookieManager.setCookie("www.example.com", "a=b") +}) + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +## WebMessagePort + +Implements a **WebMessagePort** object to send and receive messages. + +### close + +close(): void + +Closes this message port. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + msgPort: WebMessagePort[] = null; + + build() { + Column() { + Button('close') + .onClick(() => { + if (this.msgPort && this.msgPort[1]) { + this.msgPort[1].close(); + } else { + console.error("msgPort is null, Please initialize first"); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### postMessageEvent + +postMessageEvent(message: WebMessage): void + +Sends a message. For the complete sample code, see [postMessage](#postmessage). + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ------ | ---- | :------------- | +| message | [WebMessage](#webmessage) | Yes | Message to send.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------- | +| 17100010 | Can not post message using this port. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + ports: web_webview.WebMessagePort[]; + + build() { + Column() { + Button('postMessageEvent') + .onClick(() => { + try { + this.ports = this.controller.createWebMessagePorts(); + this.controller.postMessage('__init_port__', [this.ports[0]], '*'); + this.ports[1].postMessageEvent("post message from ets to html5"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### onMessageEvent + +onMessageEvent(callback: (result: WebMessage) => void): void + +Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------- | ---- | :------------------- | +| result | [WebMessage](#webmessage) | Yes | Message received.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ----------------------------------------------- | +| 17100006 | Can not register message event using this port. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + ports: web_webview.WebMessagePort[]; + + build() { + Column() { + Button('onMessageEvent') + .onClick(() => { + try { + this.ports = this.controller.createWebMessagePorts(); + this.ports[1].onMessageEvent((msg) => { + if (typeof(msg) == "string") { + console.log("received string message from html5, string is:" + msg); + } else if (typeof(msg) == "object") { + if (msg instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + msg.byteLength); + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +## WebviewController + +Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\** component. + +### initializeWebEngine + +static initializeWebEngine(): void + +Loads the dynamic link library (DLL) file of the web engine. This API can be called before the **\** component is initialized to improve the startup performance. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +The following code snippet exemplifies calling this API after the EntryAbility is created. + +```ts +// xxx.ts +import UIAbility from '@ohos.app.ability.UIAbility'; +import web_webview from '@ohos.web.webview'; + +export default class EntryAbility extends UIAbility { + onCreate(want, launchParam) { + console.log("EntryAbility onCreate") + web_webview.WebviewController.initializeWebEngine() + globalThis.abilityWant = want + console.log("EntryAbility onCreate done") + } +} +``` + +### Creating an Object + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### loadUrl + +loadUrl(url: string | Resource, headers?: Array\): void + +Loads a specified URL. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | ---------------- | ---- | :-------------------- | +| url | string \| Resource | Yes | URL to load. | +| headers | Array\<[HeaderV9](#headerv9)> | No | Additional HTTP request header of the URL.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 17100002 | Invalid url. | +| 17100003 | Invalid resource path or file type. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadUrl') + .onClick(() => { + try { + this.controller.loadUrl('www.example.com'); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### loadData + +loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void + +Loads specified data. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | ------ | ---- | ------------------------------------------------------------ | +| data | string | Yes | Character string obtained after being Base64 or URL encoded. | +| mimeType | string | Yes | Media type (MIME). | +| encoding | string | Yes | Encoding type, which can be Base64 or URL. | +| baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **\** component to **window.origin**.| +| historyUrl | string | No | URL used for historical records. If this parameter is not empty, historical records are managed based on this URL. This parameter is invalid when **baseUrl** is left empty.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 17100002 | Invalid url. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('loadData') + .onClick(() => { + try { + this.controller.loadData( + "Source:
source
", + "text/html", + "UTF-8" + ); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### accessforward + +accessForward(): boolean + +Checks whether moving to the next page can be performed on the current page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------- | --------------------------------- | +| boolean | Returns **true** if moving to the next page can be performed on the current page; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('accessForward') + .onClick(() => { + try { + let result = this.controller.accessForward(); + console.log('result:' + result); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### forward + +forward(): void + +Moves to the next page based on the history stack. This API is generally used together with **accessForward**. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('forward') + .onClick(() => { + try { + this.controller.forward(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### accessBackward + +accessBackward(): boolean + +Checks whether moving to the previous page can be performed on the current page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------- | -------------------------------- | +| boolean | Returns **true** if moving to the previous page can be performed on the current page; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('accessBackward') + .onClick(() => { + try { + let result = this.controller.accessBackward(); + console.log('result:' + result); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### backward + +backward(): void + +Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('backward') + .onClick(() => { + try { + this.controller.backward(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### onActive + +onActive(): void + +Invoked to instruct the **\** component to enter the foreground, active state. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('onActive') + .onClick(() => { + try { + this.controller.onActive(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### onInactive + +onInactive(): void + +Invoked to instruct the **\** component to enter the inactive state. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('onInactive') + .onClick(() => { + try { + this.controller.onInactive(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### refresh +refresh(): void + +Invoked to instruct the **\** component to refresh the web page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('refresh') + .onClick(() => { + try { + this.controller.refresh(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### accessStep + +accessStep(step: number): boolean + +Checks whether a specific number of steps forward or backward can be performed on the current page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ------------------------------------------ | +| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| + +**Return value** + +| Type | Description | +| ------- | ------------------ | +| boolean | Whether moving forward or backward is performed on the current page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State steps: number = 2; + + build() { + Column() { + Button('accessStep') + .onClick(() => { + try { + let result = this.controller.accessStep(this.steps); + console.log('result:' + result); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### clearHistory + +clearHistory(): void + +Clears the browsing history. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('clearHistory') + .onClick(() => { + try { + this.controller.clearHistory(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getHitTest + +getHitTest(): HitTestTypeV9 + +Obtains the element type of the area being clicked. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------------------------------------------------------------ | ---------------------- | +| [HitTestTypeV9](#hittesttypev9)| Element type of the area being clicked.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getHitTest') + .onClick(() => { + try { + let hitTestType = this.controller.getHitTest(); + console.log("hitTestType: " + hitTestType); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### registerJavaScriptProxy + +registerJavaScriptProxy(object: object, name: string, methodList: Array\): void + +Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. After this API is called, call [refresh](#refresh) for the registration to take effect. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| ---------- | -------------- | ---- | ------------------------------------------------------------ | +| object | object | Yes | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return values of the methods can only be of the string, number, or Boolean type.| +| name | string | Yes | Name of the object to be registered, which is the same as that invoked in the window. After registration, the window can use this name to access the JavaScript object at the application side.| +| methodList | Array\ | Yes | Methods of the JavaScript object to be registered at the application side. | + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct Index { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + testObj = { + test: (data) => { + return "ArkUI Web Component"; + }, + toString: () => { + console.log('Web Component toString'); + } + } + + build() { + Column() { + Button('refresh') + .onClick(() => { + try { + this.controller.refresh(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Button('Register JavaScript To Window') + .onClick(() => { + try { + this.controller.registerJavaScriptProxy(this.testObj, "objName", ["test", "toString"]); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: $rawfile('index.html'), controller: this.controller }) + .javaScriptAccess(true) + } + } +} +``` + +### runJavaScript + +runJavaScript(script: string, callback : AsyncCallback\): void + +Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------- | ---- | ---------------------------- | +| script | string | Yes | JavaScript script. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State webResult: string = '' + + build() { + Column() { + Text(this.webResult).fontSize(20) + Web({ src: $rawfile('index.html'), controller: this.controller }) + .javaScriptAccess(true) + .onPageEnd(e => { + try { + this.controller.runJavaScript( + 'test()', + (error, result) => { + if (error) { + console.info(`run JavaScript error: ` + JSON.stringify(error)) + return; + } + if (result) { + this.webResult = result + console.info(`The test() return value is: ${result}`) + } + }); + console.info('url: ', e.url); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + } + } +} +``` + +### runJavaScript + +runJavaScript(script: string): Promise\ + +Executes a JavaScript script. This API uses a promise to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------- | +| script | string | Yes | JavaScript script.| + +**Return value** + +| Type | Description | +| --------------- | --------------------------------------------------- | +| Promise\ | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State webResult: string = ''; + + build() { + Column() { + Text(this.webResult).fontSize(20) + Web({ src: $rawfile('index.html'), controller: this.controller }) + .javaScriptAccess(true) + .onPageEnd(e => { + try { + this.controller.runJavaScript('test()') + .then(function (result) { + console.log('result: ' + result); + }) + .catch(function (error) { + console.error("error: " + error); + }) + console.info('url: ', e.url); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + } + } +} +``` + +### deleteJavaScriptRegister + +deleteJavaScriptRegister(name: string): void + +Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately without invoking the [refresh](#refresh) API. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---- | +| name | string | Yes | Name of the registered JavaScript object, which can be used to invoke the corresponding object on the application side from the web side.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | +| 17100008 | Cannot delete JavaScriptProxy. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State name: string = 'Object'; + + build() { + Column() { + Button('deleteJavaScriptRegister') + .onClick(() => { + try { + this.controller.deleteJavaScriptRegister(this.name); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### zoom + +zoom(factor: number): void + +Zooms in or out of this web page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ------ | -------- | ---- | ------------------------------------------------------------ | +| factor | number | Yes | Relative zoom ratio. A positive value indicates zoom-in, and a negative value indicates zoom-out.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | +| 17100004 | Function not enable. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State factor: number = 1; + + build() { + Column() { + Button('zoom') + .onClick(() => { + try { + this.controller.zoom(this.factor); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### searchAllAsync + +searchAllAsync(searchString: string): void + +Searches the web page for content that matches the keyword specified by **'searchString'** and highlights the matches on the page. This API returns the result asynchronously through [onSearchResultReceive](../arkui-ts/ts-basic-components-web.md#onsearchresultreceive9). + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------------ | -------- | ---- | -------------- | +| searchString | string | Yes | Search keyword.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State searchString: string = "xxx"; + + build() { + Column() { + Button('searchString') + .onClick(() => { + try { + this.controller.searchAllAsync(this.searchString); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + .onSearchResultReceive(ret => { + console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + + "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); + }) + } + } +} +``` + +### clearMatches + +clearMatches(): void + +Clears the matches found through [searchAllAsync](#searchallasync). + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('clearMatches') + .onClick(() => { + try { + this.controller.clearMatches(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### searchNext + +searchNext(forward: boolean): void + +Searches for and highlights the next match. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | ---------------------- | +| forward | boolean | Yes | Whether to search forward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('searchNext') + .onClick(() => { + try { + this.controller.searchNext(true); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### clearSslCache + +clearSslCache(): void + +Clears the user operation corresponding to the SSL certificate error event recorded by the **\** component. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('clearSslCache') + .onClick(() => { + try { + this.controller.clearSslCache(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### clearClientAuthenticationCache + +clearClientAuthenticationCache(): void + +Clears the user operation corresponding to the client certificate request event recorded by the **\** component. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('clearClientAuthenticationCache') + .onClick(() => { + try { + this.controller.clearClientAuthenticationCache(); + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### createWebMessagePorts + + createWebMessagePorts(): Array\ + +Creates web message ports. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ---------------------- | ----------------- | +| Array\ | List of web message ports.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + + ```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + ports: web_webview.WebMessagePort[]; + + build() { + Column() { + Button('createWebMessagePorts') + .onClick(() => { + try { + this.ports = this.controller.createWebMessagePorts(); + console.log("createWebMessagePorts size:" + this.ports.length) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} + ``` + +### postMessage + +postMessage(name: string, ports: Array\, uri: string): void + +Sends a web message to an HTML5 window. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ---------------------- | ---- | :------------------------------- | +| name | string | Yes | Message to send, including the data and message port.| +| ports | Array\ | Yes | Ports for receiving the message. | +| uri | string | Yes | URI for receiving the message. | + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + ports: web_webview.WebMessagePort[]; + @State sendFromEts: string = 'Send this message from ets to HTML'; + @State receivedFromHtml: string = 'Display received message send from HTML'; + + build() { + Column() { + // Display the received HTML content. + Text(this.receivedFromHtml) + // Send the content in the text box to an HTML window. + TextInput({placeholder: 'Send this message from ets to HTML'}) + .onChange((value: string) => { + this.sendFromEts = value; + }) + + Button('postMessage') + .onClick(() => { + try { + // 1. Create two message ports. + this.ports = this.controller.createWebMessagePorts(); + // 2. Send one of the message ports to the HTML side, which can then save and use the port. + this.controller.postMessage('__init_port__', [this.ports[0]], '*'); + // 3. Register a callback for the other message port on the application side. + this.ports[1].onMessageEvent((result: WebMessage) => { + var msg = 'Got msg from HTML:'; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } + this.receivedFromHtml = msg; + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + + // 4. Use the port on the application side to send messages to the message port that has been sent to the HTML. + Button('SendDataToHTML') + .onClick(() => { + try { + if (this.ports && this.ports[1]) { + this.ports[1].postMessageEvent("post message from ets to HTML"); + } else { + console.error(`ports is null, Please initialize first`); + } + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: $rawfile('xxx.html'), controller: this.controller }) + } + } +} +``` + +```html + + + + + + WebView Message Port Demo + + + +

WebView Message Port Demo

+
+
+
+
+

display received message send from ets

+ + + +``` + +```js +//xxx.js +var h5Port; +var output = document.querySelector('.output'); +window.addEventListener('message', function (event) { + if (event.data == '__init_port__') { + if (event.ports[0] != null) { + The h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. + h5Port.onmessage = function (event) { + // 2. Receive the message sent from the eTS side. + var msg = 'Got message from ets:'; + var result = event.data; + if (typeof(result) == "string") { + console.log("received string message from html5, string is:" + result); + msg = msg + result; + } else if (typeof(result) == "object") { + if (result instanceof ArrayBuffer) { + console.log("received arraybuffer from html5, length is:" + result.byteLength); + msg = msg + "lenght is " + result.byteLength; + } else { + console.log("not support"); + } + } else { + console.log("not support"); + } + output.innerHTML = msg; + } + } + } +}) + +// 3. Use h5Port to send messages to the eTS side. +function PostMsgToEts(data) { + if (h5Port) { + h5Port.postMessage(data); + } else { + console.error("h5Port is null, Please initialize first"); + } +} +``` + +### requestFocus + +requestFocus(): void + +Requests focus for this web page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('requestFocus') + .onClick(() => { + try { + this.controller.requestFocus(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }); + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### zoomIn + +zoomIn(): void + +Zooms in on this web page by 20%. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 17100004 | Function not enable. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('zoomIn') + .onClick(() => { + try { + this.controller.zoomIn(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### zoomOut + +zoomOut(): void + +Zooms out of this web page by 20%. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 17100004 | Function not enable. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('zoomOut') + .onClick(() => { + try { + this.controller.zoomOut(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getHitTestValue + +getHitTestValue(): HitTestValue + +Obtains the element information of the area being clicked. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------------ | -------------------- | +| [HitTestValue](#hittestvalue) | Element information of the area being clicked.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getHitTestValue') + .onClick(() => { + try { + let hitValue = this.controller.getHitTestValue(); + console.log("hitType: " + hitValue.type); + console.log("extra: " + hitValue.extra); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getWebId + +getWebId(): number + +Obtains the index value of this **\** component, which can be used for **\** component management. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | --------------------- | +| number | Index value of the current **\** component.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getWebId') + .onClick(() => { + try { + let id = this.controller.getWebId(); + console.log("id: " + id); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getUserAgent + +getUserAgent(): string + +Obtains the default user agent of this web page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | -------------- | +| string | Default user agent.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getUserAgent') + .onClick(() => { + try { + let userAgent = this.controller.getUserAgent(); + console.log("userAgent: " + userAgent); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getTitle + +getTitle(): string + +Obtains the title of the current web page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| string | Title of the current web page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getTitle') + .onClick(() => { + try { + let title = this.controller.getTitle(); + console.log("title: " + title); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getPageHeight + +getPageHeight(): number + +Obtains the height of this web page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | -------------------- | +| number | Height of the current web page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getPageHeight') + .onClick(() => { + try { + let pageHeight = this.controller.getPageHeight(); + console.log("pageHeight : " + pageHeight); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### storeWebArchive + +storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\): void + +Stores this web page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------------------------------------------------ | +| baseName | string | Yes | Save path. The value cannot be null. | +| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| +| callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise. | + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 17100003 | Invalid resource path or file type. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('saveWebArchive') + .onClick(() => { + try { + this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { + if (error) { + console.info(`save web archive error: ` + JSON.stringify(error)) + return; + } + if (filename != null) { + console.info(`save web archive success: ${filename}`) + } + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### storeWebArchive + +storeWebArchive(baseName: string, autoName: boolean): Promise\ + +Stores this web page. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type| Mandatory| Description | +| -------- | -------- | ---- | ------------------------------------------------------------ | +| baseName | string | Yes | Save path. The value cannot be null. | +| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.| + +**Return value** + +| Type | Description | +| --------------- | ----------------------------------------------------- | +| Promise\ | Promise used to return the save path if the operation is successful and null otherwise.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | +| 17100003 | Invalid resource path or file type. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('saveWebArchive') + .onClick(() => { + try { + this.controller.storeWebArchive("/data/storage/el2/base/", true) + .then(filename => { + if (filename != null) { + console.info(`save web archive success: ${filename}`) + } + }) + .catch(error => { + console.log('error: ' + JSON.stringify(error)); + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getUrl + +getUrl(): string + +Obtains the URL of this page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | ------------------- | +| string | URL of the current page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getUrl') + .onClick(() => { + try { + let url = this.controller.getUrl(); + console.log("url: " + url); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### stop + +stop(): void + +Stops page loading. + +**System capability**: SystemCapability.Web.Webview.Core + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('stop') + .onClick(() => { + try { + this.controller.stop(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }); + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### backOrForward + +backOrForward(step: number): void + +Performs a specific number of steps forward or backward on the current page based on the history stack. No redirection will be performed if the corresponding page does not exist in the history stack. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| step | number | Yes | Number of the steps to take.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State step: number = -2; + + build() { + Column() { + Button('backOrForward') + .onClick(() => { + try { + this.controller.backOrForward(this.step); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### scrollTo + +scrollTo(x:number, y:number): void + +Scrolls the page to the specified absolute position. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.| +| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollTo') + .onClick(() => { + try { + this.controller.scrollTo(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### scrollBy + +scrollBy(deltaX:number, deltaY:number): void + +Scrolls the page by the specified amount. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| +| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('scrollBy') + .onClick(() => { + try { + this.controller.scrollBy(50, 50); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### slideScroll + +slideScroll(vx:number, vy:number): void + +Simulates a slide-to-scroll action on the page at the specified velocity. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | ---------------------- | +| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.| +| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('slideScroll') + .onClick(() => { + try { + this.controller.slideScroll(500, 500); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +```html + + + + + Demo + + + +Scroll Test + + +``` + +### getOriginalUrl + +getOriginalUrl(): string + +Obtains the original URL of this page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------ | ----------------------- | +| string | Original URL of the current page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getOrgUrl') + .onClick(() => { + try { + let url = this.controller.getOriginalUrl(); + console.log("original url: " + url); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getFavicon + +getFavicon(): image.PixelMap + +Obtains the favicon of this page. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| -------------------------------------- | ------------------------------- | +| [PixelMap](js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; +import image from "@ohos.multimedia.image" +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State pixelmap: image.PixelMap = undefined; + + build() { + Column() { + Button('getFavicon') + .onClick(() => { + try { + this.pixelmap = this.controller.getFavicon(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### setNetworkAvailable + +setNetworkAvailable(enable: boolean): void + +Sets the **window.navigator.onLine** attribute in JavaScript. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | --------------------------------- | +| enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('setNetworkAvailable') + .onClick(() => { + try { + this.controller.setNetworkAvailable(true); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### hasImage + +hasImage(callback: AsyncCallback\): void + +Checks whether this page contains images. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | -------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('hasImageCb') + .onClick(() => { + try { + this.controller.hasImage((error, data) => { + if (error) { + console.info(`hasImage error: ` + JSON.stringify(error)) + return; + } + console.info("hasImage: " + data); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### hasImage + +hasImage(): Promise\ + +Checks whether this page contains images. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ----------------- | --------------------------------------- | +| Promise\ | Promise used to return the result.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web compoent. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('hasImagePm') + .onClick(() => { + try { + this.controller.hasImage().then((data) => { + console.info('hasImage: ' + data); + }) + .catch(function (error) { + console.error("error: " + error); + }) + } catch (error) { + console.error(`Errorcode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### removeCache + +removeCache(clearRom: boolean): void + +Clears the cache in the application. This API will clear the cache for all webviews in the same application. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | -------------------------------------------------------- | +| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **true** means to clear the cache in the ROM and RAM at the same time, and **false** means to only clear the cache in the RAM.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('removeCache') + .onClick(() => { + try { + this.controller.removeCache(false); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getBackForwardEntries + +getBackForwardEntries(): BackForwardList + +Obtains the historical information list of the current webview. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ----------------------------------- | --------------------------- | +| [BackForwardList](#backforwardlist) | Historical information list of the current webview.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------------ | +| 17100001 | Init error. The WebviewController must be associated with a Web component. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getBackForwardEntries') + .onClick(() => { + try { + let list = this.controller.getBackForwardEntries() + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### customizeSchemes + +static customizeSchemes(schemes: Array\): void + +Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\** component is initialized. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------- | ---- | -------------------------------------- | +| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + responseweb: WebResourceResponse = new WebResourceResponse() + scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true} + scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true} + scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true} + + aboutToAppear():void { + try { + web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]) + } catch(error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + } + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onInterceptRequest((event) => { + console.log('url:' + event.request.getRequestUrl()) + return this.responseweb + }) + } + } +} +``` + +## WebCookieManager + +Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance. + +### getCookie + +static getCookie(url: string): string + +Obtains the cookie value corresponding to the specified URL. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | :------------------------ | +| url | string | Yes | URL of the cookie value to obtain.| + +**Return value** + +| Type | Description | +| ------ | ------------------------- | +| string | Cookie value corresponding to the specified URL.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100002 | Invalid url. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getCookie') + .onClick(() => { + try { + let value = web_webview.WebCookieManager.getCookie('www.example.com'); + console.log("value: " + value); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### setCookie + +static setCookie(url: string, value: string): void + +Sets a cookie value for the specified URL. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | :------------------------ | +| url | string | Yes | URL of the cookie to set.| +| value | string | Yes | Cookie value to set. | + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100002 | Invalid url. | +| 17100005 | Invalid cookie value. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('setCookie') + .onClick(() => { + try { + web_webview.WebCookieManager.setCookie('www.example.com', 'a=b'); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### saveCookieAsync + +static saveCookieAsync(callback: AsyncCallback\): void + +Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | :------------------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the operation result.| + + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('saveCookieAsync') + .onClick(() => { + try { + web_webview.WebCookieManager.saveCookieAsync((error) => { + if (error) { + console.log("error: " + error); + } + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### saveCookieAsync + +static saveCookieAsync(): Promise\ + +Saves the cookies in the memory to the drive. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ---------------- | ----------------------------------------- | +| Promise\ | Promise used to return the operation result.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('saveCookieAsync') + .onClick(() => { + try { + web_webview.WebCookieManager.saveCookieAsync() + .then(() => { + console.log("saveCookieAsyncCallback success!"); + }) + .catch((error) => { + console.error("error: " + error); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### putAcceptCookieEnabled + +static putAcceptCookieEnabled(accept: boolean): void + +Sets whether the **WebCookieManager** instance has the permission to send and receive cookies. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | :----------------------------------- | +| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('putAcceptCookieEnabled') + .onClick(() => { + try { + web_webview.WebCookieManager.putAcceptCookieEnabled(false); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### isCookieAllowed + +static isCookieAllowed(): boolean + +Checks whether the **WebCookieManager** instance has the permission to send and receive cookies. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------- | -------------------------------- | +| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('isCookieAllowed') + .onClick(() => { + let result = web_webview.WebCookieManager.isCookieAllowed(); + console.log("result: " + result); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### putAcceptThirdPartyCookieEnabled + +static putAcceptThirdPartyCookieEnabled(accept: boolean): void + +Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | :----------------------------------------- | +| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('putAcceptThirdPartyCookieEnabled') + .onClick(() => { + try { + web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### isThirdPartyCookieAllowed + +static isThirdPartyCookieAllowed(): boolean + +Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------- | -------------------------------------- | +| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('isThirdPartyCookieAllowed') + .onClick(() => { + let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed(); + console.log("result: " + result); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### existCookie + +static existCookie(): boolean + +Checks whether cookies exist. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------- | -------------------------------------- | +| boolean | Whether cookies exist.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('existCookie') + .onClick(() => { + let result = web_webview.WebCookieManager.existCookie(); + console.log("result: " + result); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### deleteEntireCookie + +static deleteEntireCookie(): void + +Deletes all cookies. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('deleteEntireCookie') + .onClick(() => { + web_webview.WebCookieManager.deleteEntireCookie(); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### deleteSessionCookie + +static deleteSessionCookie(): void + +Deletes all session cookies. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview' + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('deleteSessionCookie') + .onClick(() => { + web_webview.WebCookieManager.deleteSessionCookie(); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +## WebStorage + +Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **\** components in an application share a **WebStorage** object. + +### deleteOrigin + +static deleteOrigin(origin : string): void + +Deletes all data in the specified origin. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------ | +| origin | string | Yes | Index of the origin.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('deleteOrigin') + .onClick(() => { + try { + web_webview.WebStorage.deleteOrigin(this.origin); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +### getOrigins + +static getOrigins(callback: AsyncCallback\>) : void + +Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------ | +| callback | AsyncCallback\> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100012 | Invalid web storage origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getOrigins') + .onClick(() => { + try { + web_webview.WebStorage.getOrigins((error, origins) => { + if (error) { + console.log('error: ' + JSON.stringify(error)); + return; + } + for (let i = 0; i < origins.length; i++) { + console.log('origin: ' + origins[i].origin); + console.log('usage: ' + origins[i].usage); + console.log('quota: ' + origins[i].quota); + } + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +### getOrigins + +static getOrigins() : Promise\> + +Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| -------------------------------- | ------------------------------------------------------------ | +| Promise\> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100012 | Invalid web storage origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getOrigins') + .onClick(() => { + try { + web_webview.WebStorage.getOrigins() + .then(origins => { + for (let i = 0; i < origins.length; i++) { + console.log('origin: ' + origins[i].origin); + console.log('usage: ' + origins[i].usage); + console.log('quota: ' + origins[i].quota); + } + }) + .catch(e => { + console.log('error: ' + JSON.stringify(e)); + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +### getOriginQuota + +static getOriginQuota(origin : string, callback : AsyncCallback\) : void + +Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------ | +| origin | string | Yes | Index of the origin.| +| callback | AsyncCallback\ | Yes | Storage quota of the origin. | + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('getOriginQuota') + .onClick(() => { + try { + web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => { + if (error) { + console.log('error: ' + JSON.stringify(error)); + return; + } + console.log('quota: ' + quota); + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +### getOriginQuota + +static getOriginQuota(origin : string) : Promise\ + +Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| origin | string | Yes | Index of the origin.| + +**Return value** + +| Type | Description | +| --------------- | --------------------------------------- | +| Promise\ | Promise used to return the storage quota of the origin.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('getOriginQuota') + .onClick(() => { + try { + web_webview.WebStorage.getOriginQuota(this.origin) + .then(quota => { + console.log('quota: ' + quota); + }) + .catch(e => { + console.log('error: ' + JSON.stringify(e)); + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +### getOriginUsage + +static getOriginUsage(origin : string, callback : AsyncCallback\) : void + +Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------ | +| origin | string | Yes | Index of the origin.| +| callback | AsyncCallback\ | Yes | Storage usage of the origin. | + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('getOriginUsage') + .onClick(() => { + try { + web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => { + if (error) { + console.log('error: ' + JSON.stringify(error)); + return; + } + console.log('usage: ' + usage); + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +### getOriginUsage + +static getOriginUsage(origin : string) : Promise\ + +Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| origin | string | Yes | Index of the origin.| + +**Return value** + +| Type | Description | +| --------------- | ------------------------------------- | +| Promise\ | Promise used to return the storage usage of the origin.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ----------------------------------------------------- | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('getOriginUsage') + .onClick(() => { + try { + web_webview.WebStorage.getOriginUsage(this.origin) + .then(usage => { + console.log('usage: ' + usage); + }) + .catch(e => { + console.log('error: ' + JSON.stringify(e)); + }) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +### deleteAllData + +static deleteAllData(): void + +Deletes all data in the Web SQL Database. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('deleteAllData') + .onClick(() => { + try { + web_webview.WebStorage.deleteAllData(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } +} +``` + +## WebDataBase + +Implements a **WebDataBase** object. + +### getHttpAuthCredentials + +static getHttpAuthCredentials(host: string, realm: string): Array\ + +Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------------- | +| host | string | Yes | Host to which HTTP authentication credentials apply.| +| realm | string | Yes | Realm to which HTTP authentication credentials apply. | + +**Return value** + +| Type | Description | +| ----- | -------------------------------------------- | +| Array\ | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + host: string = "www.spincast.org"; + realm: string = "protected example"; + username_password: string[]; + + build() { + Column() { + Button('getHttpAuthCredentials') + .onClick(() => { + try { + this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm); + console.log('num: ' + this.username_password.length); + ForEach(this.username_password, (item) => { + console.log('username_password: ' + item); + }, item => item) + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### saveHttpAuthCredentials + +static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void + +Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------------- | +| host | string | Yes | Host to which HTTP authentication credentials apply.| +| realm | string | Yes | Realm to which HTTP authentication credentials apply. | +| username | string | Yes | User name. | +| password | string | Yes | Password. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + host: string = "www.spincast.org"; + realm: string = "protected example"; + + build() { + Column() { + Button('saveHttpAuthCredentials') + .onClick(() => { + try { + web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche"); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### existHttpAuthCredentials + +static existHttpAuthCredentials(): boolean + +Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ------- | ------------------------------------------------------------ | +| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('existHttpAuthCredentials') + .onClick(() => { + try { + let result = web_webview.WebDataBase.existHttpAuthCredentials(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### deleteHttpAuthCredentials + +static deleteHttpAuthCredentials(): void + +Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('deleteHttpAuthCredentials') + .onClick(() => { + try { + web_webview.WebDataBase.deleteHttpAuthCredentials(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +## WebAsyncController + +Implements a **WebAsyncController** object, which can be used to control the behavior of a **\** component with asynchronous callbacks. A **WebAsyncController **object controls one **\** component. + +### Creating an Object + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + webAsyncController: web_webview.WebAsyncController = new web_webview.WebAsyncController(this.controller) + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + +### constructor9+ + +constructor(controller: WebController) + +Implements a **WebAsyncController** by binding it with a [WebController](../arkui-ts/ts-basic-components-web.md#webcontroller) object. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| ----- | ---- | ---- | --- | +| controller | [WebController](../arkui-ts/ts-basic-components-web.md#webcontroller) | Yes| **WebviewController** to bind.| + +### storeWebArchive9+ + +storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\): void + +Stores this web page. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | +| callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise.| + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController() + build() { + Column() { + Button('saveWebArchive') + .onClick(() => { + let webAsyncController = new web_webview.WebAsyncController(this.controller) + webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { + if (filename != null) { + console.info(`save web archive success: ${filename}`) + } + }) + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + +### storeWebArchive9+ + +storeWebArchive(baseName: string, autoName: boolean): Promise\ + +Stores this web page. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| baseName | string | Yes| Save path. The value cannot be null. | +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. | + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the save path if the operation is successful and null otherwise. | + +**Example** + + ```ts + // xxx.ets + import web_webview from '@ohos.web.webview' + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + build() { + Column() { + Button('saveWebArchive') + .onClick(() => { + let webAsyncController = new web_webview.WebAsyncController(this.controller); + webAsyncController.storeWebArchive("/data/storage/el2/base/", true) + .then(filename => { + if (filename != null) { + console.info(`save web archive success: ${filename}`) + } + }) + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + +## GeolocationPermissions + +Implements a **GeolocationPermissions** object. + +### allowGeolocation + +static allowGeolocation(origin: string): void + +Allows the specified origin to use the geolocation information. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| origin | string | Yes |Index of the origin.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('allowGeolocation') + .onClick(() => { + try { + web_webview.GeolocationPermissions.allowGeolocation(this.origin); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### deleteGeolocation + +static deleteGeolocation(origin: string): void + +Clears the geolocation permission status of a specified origin. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| origin | string | Yes | Index of the origin.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('deleteGeolocation') + .onClick(() => { + try { + web_webview.GeolocationPermissions.deleteGeolocation(this.origin); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getAccessibleGeolocation + +static getAccessibleGeolocation(origin: string, callback: AsyncCallback\): void + +Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------- | ---- | ------------------------------------------------------------ | +| origin | string | Yes | Index of the origin. | +| callback | AsyncCallback\ | Yes | Callback used to return the geolocation permission status of the specified origin. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified origin is not found.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('getAccessibleGeolocation') + .onClick(() => { + try { + web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => { + if (error) { + console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error)); + return; + } + console.log('getAccessibleGeolocationAsync result: ' + result); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getAccessibleGeolocation + +static getAccessibleGeolocation(origin: string): Promise\ + +Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type| Mandatory| Description | +| ------ | -------- | ---- | -------------------- | +| origin | string | Yes | Index of the origin.| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the geolocation permission status of the specified origin. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified origin is not found.| + +**Error codes** + +For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md). + +| ID| Error Message | +| -------- | ------------------------------------------------------ | +| 17100011 | Invalid origin. | + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + origin: string = "file:///"; + + build() { + Column() { + Button('getAccessibleGeolocation') + .onClick(() => { + try { + web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin) + .then(result => { + console.log('getAccessibleGeolocationPromise result: ' + result); + }).catch(error => { + console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error)); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getStoredGeolocation + +static getStoredGeolocation(callback: AsyncCallback\>): void + +Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ---------------------------------------- | +| callback | AsyncCallback\> | Yes | Callback used to return the geolocation permission status of all origins.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getStoredGeolocation') + .onClick(() => { + try { + web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => { + if (error) { + console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error)); + return; + } + let origins_str: string = origins.join(); + console.log('getStoredGeolocationAsync origins: ' + origins_str); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### getStoredGeolocation + +static getStoredGeolocation(): Promise\> + +Obtains the geolocation permission status of all origins. This API uses a promise to return the result. + +**System capability**: SystemCapability.Web.Webview.Core + +**Return value** + +| Type | Description | +| ---------------------- | --------------------------------------------------------- | +| Promise\> | Promise used to return the geolocation permission status of all origins.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('getStoredGeolocation') + .onClick(() => { + try { + web_webview.GeolocationPermissions.getStoredGeolocation() + .then(origins => { + let origins_str: string = origins.join(); + console.log('getStoredGeolocationPromise origins: ' + origins_str); + }).catch(error => { + console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error)); + }); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +### deleteAllGeolocation + +static deleteAllGeolocation(): void + +Clears the geolocation permission status of all sources. + +**System capability**: SystemCapability.Web.Webview.Core + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + + build() { + Column() { + Button('deleteAllGeolocation') + .onClick(() => { + try { + web_webview.GeolocationPermissions.deleteAllGeolocation(); + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` +## HeaderV9 +Describes the request/response header returned by the **\** component. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable|Description | +| ----------- | ------ | -----|------|------------------- | +| headerKey | string | Yes| Yes| Key of the request/response header. | +| headerValue | string | Yes| Yes| Value of the request/response header.| + +## HitTestTypeV9 + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Value| Description | +| ------------- | -- |----------------------------------------- | +| EditText | 0 |Editable area. | +| Email | 1 |Email address. | +| HttpAnchor | 2 |Hyperlink whose **src** is **http**. | +| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is **http**.| +| Img | 4 |HTML::img tag. | +| Map | 5 |Geographical address. | +| Phone | 6 |Phone number. | +| Unknown | 7 |Unknown content. | + +## HitTestValue + +Provides the element information of the area being clicked. For details about the sample code, see **getHitTestValue**. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name| Type| Readable| Writable| Description| +| ---- | ---- | ---- | ---- |---- | +| type | [HitTestTypeV9](#hittesttypev9) | Yes| No| Element type of the area being clicked.| +| extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.| + +## WebMessage + +Describes the data types supported for [WebMessagePort](#webmessageport). + +| Type | Description | +| -------- | -------------------------------------- | +| string | String type.| +| ArrayBuffer | Binary type.| + +## WebStorageOrigin + +Provides usage information of the Web SQL Database. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description| +| ------ | ------ | ---- | ---- | ---- | +| origin | string | Yes | No| Index of the origin.| +| usage | number | Yes | No| Storage usage of the origin. | +| quota | number | Yes | No| Storage quota of the origin. | + +## BackForwardList + +Provides the historical information list of the current webview. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| ------------ | ------ | ---- | ---- | ---------------------------- | +| currentIndex | number | Yes | No | Index of the current page in the page history stack.| +| size | number | Yes | No | Number of indexes in the history stack. | + +### getItemAtIndex + +getItemAtIndex(index: number): HistoryItem + +Obtains the page record with the specified index in the history stack. + +**System capability**: SystemCapability.Web.Webview.Core + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------------- | +| index | number | Yes | Index of the target page record in the history stack.| + +**Return value** + +| Type | Description | +| --------------------------- | ------------ | +| [HistoryItem](#historyitem) | Historical page record.| + +**Example** + +```ts +// xxx.ets +import web_webview from '@ohos.web.webview'; +import image from "@ohos.multimedia.image" + +@Entry +@Component +struct WebComponent { + controller: web_webview.WebviewController = new web_webview.WebviewController(); + @State icon: image.PixelMap = undefined; + + build() { + Column() { + Button('getBackForwardEntries') + .onClick(() => { + try { + let list = this.controller.getBackForwardEntries(); + let historyItem = list.getItemAtIndex(list.currentIndex); + console.log("HistoryItem: " + JSON.stringify(historyItem)); + this.icon = historyItem.icon; + } catch (error) { + console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); + } + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } +} +``` + +## HistoryItem + +Describes a historical page record. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| ------------- | -------------------------------------- | ---- | ---- | ---------------------------- | +| icon | [PixelMap](js-apis-image.md#pixelmap7) | Yes | No | **PixelMap** object of the icon on the historical page.| +| historyUrl | string | Yes | No | URL of the historical page. | +| historyRawUrl | string | Yes | No | Original URL of the historical page. | +| title | string | Yes | No | Title of the historical page. | + +## WebCustomScheme + +Defines a custom URL scheme. + +**System capability**: SystemCapability.Web.Webview.Core + +| Name | Type | Readable| Writable| Description | +| -------------- | --------- | ---- | ---- | ---------------------------- | +| schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters and include only lowercase letters, digits, periods (.), plus signs (+), and hyphens (-). | +| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). | +| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. | diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index a8221a78898accf8d18724193df311a13693b998..6af6bc0a51e3a862a159b6bf450c9ce90bd31346 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifi (WLAN) + The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -166,20 +168,17 @@ Represents WLAN hotspot information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| Service set identifier (SSID) of the hotspot, in UTF-8 format.| -| bssid | string | Read only| Basic service set identifier (BSSID) of the hotspot.| -| capabilities | string | Read only| Hotspot capabilities.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| WLAN security type.| -| rssi | number | Read only| Received signal strength indicator (RSSI) of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN access point (AP).| -| frequency | number | Read only| Frequency of the WLAN AP.| -| channelWidth | number | Read only| Channel width of the WLAN AP.| -| centerFrequency09+ | number | Read only| Center frequency of the hotspot.| -| centerFrequency19+ | number | Read only| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| -| infoElems9+ | Array<[WifiInfoElem](#wifiinfoelem9)> | Read only| Information elements.| -| timestamp | number | Read only| Timestamp.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| +| capabilities | string | Yes| No| Hotspot capabilities.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| +| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| timestamp | number | Yes| No| Timestamp.| ## WifiSecurityType @@ -189,50 +188,13 @@ Enumerates the WLAN security types. **System capability**: SystemCapability.Communication.WiFi.Core -| **Name**| **Default Value**| **Description**| +| **Name**| **Value**| **Description**| | -------- | -------- | -------- | | WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| | WIFI_SEC_TYPE_OPEN | 1 | Open security type.| | WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| | WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| | WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| -| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| -| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| -| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| -| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| -| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| - - -## WifiInfoElem9+ - -Represents a WLAN information element. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| eid | number | Read only| ID of the information element.| -| content | Uint8Array | Read only| Content of the information element.| - - -## WifiChannelWidth9+ - -Enumerates the WLAN channel widths. - -**System capability**: SystemCapability.Communication.WiFi.STA - - -| **Name**| **Default Value**| **Description**| -| -------- | -------- | -------- | -| WIDTH_20MHZ | 0 | 20 MHz.| -| WIDTH_40MHZ | 1 | 40 MHz.| -| WIDTH_80MHZ | 2 | 80 MHz.| -| WIDTH_160MHZ | 3 | 160 MHz.| -| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| -| WIDTH_INVALID | 5 | Invalid value.| ## wifi.getScanInfosSync9+ @@ -274,7 +236,7 @@ Adds network configuration. This API uses a promise to return the result. | **Type**| **Description**| | -------- | -------- | - | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| + | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the network configuration fails to be added.| ## WifiDeviceConfig @@ -283,33 +245,32 @@ Represents the WLAN configuration. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| isHiddenSsid | boolean | Read only| Whether the network is hidden.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| creatorUid | number | Read only| ID of the creator.
**System API**: This is a system API.| -| disableReason | number | Read only| Reason for disabling WLAN.
**System API**: This is a system API.| -| netId | number | Read only| Network ID.
**System API**: This is a system API.| -| randomMacType | number | Read only| Random MAC type.
**System API**: This is a system API.| -| randomMacAddr | string | Read only| Random MAC address.
**System API**: This is a system API.| -| ipType | [IpType](#iptype7) | Read only| IP address type.
**System API**: This is a system API.| -| staticIp | [IpConfig](#ipconfig7) | Read only| Static IP address configuration.
**System API**: This is a system API.| -| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Read only| EAP configuration.
**System API**: This is a system API.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype7) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig7) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| ## IpType7+ -Enumerates the IP address types. +Enumerate the IP address types. **System API**: This is a system API. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | STATIC | 0 | Static IP address.| | DHCP | 1 | IP address allocated by DHCP.| @@ -324,78 +285,12 @@ Represents IP configuration information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| dnsServers | number[] | Read only| Domain name server (DNS) information.| -| domains | Array<string> | Read only| Domain information.| - - -## WifiEapConfig9+ - -Represents EAP configuration information. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| eapMethod | [EapMethod](#eapmethod9) | Read only| EAP authentication method.| -| phase2Method | [Phase2Method](#phase2method9) | Read only| Phase 2 authentication method.| -| identity | string | Read only| Identity Information.| -| anonymousIdentity | string | Read only| Anonymous identity.| -| password | string | Read only| Password.| -| caCertAliases | string | Read only| CA certificate alias.| -| caPath | string | Read only| CA certificate path.| -| clientCertAliases | string | Read only| Client certificate alias.| -| altSubjectMatch | string | Read only| A string to match the alternate subject.| -| domainSuffixMatch | string | Read only| A string to match the domain suffix.| -| realm | string | Read only| Realm for the passpoint credential.| -| plmn | string | Read only| Public land mobile network (PLMN) of the passpoint credential provider.| -| eapSubId | number | Read only| Sub-ID of the SIM card.| - - -## EapMethod9+ - -Enumerates the EAP authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| EAP_NONE | 0 | Not specified.| -| EAP_PEAP | 1 | PEAP.| -| EAP_TLS | 2 | TLS.| -| EAP_TTLS | 3 | TTLS.| -| EAP_PWD | 4 | Password.| -| EAP_SIM | 5 | SIM.| -| EAP_AKA | 6 | AKA.| -| EAP_AKA_PRIME | 7 | AKA Prime.| -| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| - - -## Phase2Method9+ - -Enumerates the Phase 2 authentication methods. - -**System API**: This is a system API. - -**System capability**: SystemCapability.Communication.WiFi.STA - -| Name| Default Value| Description| -| -------- | -------- | -------- | -| PHASE2_NONE | 0 | Not specified.| -| PHASE2_PAP | 1 | PAP.| -| PHASE2_MSCHAP | 2 | MS-CHAP.| -| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| -| PHASE2_GTC | 4 | GTC .| -| PHASE2_SIM | 5 | SIM.| -| PHASE2_AKA | 6 | AKA.| -| PHASE2_AKA_PRIME | 7 | AKA Prime.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| ## wifi.addDeviceConfig @@ -500,122 +395,6 @@ Removes the configuration of an untrusted network. This API uses an asynchronous | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig): Promise<number> - -Adds the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<number> | Promise used to return the network configuration ID.| - - -## wifi.addCandidateConfig9+ - -addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void - -Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| - | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number): Promise<void> - -Removes the configuration of a candidate network. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - | Promise<void> | Promise used to return the result.| - - -## wifi.removeCandidateConfig9+ - -removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void - -Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the network configuration to remove.| -| callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| - - -## wifi.getCandidateConfigs9+ - -getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> - -Obtains candidate network configuration. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Return value** - - | **Type**| **Description**| - | -------- | -------- | - |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| - - -## wifi.connectToCandidateConfig9+ - -connectToCandidateConfig(networkId: number): void - -Connects to a candidate network. - -**Required permissions**: ohos.permission.SET_WIFI_INFO - -**System capability**: SystemCapability.Communication.WiFi.STA - -**Parameters** - - | **Name**| **Type**| **Mandatory**| **Description**| - | -------- | -------- | -------- | -------- | - | networkId | number | Yes| ID of the candidate network configuration.| - - ## wifi.connectToNetwork connectToNetwork(networkId: number): boolean @@ -725,7 +504,7 @@ Obtains WLAN connection information. This API uses a promise to return the resul | Type| Description| | -------- | -------- | - | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information.| ## wifi.getLinkedInfo @@ -770,24 +549,23 @@ Represents the WLAN connection information. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| bssid | string | Read only| BSSID of the hotspot.| -| networkId | number | Read only| Network configuration ID.
**System API**: This is a system API.| -| rssi | number | Read only| RSSI of the hotspot, in dBm.| -| band | number | Read only| Frequency band of the WLAN AP.| -| linkSpeed | number | Read only| Speed of the WLAN AP.| -| frequency | number | Read only| Frequency of the WLAN AP.| -| isHidden | boolean | Read only| Whether to hide the WLAN AP.| -| isRestricted | boolean | Read only| Whether to restrict data volume at the WLAN AP.| -| chload | number | Read only| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| -| snr | number | Read only| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| -| macType9+ | number | Read only| MAC address type.| -| macAddress | string | Read only| MAC address of the device.| -| ipAddress | number | Read only| IP address of the device that sets up the WLAN connection.| -| suppState | [SuppState](#suppstate) | Read only| Supplicant state.
**System API**: This is a system API.| -| connState | [ConnState](#connstate) | Read only| WLAN connection state.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| ## ConnState @@ -796,7 +574,7 @@ Enumerates the WLAN connection states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SCANNING | 0 | The device is scanning for available APs.| | CONNECTING | 1 | A WLAN connection is being established.| @@ -816,7 +594,7 @@ Enumerates the supplicant states. **System capability**: SystemCapability.Communication.WiFi.STA -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | The supplicant is disconnected from the AP.| | INTERFACE_DISABLED | 1 | The network interface is disabled.| @@ -871,16 +649,16 @@ Obtains the features supported by this device. | Value| Description| | -------- | -------- | -| 0x0001 | WLAN infrastructure mode. | -| 0x0002 | 5 GHz feature. | -| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature. | -| 0x0008 | Wi-Fi Direct. | -| 0x0010 | SoftAP. | -| 0x0040 | Wi-Fi AWare. | -| 0x8000 | WLAN AP/STA concurrency. | -| 0x8000000 | WPA3 Personal (WPA-3 SAE). | -| 0x10000000 | WPA3-Enterprise Suite B. | -| 0x20000000 | Enhanced open feature. | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| ## wifi.isFeatureSupported7+ @@ -949,15 +727,15 @@ Represents IP information. **System capability**: SystemCapability.Communication.WiFi.STA -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ipAddress | number | Read only| IP address.| -| gateway | number | Read only| Gateway.| -| netmask | number | Read only| Subnet mask.| -| primaryDns | number | Read only| IP address of the preferred DNS server.| -| secondDns | number | Read only| IP address of the alternate DNS server.| -| serverIp | number | Read only| IP address of the DHCP server.| -| leaseDuration | number | Read only| Lease duration of the IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| ## wifi.getCountryCode7+ @@ -1237,13 +1015,13 @@ Represents the hotspot configuration. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| ssid | string | Read only| SSID of the hotspot, in UTF-8 format.| -| securityType | [WifiSecurityType](#wifisecuritytype) | Read only| Security type.| -| band | number | Read only| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| -| preSharedKey | string | Read only| PSK of the hotspot.| -| maxConn | number | Read only| Maximum number of connections allowed.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| ## wifi.getHotspotConfig7+ @@ -1292,11 +1070,11 @@ Represents the station information. **System capability**: SystemCapability.Communication.WiFi.AP.Core -| **Name**| **Type**| **Readable/Writable**| **Description**| -| -------- | -------- | -------- | -------- | -| name | string | Read only| Device name.| -| macAddress | string | Read only| MAC address.| -| ipAddress | string | Read only| IP address.| +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| ## wifi.getP2pLinkedInfo8+ @@ -1323,11 +1101,11 @@ Represents the P2P link information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| connectState | [P2pConnectState](#p2pconnectstate8) | Read only| P2P connection state.| -| isGroupOwner | boolean | Read only| Whether the device is the group owner.| -| groupOwnerAddr | string | Read only| MAC address of the group. +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate8) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. ## P2pConnectState8+ @@ -1336,7 +1114,7 @@ Enumerates the P2P connection states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | DISCONNECTED | 0 | Disconnected.| | CONNECTED | 1 | Connected.| @@ -1373,7 +1151,7 @@ Obtains the current P2P group information. This API uses a promise to return the | Type| Description| | -------- | -------- | - | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the P2P group information obtained.| ## wifi.getCurrentGroup8+ @@ -1433,13 +1211,13 @@ Represents the P2P device information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceName | string | Read only| Device name.| -| deviceAddress | string | Read only| MAC address of the device.| -| primaryDeviceType | string | Read only| Type of the primary device.| -| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Read only| Device status.| -| groupCapabilitys | number | Read only| Group capabilities.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address of the device.| +| primaryDeviceType | string | Yes| No| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus8) | Yes| No| Device status.| +| groupCapabilitys | number | Yes| No| Group capabilities.| ## P2pDeviceStatus8+ @@ -1448,7 +1226,7 @@ Enumerates the P2P device states. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | CONNECTED | 0 | Connected.| | INVITED | 1 | Invited.| @@ -1457,40 +1235,6 @@ Enumerates the P2P device states. | UNAVAILABLE | 4 | Unavailable.| -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(): Promise<WifiP2pDevice> - -Obtains the local device information in the P2P connection. This API uses a promise to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| - - -## wifi.getP2pLocalDevice9+ - -getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void - -Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| - - ## wifi.createGroup8+ createGroup(config: WifiP2PConfig): boolean @@ -1520,13 +1264,13 @@ Represents P2P group configuration. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| deviceAddress | string | Read only| Device address.| -| netId | number | Read only| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| -| passphrase | string | Read only| Passphrase of the group.| -| groupName | string | Read only| Name of the group.| -| goBand | [GroupOwnerBand](#groupownerband8) | Read only| Frequency band of the group.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| groupName | string | Yes| No| Name of the group.| +| goBand | [GroupOwnerBand](#groupownerband8) | Yes| No| Frequency band of the group.| ## GroupOwnerBand8+ @@ -1535,7 +1279,7 @@ Enumerates the P2P group frequency bands. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | GO_BAND_AUTO | 0 | Auto.| | GO_BAND_2GHZ | 1 | 2 GHz.| @@ -1727,61 +1471,23 @@ Deletes a persistent group. | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| -## wifi.getP2pGroups9+ - -getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> - -Obtains information about all P2P groups. This API uses a promise to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Return value** - - | Type| Description| - | -------- | -------- | - | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| - - ## WifiP2pGroupInfo8+ Represents the P2P group information. **System capability**: SystemCapability.Communication.WiFi.P2P -| Name| Type| Readable/Writable| Description| -| -------- | -------- | -------- | -------- | -| isP2pGo | boolean | Read only| Whether the device is the group owner.| -| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Read only| Device information of the group.| -| passphrase | string | Read only| Passphrase of the group.| -| interface | string | Read only| Interface name.| -| groupName | string | Read only| Group name.| -| networkId | number | Read only| Network ID.| -| frequency | number | Read only| Frequency of the group.| -| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Read only| List of connected devices.| -| goIpAddress | string | Read only| IP address of the group.| - - -## wifi.getP2pGroups9+ - -getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void - -Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. - -**System API**: This is a system API. - -**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION - -**System capability**: SystemCapability.Communication.WiFi.P2P - -**Parameters** - - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice8) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice8) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| ## wifi.setDeviceName8+ @@ -1830,10 +1536,10 @@ Registers the WLAN state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('wifiStateChange')7+ @@ -2012,10 +1718,10 @@ Registers the hotspot state change events. | **Value**| **Description**| | -------- | -------- | -| 0 | Deactivated. | -| 1 | Activated. | -| 2 | Activating. | -| 3 | Deactivating. | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| ## wifi.off('hotspotStateChange')7+ @@ -2057,11 +1763,11 @@ Registers the P2P state change events. | **Value**| **Description**| | -------- | -------- | -| 1 | Available. | -| 2 | Opening. | -| 3 | Opened. | -| 4 | Closing. | -| 5 | Closed. | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| ## wifi.off('p2pStateChange')8+ diff --git a/en/application-dev/reference/apis/js-apis-wifiManager.md b/en/application-dev/reference/apis/js-apis-wifiManager.md new file mode 100644 index 0000000000000000000000000000000000000000..8e3526343a3f62066af7686b4fbe5cb587fa1cbc --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManager.md @@ -0,0 +1,2187 @@ +# WLAN + +The **WLAN** module provides basic wireless local area network (WLAN) functions, peer-to-peer (P2P) functions, and WLAN message notification services. It allows applications to communicate with other devices over WLAN. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. + + +## Modules to Import + +```js +import wifiManager from '@ohos.wifiManager'; +``` + +## wifi.enableWifi9+ + +enableWifi(): void + +Enables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableWifi9+ + +disableWifi(): void + +Disables WLAN. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isWifiActive9+ + +isWifiActive(): boolean + +Checks whether WLAN is enabled. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| + + +## wifi.scan9+ + +scan(): void + +Starts a scan for WLAN. + +**Required permissions**: **ohos.permission.SET_WIFI_INFO** and **ohos.permission.LOCATION** + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getScanResults9+ + +getScanResults(): Promise<Array<WifiScanInfo>> + +Obtains the scan result. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| + + +## wifi.getScanResults9+ + +getScanResults(callback: AsyncCallback<Array<WifiScanInfo>>): void + +Obtains the scan result. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getScanInfos((err, result) => { + if (err) { + console.error("get scan info error"); + return; + } + + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + + wifi.getScanInfos().then(result => { + var len = Object.keys(result).length; + console.log("wifi received scan info: " + len); + for (var i = 0; i < len; ++i) { + console.info("ssid: " + result[i].ssid); + console.info("bssid: " + result[i].bssid); + console.info("capabilities: " + result[i].capabilities); + console.info("securityType: " + result[i].securityType); + console.info("rssi: " + result[i].rssi); + console.info("band: " + result[i].band); + console.info("frequency: " + result[i].frequency); + console.info("channelWidth: " + result[i].channelWidth); + console.info("timestamp: " + result[i].timestamp); + } + }); + ``` + + +## WifiScanInfo9+ + +Represents WLAN hotspot information. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| Service set identifier (SSID) of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| Basic service set identifier (BSSID) of the hotspot.| +| capabilities | string | Yes| No| Hotspot capabilities.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| WLAN security type.| +| rssi | number | Yes| No| Received signal strength indicator (RSSI) of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN access point (AP).| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| channelWidth | number | Yes| No| Channel width of the WLAN AP.| +| centerFrequency0 | number | Yes| No| Center frequency of the hotspot.| +| centerFrequency1 | number | Yes| No| Center frequency of the hotspot. If the hotspot uses two non-overlapping WLAN channels, two center frequencies, namely **centerFrequency0** and **centerFrequency1**, are returned.| +| infoElems | Array<[WifiInfoElem](#wifiinfoelem9)> | Yes| No| Information elements.| +| timestamp | number | Yes| No| Timestamp.| + + +## WifiSecurityType9+ + +Enumerates the WLAN security types. + +**System capability**: SystemCapability.Communication.WiFi.Core + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIFI_SEC_TYPE_INVALID | 0 | Invalid security type.| +| WIFI_SEC_TYPE_OPEN | 1 | Open security type.| +| WIFI_SEC_TYPE_WEP | 2 | Wired Equivalent Privacy (WEP).| +| WIFI_SEC_TYPE_PSK | 3 | Pre-shared key (PSK).| +| WIFI_SEC_TYPE_SAE | 4 | Simultaneous Authentication of Equals (SAE).| +| WIFI_SEC_TYPE_EAP9+ | 5 | Extensible Authentication protocol (EAP).| +| WIFI_SEC_TYPE_EAP_SUITE_B9+ | 6 | Suite B 192-bit encryption.| +| WIFI_SEC_TYPE_OWE9+ | 7 | Opportunistic Wireless Encryption (OWE).| +| WIFI_SEC_TYPE_WAPI_CERT9+ | 8 | WLAN Authentication and Privacy Infrastructure (WAPI) in certificate-based mode (WAPI-CERT).| +| WIFI_SEC_TYPE_WAPI_PSK9+ | 9 | WAPI-PSK.| + + +## WifiInfoElem9+ + +Represents a WLAN information element. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eid | number | Yes| No| ID of the information element.| +| content | Uint8Array | Yes| No| Content of the information element.| + + +## WifiChannelWidth9+ + +Enumerates the WLAN channel widths. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Value**| **Description**| +| -------- | -------- | -------- | +| WIDTH_20MHZ | 0 | 20 MHz.| +| WIDTH_40MHZ | 1 | 40 MHz.| +| WIDTH_80MHZ | 2 | 80 MHz.| +| WIDTH_160MHZ | 3 | 160 MHz.| +| WIDTH_80MHZ_PLUS | 4 | 80 MHz+.| +| WIDTH_INVALID | 5 | Invalid value.| + + +## wifi.getScanResultsSync9+ + +getScanResultsSync():  Array<[WifiScanInfo](#wifiscaninfo)> + +Obtains the scan result. This API returns the result synchronously. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_PEERS_MAC (or ohos.permission.LOCATION) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig): Promise<number> + +Adds network configuration. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the ID of the added network configuration. If **-1** is returned, the network configuration fails to be added.| + +## WifiDeviceConfig9+ + +Represents the WLAN configuration. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| isHiddenSsid | boolean | Yes| No| Whether the network is hidden.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| creatorUid | number | Yes| No| ID of the creator.
**System API**: This is a system API.| +| disableReason | number | Yes| No| Reason for disabling WLAN.
**System API**: This is a system API.| +| netId | number | Yes| No| Network ID.
**System API**: This is a system API.| +| randomMacType | number | Yes| No| Random MAC type.
**System API**: This is a system API.| +| randomMacAddr | string | Yes| No| Random MAC address.
**System API**: This is a system API.| +| ipType | [IpType](#iptype9) | Yes| No| IP address type.
**System API**: This is a system API.| +| staticIp | [IpConfig](#ipconfig9) | Yes| No| Static IP address configuration.
**System API**: This is a system API.| +| eapConfig9+ | [WifiEapConfig](#wifieapconfig9) | Yes| No| EAP configuration.
**System API**: This is a system API.| + + +## IpType9+ + +Enumerates the IP address types. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + + +| Name| Value| Description| +| -------- | -------- | -------- | +| STATIC | 0 | Static IP address.| +| DHCP | 1 | IP address allocated by DHCP.| +| UNKNOWN | 2 | Not specified.| + + +## IpConfig9+ + +Represents IP configuration information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| prefixLength | number | Yes| No| Subnet mask.| +| dnsServers | number[] | Yes| No| Domain name server (DNS) information.| +| domains | Array<string> | Yes| No| Domain information.| + + +## WifiEapConfig9+ + +Represents EAP configuration information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| eapMethod | [EapMethod](#eapmethod9) | Yes| No| EAP authentication method.| +| phase2Method | [Phase2Method](#phase2method9) | Yes| No| Phase 2 authentication method.| +| identity | string | Yes| No| Identity Information.| +| anonymousIdentity | string | Yes| No| Anonymous identity.| +| password | string | Yes| No| Password.| +| caCertAliases | string | Yes| No| CA certificate alias.| +| caPath | string | Yes| No| CA certificate path.| +| clientCertAliases | string | Yes| No| Client certificate alias.| +| altSubjectMatch | string | Yes| No| A string to match the alternate subject.| +| domainSuffixMatch | string | Yes| No| A string to match the domain suffix.| +| realm | string | Yes| No| Realm for the passpoint credential.| +| plmn | string | Yes| No| Public land mobile network (PLMN) of the passpoint credential provider.| +| eapSubId | number | Yes| No| Sub-ID of the SIM card.| + + +## EapMethod9+ + +Enumerates the EAP authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| EAP_NONE | 0 | Not specified.| +| EAP_PEAP | 1 | PEAP.| +| EAP_TLS | 2 | TLS.| +| EAP_TTLS | 3 | TTLS.| +| EAP_PWD | 4 | Password.| +| EAP_SIM | 5 | SIM.| +| EAP_AKA | 6 | AKA.| +| EAP_AKA_PRIME | 7 | AKA Prime.| +| EAP_UNAUTH_TLS | 8 | UNAUTH TLS.| + + +## Phase2Method9+ + +Enumerates the Phase 2 authentication methods. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| PHASE2_NONE | 0 | Not specified.| +| PHASE2_PAP | 1 | PAP.| +| PHASE2_MSCHAP | 2 | MS-CHAP.| +| PHASE2_MSCHAPV2 | 3 | MS-CHAPv2.| +| PHASE2_GTC | 4 | GTC .| +| PHASE2_SIM | 5 | SIM.| +| PHASE2_AKA | 6 | AKA.| +| PHASE2_AKA_PRIME | 7 | AKA Prime.| + + +## wifi.addDeviceConfig9+ + +addDeviceConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds network configuration. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig): Promise<number> + +Adds the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| + + +## wifi.addCandidateConfig9+ + +addCandidateConfig(config: WifiDeviceConfig, callback: AsyncCallback<number>): void + +Adds the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number): Promise<void> + +Removes the configuration of a candidate network. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| + + +## wifi.removeCandidateConfig9+ + +removeCandidateConfig(networkId: number, callback: AsyncCallback<void>): void + +Removes the configuration of a candidate network. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the network configuration to remove.| + | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| + + +## wifi.getCandidateConfigs9+ + +getCandidateConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains candidate network configuration. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + + +## wifi.connectToCandidateConfig9+ + +connectToCandidateConfig(networkId: number): void + +Connects to a candidate network. + +**Required permissions**: ohos.permission.SET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| + + +## wifi.connectToNetwork9+ + +connectToNetwork(networkId: number): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| Network configuration ID.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.connectToDevice9+ + +connectToDevice(config: WifiDeviceConfig): void + +Connects to the specified network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO, ohos.permission.SET_WIFI_CONFIG, and ohos.permissio.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disconnect9+ + +disconnect(): void + +Disconnects the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: + SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getSignalLevel9+ + +getSignalLevel(rssi: number, band: number): number + +Obtains the WLAN signal level. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | rssi | number | Yes| RSSI of the hotspot, in dBm.| + | band | number | Yes| Frequency band of the WLAN AP.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | Signal level obtained. The value range is [0, 4].| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(): Promise<WifiLinkedInfo> + +Obtains WLAN connection information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + + +## wifi.getLinkedInfo9+ + +getLinkedInfo(callback: AsyncCallback<WifiLinkedInfo>): void + +Obtains WLAN connection information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + wifi.getLinkedInfo((err, data) => { + if (err) { + console.error("get linked info error"); + return; + } + console.info("get wifi linked info: " + JSON.stringify(data)); + }); + + wifi.getLinkedInfo().then(data => { + console.info("get wifi linked info: " + JSON.stringify(data)); + }).catch(error => { + console.info("get linked info error"); + }); + ``` + + +## WifiLinkedInfo9+ + +Represents the WLAN connection information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| bssid | string | Yes| No| BSSID of the hotspot.| +| networkId | number | Yes| No| Network configuration ID.
**System API**: This is a system API.| +| rssi | number | Yes| No| RSSI of the hotspot, in dBm.| +| band | number | Yes| No| Frequency band of the WLAN AP.| +| linkSpeed | number | Yes| No| Speed of the WLAN AP.| +| frequency | number | Yes| No| Frequency of the WLAN AP.| +| isHidden | boolean | Yes| No| Whether to hide the WLAN AP.| +| isRestricted | boolean | Yes| No| Whether to restrict data volume at the WLAN AP.| +| chload | number | Yes| No| Channel load. A larger value indicates a higher load.
**System API**: This is a system API.| +| snr | number | Yes| No| Signal-to-noise ratio (SNR).
**System API**: This is a system API.| +| macType9+ | number | Yes| No| MAC address type.| +| macAddress | string | Yes| No| MAC address of the device.| +| ipAddress | number | Yes| No| IP address of the device that sets up the WLAN connection.| +| suppState | [SuppState](#suppstate) | Yes| No| Supplicant state.
**System API**: This is a system API.| +| connState | [ConnState](#connstate) | Yes| No| WLAN connection state.| + + +## ConnState9+ + +Enumerates the WLAN connection states. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| SCANNING | 0 | The device is scanning for available APs.| +| CONNECTING | 1 | A WLAN connection is being established.| +| AUTHENTICATING | 2 | An authentication is being performed for a WLAN connection.| +| OBTAINING_IPADDR | 3 | The IP address of the WLAN connection is being acquired.| +| CONNECTED | 4 | A WLAN connection is established.| +| DISCONNECTING | 5 | The WLAN connection is being disconnected.| +| DISCONNECTED | 6 | The WLAN connection is disconnected.| +| UNKNOWN | 7 | Failed to set up the WLAN connection.| + + +## SuppState9+ + +Enumerates the supplicant states. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | The supplicant is disconnected from the AP.| +| INTERFACE_DISABLED | 1 | The network interface is disabled.| +| INACTIVE | 2 | The supplicant is inactive.| +| SCANNING | 3 | The supplicant is scanning for a WLAN connection.| +| AUTHENTICATING | 4 | The supplicant is being authenticated.| +| ASSOCIATING | 5 | The supplicant is being associated with an AP.| +| ASSOCIATED | 6 | The supplicant is associated with an AP.| +| FOUR_WAY_HANDSHAKE | 7 | A four-way handshake is being performed for the supplicant.| +| GROUP_HANDSHAKE | 8 | A group handshake is being performed for the supplicant.| +| COMPLETED | 9 | The authentication is complete.| +| UNINITIALIZED | 10 | The supplicant failed to set up the connection.| +| INVALID | 11 | Invalid value.| + + +## wifi.isConnected9+ + +isConnected(): boolean + +Checks whether the WLAN is connected. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + + +## wifi.getSupportedFeatures9+ + +getSupportedFeatures(): number + +Obtains the features supported by this device. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value. | + +**Feature IDs** + +| Value| Description| +| -------- | -------- | +| 0x0001 | WLAN infrastructure mode| +| 0x0002 | 5 GHz feature| +| 0x0004 | Generic Advertisement Service (GAS)/Access Network Query Protocol (ANQP) feature| +| 0x0008 | Wi-Fi Direct| +| 0x0010 | SoftAP| +| 0x0040 | Wi-Fi AWare| +| 0x8000 | WLAN AP/STA concurrency| +| 0x8000000 | WPA3 Personal (WPA-3 SAE)| +| 0x10000000 | WPA3-Enterprise Suite B | +| 0x20000000 | Enhanced open feature| + + +## wifi.isFeatureSupported9+ + +isFeatureSupported(featureId: number): boolean + +Checks whether the device supports the specified WLAN feature. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.getDeviceMacAddress9+ + +getDeviceMacAddress(): string[] + +Obtains the device MAC address. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_LOCAL_MAC and ohos.permission.GET_WIFI_INFO (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| + + +## wifi.getIpInfo9+ + +getIpInfo(): IpInfo + +Obtains IP information. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo9) | IP information obtained.| + + +## IpInfo9+ + +Represents IP information. + +**System capability**: SystemCapability.Communication.WiFi.STA + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ipAddress | number | Yes| No| IP address.| +| gateway | number | Yes| No| Gateway.| +| netmask | number | Yes| No| Subnet mask.| +| primaryDns | number | Yes| No| IP address of the preferred DNS server.| +| secondDns | number | Yes| No| IP address of the alternate DNS server.| +| serverIp | number | Yes| No| IP address of the DHCP server.| +| leaseDuration | number | Yes| No| Lease duration of the IP address.| + + +## wifi.getCountryCode9+ + +getCountryCode(): string + +Obtains the country code. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| + + +## wifi.reassociate9+ + +reassociate(): void + +Re-associates with the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.reconnect9+ + +reconnect(): void + +Reconnects to the network. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getDeviceConfigs9+ + +getDeviceConfigs():  Array<[WifiDeviceConfig](#wifideviceconfig)> + +Obtains network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + + +## wifi.updateNetwork9+ + +updateNetwork(config: WifiDeviceConfig): number + +Updates network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.SET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | +| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| + + +## wifi.disableNetwork9+ + +disableNetwork(netId: number): void + +Disables network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the network configuration to disable.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeAllNetwork9+ + +removeAllNetwork(): void + +Removes the configuration of all networks. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.removeDevice9+ + +removeDevice(id: number): void + +Removes the specified network configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | +| id | number | Yes| ID of the network configuration to remove.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.enableHotspot9+ + +enableHotspot(): void + +Enables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.disableHotspot9+ + +disableHotspot(): void + +Disables this hotspot. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.isHotspotDualBandSupported9+ + +isHotspotDualBandSupported(): boolean + +Checks whether the hotspot supports dual band. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + + +## wifi.isHotspotActive9+ + +isHotspotActive(): boolean + +Checks whether this hotspot is active. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| + + +## wifi.setHotspotConfig9+ + +setHotspotConfig(config: HotspotConfig): void + +Sets hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig9) | Yes| Hotspot configuration to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## HotspotConfig9+ + +Represents the hotspot configuration. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| ssid | string | Yes| No| SSID of the hotspot, in UTF-8 format.| +| securityType | [WifiSecurityType](#wifisecuritytype) | Yes| No| Security type.| +| band | number | Yes| No| Hotspot band. The value **1** stands for 2.4 GHz, the value **2** for 5 GHz, and the value **3** for dual band.| +| preSharedKey | string | Yes| No| PSK of the hotspot.| +| maxConn | number | Yes| No| Maximum number of connections allowed.| + + +## wifi.getHotspotConfig9+ + +getHotspotConfig(): HotspotConfig + +obtains hotspot configuration. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig9) | Hotspot configuration obtained.| + + +## wifi.getStations9+ + +getStations():  Array<[StationInfo](#stationinfo9)> + +Obtains information about the connected stations. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO, ohos.permission.LOCATION, and ohos.permission.MANAGE_WIFI_HOTSPOT (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo9)> | Connected stations obtained.| + + +## StationInfo9+ + +Represents the station information. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +| **Name**| **Type**| **Readable**| **Writable**| **Description**| +| -------- | -------- | -------- | -------- | -------- | +| name | string | Yes| No| Device name.| +| macAddress | string | Yes| No| MAC address.| +| ipAddress | string | Yes| No| IP address.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(): Promise<WifiP2pLinkedInfo> + +Obtains P2P link information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Promise used to return the P2P link information obtained.| + + + +## WifiP2pLinkedInfo9+ + +Represents the P2P link information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| connectState | [P2pConnectState](#p2pconnectstate9) | Yes| No| P2P connection state.| +| isGroupOwner | boolean | Yes| No| Whether the device is the group owner.| +| groupOwnerAddr | string | Yes| No| MAC address of the group. + + +## P2pConnectState9+ + +Enumerates the P2P connection states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| DISCONNECTED | 0 | Disconnected.| +| CONNECTED | 1 | Connected.| + + +## wifi.getP2pLinkedInfo9+ + +getP2pLinkedInfo(callback: AsyncCallback<WifiP2pLinkedInfo>): void + +Obtains P2P link information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(): Promise<WifiP2pGroupInfo> + +Obtains the current P2P group information. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Promise used to return the P2P group information obtained.| + + +## wifi.getCurrentGroup9+ + +getCurrentGroup(callback: AsyncCallback<WifiP2pGroupInfo>): void + +Obtains the current P2P group information. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(): Promise<WifiP2pDevice[]> + +Obtains the peer device list in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice9)> | Promise used to return the peer device list.| + + +## wifi.getP2pPeerDevices9+ + +getP2pPeerDevices(callback: AsyncCallback<WifiP2pDevice[]>): void + +Obtains the peer device list in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| + + +## WifiP2pDevice9+ + +Represents the P2P device information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceName | string | Yes| No| Device name.| +| deviceAddress | string | Yes| No| MAC address of the device.| +| primaryDeviceType | string | Yes| No| Type of the primary device.| +| deviceStatus | [P2pDeviceStatus](#p2pdevicestatus9) | Yes| No| Device status.| +| groupCapabilities | number | Yes| No| Group capabilities.| + + +## P2pDeviceStatus9+ + +Enumerates the P2P device states. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| CONNECTED | 0 | Connected.| +| INVITED | 1 | Invited.| +| FAILED | 2 | Failed.| +| AVAILABLE | 3 | Available.| +| UNAVAILABLE | 4 | Unavailable.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(): Promise<WifiP2pDevice> + +Obtains the local device information in the P2P connection. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice9)> | Promise used to return the local device information obtained.| + + +## wifi.getP2pLocalDevice9+ + +getP2pLocalDevice(callback: AsyncCallback<WifiP2pDevice>): void + +Obtains the local device information in the P2P connection. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.GET_WIFI_CONFIG + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.createGroup9+ + +createGroup(config: WifiP2PConfig): void + +Creates a P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| Group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## WifiP2PConfig9+ + +Represents P2P group configuration. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| deviceAddress | string | Yes| No| Device address.| +| netId | number | Yes| No| Network ID. The value **-1** indicates a temporary group, and **-2** indicates a persistent group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| groupName | string | Yes| No| Name of the group.| +| goBand | [GroupOwnerBand](#groupownerband9) | Yes| No| Frequency band of the group.| + + +## GroupOwnerBand9+ + +Enumerates the P2P group frequency bands. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Value| Description| +| -------- | -------- | -------- | +| GO_BAND_AUTO | 0 | Auto.| +| GO_BAND_2GHZ | 1 | 2 GHz.| +| GO_BAND_5GHZ | 2 | 5 GHz.| + + +## wifi.removeGroup9+ + +removeGroup(): void + +Removes this P2P group. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.p2pConnect9+ + +p2pConnect(config: WifiP2PConfig): void + +Sets up a P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig9) | Yes| P2P group configuration.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvP2pConnectionChangeFunc = result => { + console.info("p2p connection change receive event: " + JSON.stringify(result)); + wifi.getP2pLinkedInfo((err, data) => { + if (err) { + console.error('failed to get getP2pLinkedInfo: ' + JSON.stringify(err)); + return; + } + console.info("get getP2pLinkedInfo: " + JSON.stringify(data)); + }); + } + wifi.on("p2pConnectionChange", recvP2pConnectionChangeFunc); + + var recvP2pDeviceChangeFunc = result => { + console.info("p2p device change receive event: " + JSON.stringify(result)); + } + wifi.on("p2pDeviceChange", recvP2pDeviceChangeFunc); + + var recvP2pPeerDeviceChangeFunc = result => { + console.info("p2p peer device change receive event: " + JSON.stringify(result)); + wifi.getP2pPeerDevices((err, data) => { + if (err) { + console.error('failed to get peer devices: ' + JSON.stringify(err)); + return; + } + console.info("get peer devices: " + JSON.stringify(data)); + var len = Object.keys(data).length; + for (var i = 0; i < len; ++i) { + if (data[i].deviceName === "my_test_device") { + console.info("p2p connect to test device: " + data[i].deviceAddress); + var config = { + "deviceAddress":data[i].deviceAddress, + "netId":-2, + "passphrase":"", + "groupName":"", + "goBand":0, + } + wifi.p2pConnect(config); + } + } + }); + } + wifi.on("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc); + + var recvP2pPersistentGroupChangeFunc = () => { + console.info("p2p persistent group change receive event"); + + wifi.getCurrentGroup((err, data) => { + if (err) { + console.error('failed to get current group: ' + JSON.stringify(err)); + return; + } + console.info("get current group: " + JSON.stringify(data)); + }); + } + wifi.on("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc); + + setTimeout(function() {wifi.off("p2pConnectionChange", recvP2pConnectionChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pDeviceChange", recvP2pDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPeerDeviceChange", recvP2pPeerDeviceChangeFunc);}, 125 * 1000); + setTimeout(function() {wifi.off("p2pPersistentGroupChange", recvP2pPersistentGroupChangeFunc);}, 125 * 1000); + console.info("start discover devices -> " + wifi.startDiscoverDevices()); + ``` + +## wifi.p2pCancelConnect9+ + +p2pCancelConnect(): void + +Cancels this P2P connection. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.startDiscoverDevices9+ + +startDiscoverDevices(): void + +Starts to discover devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.stopDiscoverDevices9+ + +stopDiscoverDevices(): void + +Stops discovering devices. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.deletePersistentGroup9+ + +deletePersistentGroup(netId: number): void + +Deletes a persistent group. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the group to delete.| + +**Return value** + + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(): Promise<Array<WifiP2pGroupInfo>> + +Obtains information about all P2P groups. This API uses a promise to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)> > | Promise used to return the group information obtained.| + + +## WifiP2pGroupInfo9+ + +Represents the P2P group information. + +**System capability**: SystemCapability.Communication.WiFi.P2P + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| isP2pGo | boolean | Yes| No| Whether the device is the group owner.| +| ownerInfo | [WifiP2pDevice](#wifip2pdevice9) | Yes| No| Device information of the group.| +| passphrase | string | Yes| No| Passphrase of the group.| +| interface | string | Yes| No| Interface name.| +| groupName | string | Yes| No| Group name.| +| networkId | number | Yes| No| Network ID.| +| frequency | number | Yes| No| Frequency of the group.| +| clientDevices | [WifiP2pDevice[]](#wifip2pdevice9) | Yes| No| List of connected devices.| +| goIpAddress | string | Yes| No| IP address of the group.| + + +## wifi.getP2pGroups9+ + +getP2pGroups(callback: AsyncCallback<Array<WifiP2pGroupInfo>>): void + +Obtains information about all P2P groups. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo9)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + + +## wifi.setDeviceName9+ + +setDeviceName(devName: string): void + +Sets the device name. + +**System API**: This is a system API. + +**Required permissions**: ohos.permission.SET_WIFI_INFO and ohos.permission.MANAGE_WIFI_CONNECTION (available only to system applications) + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | devName | string | Yes| Device name to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifi.on('wifiStateChange')9+ + +on(type: "wifiStateChange", callback: Callback<number>): void + +Registers the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + +**WLAN states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('wifiStateChange')9+ + +off(type: "wifiStateChange", callback?: Callback<number>): void + +Unregisters the WLAN state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | No| Callback for the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + +**Example** + ```js + import wifi from '@ohos.wifi'; + + var recvPowerNotifyFunc = result => { + console.info("Receive power state change event: " + result); + } + + // Register an event. + wifi.on("wifiStateChange", recvPowerNotifyFunc); + + // Unregister an event. + wifi.off("wifiStateChange", recvPowerNotifyFunc); + ``` + + +## wifi.on('wifiConnectionChange')7+ + +on(type: "wifiConnectionChange", callback: Callback<number>): void + +Registers the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + +**WLAN connection states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Disconnected.| +| 1 | Connected.| + + +## wifi.off('wifiConnectionChange')9+ + +off(type: "wifiConnectionChange", callback?: Callback<number>): void + +Unregisters the WLAN connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | No| Callback for the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiScanStateChange')9+ + +on(type: "wifiScanStateChange", callback: Callback<number>): void + +Registers the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + +**WLAN scan states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Scan failed.| +| 1 | Scan successful.| + + +## wifi.off('wifiScanStateChange')9+ + +off(type: "wifiScanStateChange", callback?: Callback<number>): void + +Unregisters the WLAN scan state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + +| **Name**| **Type**| **Mandatory**| **Description**| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Event type. The value is **wifiScanStateChange**.| +| callback | Callback<number> | No| Callback for the WLAN scan state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('wifiRssiChange')9+ + +on(type: "wifiRssiChange", callback: Callback<number>): void + +Registers the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + + +## wifi.off('wifiRssiChange')9+ + +off(type: "wifiRssiChange", callback?: Callback<number>): void + +Unregisters the RSSI change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.STA + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| +| callback | Callback<number> | No| Callback for the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('hotspotStateChange')9+ + +on(type: "hotspotStateChange", callback: Callback<number>): void + +Registers the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + +**Hotspot states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Deactivated| +| 1 | Activated| +| 2 | Activating| +| 3 | Deactivating| + + +## wifi.off('hotspotStateChange')9+ + +off(type: "hotspotStateChange", callback?: Callback<number>): void + +Unregisters the hotspot state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Core + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| +| callback | Callback<number> | No| Callback for the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pStateChange')9+ + +on(type: "p2pStateChange", callback: Callback<number>): void + +Registers the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + +**P2P states** + +| **Value**| **Description**| +| -------- | -------- | +| 1 | Available| +| 2 | Opening| +| 3 | Opened| +| 4 | Closing| +| 5 | Closed| + +## wifi.off('p2pStateChange')9+ + +off(type: "p2pStateChange", callback?: Callback<number>): void + +Unregisters the P2P state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| +| callback | Callback<number> | No| Callback for the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + + ## wifi.on('p2pConnectionChange')9+ + +on(type: "p2pConnectionChange", callback: Callback<WifiP2pLinkedInfo>): void + +Registers the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | Yes| Callback invoked to return the P2P connection state.| + + +## wifi.off('p2pConnectionChange')9+ + +off(type: "p2pConnectionChange", callback?: Callback<WifiP2pLinkedInfo>): void + +Unregisters the P2P connection state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo9)> | No| Callback for the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDeviceChange')9+ + +on(type: "p2pDeviceChange", callback: Callback<WifiP2pDevice>): void + +Registers the P2P device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P device state.| + + +## wifi.off('p2pDeviceChange')9+ + +off(type: "p2pDeviceChange", callback?: Callback<WifiP2pDevice>): void + +Unregisters the P2P device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice9)> | No| Callback for the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPeerDeviceChange')9+ + +on(type: "p2pPeerDeviceChange", callback: Callback<WifiP2pDevice[]>): void + +Registers the P2P peer device state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO and ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | Yes| Callback invoked to return the P2P peer device state.| + + +## wifi.off('p2pPeerDeviceChange')9+ + +off(type: "p2pPeerDeviceChange", callback?: Callback<WifiP2pDevice[]>): void + +Unregisters the P2P peer device state change events. + +**Required permissions**: ohos.permission.LOCATION + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice9)> | No| Callback for the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pPersistentGroupChange')9+ + +on(type: "p2pPersistentGroupChange", callback: Callback<void>): void + +Registers the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| + + +## wifi.off('p2pPersistentGroupChange')9+ + +off(type: "p2pPersistentGroupChange", callback?: Callback<void>): void + +Unregisters the P2P persistent group state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | No| Callback for the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + + +## wifi.on('p2pDiscoveryChange')9+ + +on(type: "p2pDiscoveryChange", callback: Callback<number>): void + +Registers the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| + +**P2P discovered device states** + +| **Value**| **Description**| +| -------- | -------- | +| 0 | Initial state.| +| 1 | Discovered.| + + +## wifi.off('p2pDiscoveryChange')9+ + +off(type: "p2pDiscoveryChange", callback?: Callback<number>): void + +Unregisters the P2P device discovery state change events. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.P2P + +**Parameters** + + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | No| Callback for the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/apis/js-apis-wifiManagerExt.md b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md new file mode 100644 index 0000000000000000000000000000000000000000..f024294ddbc393a57394a1ad20d2686d30060e52 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-wifiManagerExt.md @@ -0,0 +1,152 @@ +# WLAN Extension Interface + +This **wifiext** module provides WLAN extension interfaces for non-universal products. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The APIs described in this document are used only for non-universal products, such as routers. + + +## Modules to Import + +```js +import wifiManagerExt from '@ohos.wifiManagerExt'; +``` + +## wifiext.enableHotspot + +enableHotspot(): boolean; + +Enables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.disableHotspot + +disableHotspot(): boolean; + +Disables the WLAN hotspot. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(): Promise<Array<PowerModel>> + +Obtains the supported power models. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<Array<[PowerModel](#powermodel)>> | Promise used to return the power models obtained.| + + +## PowerModel + +Enumerates the power models. + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +| Name| Value| Description| +| -------- | -------- | -------- | +| SLEEPING | 0 | Sleeping| +| GENERAL | 1 | General| +| THROUGH_WALL | 2 | Through_wall| + + +## wifiext.getSupportedPowerModel + +getSupportedPowerModel(callback: AsyncCallback<Array<PowerModel>>): void + +Obtains the supported power models. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + + +## wifiext.getPowerModel + +getPowerModel(): Promise<PowerModel> + +Obtains the power model. This API uses a promise to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Return value** + + | Type| Description| + | -------- | -------- | + | Promise<[PowerModel](#powermodel)> | Promise used to return the power model obtained.| + + +## wifiext.getPowerModel + +getPowerModel(callback: AsyncCallback<PowerModel>): void + +Obtains the power model. This API uses an asynchronous callback to return the result. + +**Required permissions**: ohos.permission.GET_WIFI_INFO + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the power model obtained. If **err** is not **0**, an error has occurred.| + + +## wifiext.setPowerModel + +setPowerModel(model: PowerModel) : boolean; + + Sets the power model. + +**Required permissions**: ohos.permission.MANAGE_WIFI_HOTSPOT_EXT + +**System capability**: SystemCapability.Communication.WiFi.AP.Extension + +**Parameters** + + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | model | [PowerModel](#powermodel) | Yes| Power model to set.| + +**Return value** + + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| diff --git a/en/application-dev/reference/apis/js-apis-wifiext.md b/en/application-dev/reference/apis/js-apis-wifiext.md index 9ce53d76e2517eb199067f779168fb9fe9d8b032..70961ffe279bf5543bbe28168f8571a54ca46651 100644 --- a/en/application-dev/reference/apis/js-apis-wifiext.md +++ b/en/application-dev/reference/apis/js-apis-wifiext.md @@ -1,7 +1,9 @@ -# WLAN +# @ohos.wifiext + This **wifiext** module provides WLAN extension interfaces for non-universal products. -> **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. The APIs described in this document are used only for non-universal products, such as routers. @@ -69,7 +71,7 @@ Enumerates the power models. **System capability**: SystemCapability.Communication.WiFi.AP.Extension -| Name| Default Value| Description| +| Name| Value| Description| | -------- | -------- | -------- | | SLEEPING | 0 | Sleeping| | GENERAL | 1 | General| @@ -90,7 +92,7 @@ Obtains the supported power models. This API uses an asynchronous callback to re | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[PowerModel](#powermodel)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| + | callback | AsyncCallback<Array<[PowerModel](#powermodel)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is 0 and **data** is the power models obtained. If **err** is not **0**, an error has occurred.| ## wifiext.getPowerModel @@ -141,7 +143,7 @@ setPowerModel(model: PowerModel) : boolean; | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | - | model | AsyncCallback<[PowerModel](#powermodel)> | Yes| Power model to set.| + | model | [PowerModel](#powermodel) | Yes| Power model to set.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-window.md b/en/application-dev/reference/apis/js-apis-window.md index 9d60fe2118d81d8b423a851b6dbf759b48a10864..90a20044c16f8c9fe2dd11d3aaa294e7d869c55b 100644 --- a/en/application-dev/reference/apis/js-apis-window.md +++ b/en/application-dev/reference/apis/js-apis-window.md @@ -1,4 +1,4 @@ -# Window +# @ohos.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. @@ -46,17 +46,15 @@ Enumerates the window types. ## 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. +Defines the parameters for creating a subwindow or system window. **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. | +| name | string | Yes| Name of the window. | +| windowType | [WindowType](#windowtype7) | Yes| Type of the window. | +| ctx | BaseContext | No| Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md). If this parameter is not set, no context is used.
A system window is created when **Context** is [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| | 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. | @@ -250,7 +248,7 @@ Enumerates the color spaces. | Name | Value| Description | | ---------- | ------ | -------------- | -| DEFAULT | 0 | Default gamut.| +| DEFAULT | 0 | Default SRGB gamut.| | WIDE_GAMUT | 1 | Wide-gamut. | ## ScaleOptions9+ @@ -302,7 +300,7 @@ Describes the translation parameters. createWindow(config: Configuration, callback: AsyncCallback<Window>): void -Creates a subwindow. This API uses an asynchronous callback to return the result. +Creates a subwindow or system window. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -310,8 +308,8 @@ Creates a subwindow. 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.| +| config | [Configuration](#configuration9) | Yes| Parameters used for creating the window. | +| callback | AsyncCallback<[Window](#window)> | Yes| Callback used to return the window created.| **Error codes** @@ -346,7 +344,7 @@ try { createWindow(config: Configuration): Promise<Window> -Creates a subwindow. This API uses a promise to return the result. +Creates a subwindow or system window. This API uses a promise to return the result. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -354,13 +352,13 @@ Creates a subwindow. This API uses a promise to return the result. | Name| Type| Mandatory| Description| | ------ | -------------------------------- | -- | ------------------ | -| config | [Configuration](#configuration9) | Yes| Current application context.| +| config | [Configuration](#configuration9) | Yes| Parameters used for creating the window.| **Return value** | Type| Description| | -------------------------------- | ------------------------------------ | -| Promise<[Window](#window)> | Promise used to return the subwindow created.| +| Promise<[Window](#window)> | Promise used to return the window created.| **Error codes** @@ -393,7 +391,7 @@ try { findWindow(name: string): Window -Finds a window based on the ID. +Finds a window based on the name. **System capability**: SystemCapability.WindowManager.WindowManager.Core @@ -432,7 +430,7 @@ Obtains the top window of the current application. This API uses an asynchronous | 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).| +| ctx | BaseContext | Yes| Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-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.| **Error codes** @@ -474,7 +472,7 @@ Obtains the top window of the current application. This API uses a promise to re | 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).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -899,7 +897,7 @@ promise.then((data)=> { create(ctx: BaseContext, id: string, type: WindowType, callback: AsyncCallback<Window>): void -Creates a subwindow in the FA model or a system window in the stage model. This API uses an asynchronous callback to return the result. +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. > **NOTE** > @@ -911,7 +909,7 @@ Creates a subwindow in the FA model or a system window in the stage model. This | 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).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype7) | Yes | Window type. | | callback | AsyncCallback<[Window](#window)> | Yes | Callback used to return the subwindow created. | @@ -935,7 +933,7 @@ window.create(this.context, 'alertWindow', window.WindowType.TYPE_SYSTEM_ALERT, create(ctx: BaseContext, id: string, type: WindowType): Promise<Window> -Creates a subwindow in the FA model or a system window in the stage model. This API uses a promise to return the result. +Creates a subwindow (in API version 8) or a system window (from API version 9). This API uses a promise to return the result. > **NOTE** > @@ -947,7 +945,7 @@ Creates a subwindow in the FA model or a system window in the stage model. This | 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).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [ServiceExtensionContext](js-apis-inner-application-serviceExtensionContext.md).| | id | string | Yes | Window ID. | | type | [WindowType](#windowtype7) | Yes | Window type. | @@ -1123,7 +1121,7 @@ Obtains the top window of the current application. This API uses an asynchronous | 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).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-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** @@ -1156,7 +1154,7 @@ Obtains the top window of the current application. This API uses a promise to re | 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).| +| ctx | BaseContext | Yes | Current application context.
For details about the context in the FA model, see [Context](js-apis-inner-app-context.md).
For details about the context in the stage model, see [Context](js-apis-ability-context.md).| **Return value** @@ -1546,6 +1544,8 @@ moveWindowTo(x: number, y: number, callback: AsyncCallback<void>): void Moves this window. This API uses an asynchronous callback to return the result. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1587,6 +1587,8 @@ moveWindowTo(x: number, y: number): Promise<void> Moves this window. This API uses a promise to return the result. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1638,6 +1640,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1685,6 +1689,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + **System capability**: SystemCapability.WindowManager.WindowManager.Core **Parameters** @@ -1983,7 +1989,7 @@ Sets whether to display the status bar and navigation bar in this window. This A | Name| Type| Mandatory| Description| | -------- | ---------------------------- | -- | --------- | -| names | Array<'status'\|'navigation'> | 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.| +| names | Array<'status'\|'navigation'> | 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** @@ -4320,6 +4326,8 @@ moveTo(x: number, y: number, callback: AsyncCallback<void>): void Moves this window. This API uses an asynchronous callback to return the result. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9) instead. @@ -4353,6 +4361,8 @@ moveTo(x: number, y: number): Promise<void> Moves this window. This API uses a promise to return the result. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [moveWindowTo()](#movewindowto9-1) instead. @@ -4396,6 +4406,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9) instead. @@ -4435,6 +4447,8 @@ The system window has the following size limits: [0, 2560] in width and [0, 2560 The new width and height you set must meet the limits. +This operation is not supported in a window in full-screen mode. + > **NOTE** > > This API is supported since API version 7 and deprecated since API version 9. You are advised to use [resize()](#resize9-1) instead. @@ -5902,12 +5916,12 @@ Describes the lifecycle of a window stage. **System capability**: SystemCapability.WindowManager.WindowManager.Core -| Name | 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 | Value | Description | +| -------- | ----- | ---------------------------------------------- | +| SHOWN | 1 | The window stage is running in the foreground. | +| ACTIVE | 2 | The window stage gains focus. | +| INACTIVE | 3 | The window stage loses focus. | +| HIDDEN | 4 | The window stage is running in the background. | ## WindowStage9+ @@ -5943,9 +5957,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -5990,9 +6006,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6036,9 +6054,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6080,9 +6100,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6138,9 +6160,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6187,9 +6211,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6233,9 +6259,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); let windowClass = null; @@ -6281,9 +6309,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); @@ -6340,9 +6370,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { storage : LocalStorage onWindowStageCreate(windowStage) { this.storage = new LocalStorage(); @@ -6392,9 +6424,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6442,9 +6476,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6490,9 +6526,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { @@ -6530,9 +6568,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('disableWindowDecor'); windowStage.disableWindowDecor(); @@ -6571,9 +6611,11 @@ For details about the error codes, see [Window Error Codes](../errorcodes/errorc **Example** ```ts -import Ability from '@ohos.application.Ability'; +import UIAbility from '@ohos.app.ability.UIAbility'; + +export default class EntryAbility extends UIAbility { + // ... -class myAbility extends Ability { onWindowStageCreate(windowStage) { console.log('onWindowStageCreate'); try { diff --git a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md index 46d23a02136a6d042b3f05fb335d5bd620dfd82f..ffae7ffbf0941f4aa79fb0335b853fc281e66476 100644 --- a/en/application-dev/reference/apis/js-apis-windowAnimationManager.md +++ b/en/application-dev/reference/apis/js-apis-windowAnimationManager.md @@ -1,4 +1,5 @@ -# Window Animation Management +# @ohos.animation.windowAnimationManager (Window Animation Management) + The **WindowAnimationManager** module provides APIs to listen for application start/exit events and window minimization/maximization events and associate animations with these events. > **NOTE** diff --git a/en/application-dev/reference/apis/js-apis-worker.md b/en/application-dev/reference/apis/js-apis-worker.md index a9bb769b0eccd89631f4747bcce6deba03c4533a..db8a73c0ff0b29ca6c753073f8ea0d297b19ccb8 100644 --- a/en/application-dev/reference/apis/js-apis-worker.md +++ b/en/application-dev/reference/apis/js-apis-worker.md @@ -1,11 +1,15 @@ -# Worker Startup +# @ohos.worker (Worker Startup) + +The worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. + +With the **Worker** module, you can provide a multithreading environment for an application, so that the application can perform a time-consuming operation in a background thread. This greatly prevents a computing-intensive or high-latency task from blocking the running of the main thread. A **Worker** instance will not be proactively destroyed once it is created. It consumes resources to keep running. Therefore, you should call the API to terminate it in a timely manner. + +The **Context** object of the worker thread is different from that of the main thread. The worker thread does not support UI operations. > **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 worker thread is an independent thread running in parallel with the main thread. The thread that creates the worker thread is referred to as the host thread. The URL file passed in during worker creation is executed in the worker thread. The worker thread can process time-consuming operations, but cannot directly operate the UI. - ## Modules to Import ```js @@ -17,10 +21,10 @@ import worker from '@ohos.worker'; **System capability**: SystemCapability.Utils.Lang -| Name | Type | Readable| Writable| Description | +| Name | Type | Readable| Writable| Description | | --------------------------------- | --------------------------------------------------------- | ---- | ---- | ------------------------------------------------------------ | | workerPort9+ | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Yes | Object of the worker thread used to communicate with the host thread. | -| parentPort(deprecated) | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.
This attribute is deprecated since API version 9. You are advised to use **workerPort9+** instead.| +| parentPort(deprecated) | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscope) | Yes | Yes | Object of the worker thread used to communicate with the host thread.
This attribute is supported since API version 7 and deprecated since API version 9.
You are advised to use **workerPort9+** instead.| ## WorkerOptions @@ -31,18 +35,20 @@ Provides options that can be set for the **Worker** instance to create. | Name| Type| Readable| Writable| Description | | ---- | -------- | ---- | ---- | -------------- | +| type | "classic" \| "module" | Yes | Yes | Mode in which the **Worker** instance executes the script. The default value is **classic**. The module **type** is not supported yet.| | name | string | Yes | Yes | Name of the worker thread.| +| shared | boolean | Yes | Yes | Sharing of the **Worker** instance is not supported yet.| ## ThreadWorker9+ -Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [WorkerEventTarget](#workereventtarget9). +Before using the following APIs, you must create a **ThreadWorker** instance. The **ThreadWorker** class inherits from [WorkerEventTarget](#workereventtarget9). ### constructor9+ constructor(scriptURL: string, options?: WorkerOptions) -A constructor used to create a **Worker** instance. +A constructor used to create a **ThreadWorker** instance. **System capability**: SystemCapability.Utils.Lang @@ -55,9 +61,20 @@ A constructor used to create a **Worker** instance. **Return value** -| Type | Description | -| ------ | --------------------------------------------------------- | -| Worker | Returns the **Worker** instance created; returns **undefined** if the **Worker** instance fails to be created.| +| Type | Description | +| ------------ | ------------------------------------------------------------ | +| ThreadWorker | Returns the **ThreadWorker** instance created; returns **undefined** if the **ThreadWorker** instance fails to be created.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message| +| -------- | -------- | +| 10200003 | Worker initialization failure. | +| 10200007 | The worker file patch is invalid path. | + + **Example** @@ -90,7 +107,7 @@ In the FA model: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -134,6 +151,40 @@ In the stage model: } ``` +### postMessage9+ + +postMessage(message: Object, transfer: ArrayBuffer[]): void; + +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 + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------------ | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); + +workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); +``` ### postMessage9+ @@ -150,6 +201,15 @@ Sends a message to the worker thread. The data type of the message must be seque | message | Object | Yes | Message to be sent to the worker thread. | | options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + **Example** ```js @@ -161,12 +221,11 @@ var buffer = new ArrayBuffer(8); workerInstance.postMessage(buffer, [buffer]); ``` - ### on9+ on(type: string, listener: WorkerEventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener9+](#addeventlistener9). **System capability**: SystemCapability.Utils.Lang @@ -177,6 +236,15 @@ Adds an event listener for the worker thread. | type | string | Yes | Type of the event to listen for. | | listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -202,6 +270,15 @@ Adds an event listener for the worker thread and removes the event listener afte | type | string | Yes | Type of the event to listen for. | | listener | [WorkerEventListener](#workereventlistener9) | Yes| Callback to invoke when an event of the specified type occurs. Callback to invoke when an event of the specified type occurs.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -216,7 +293,7 @@ workerInstance.once("alert", (e)=>{ off(type: string, listener?: WorkerEventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener9+](#removeeventlistener9). **System capability**: SystemCapability.Utils.Lang @@ -227,10 +304,20 @@ Removes an event listener for the worker thread. | type | string | Yes | Type of the event for which the event listener is to be removed. | | listener | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` @@ -243,6 +330,14 @@ Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -263,7 +358,16 @@ Defines the event handler to be called when the worker thread exits. The handler | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | No | Code indicating the worker thread exit state.| +| code | number | Yes | Code indicating the worker thread exit state.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -272,6 +376,13 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.onexit = function(e) { console.log("onexit"); } + +// onexit is executed in either of the following ways: +// Main thread: +workerInstance.terminate(); + +// Worker thread: +//parentPort.close() ``` @@ -287,7 +398,16 @@ Defines the event handler to be called when an exception occurs during worker ex | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| err | [ErrorEvent](#errorevent) | No | Error data.| +| err | [ErrorEvent](#errorevent) | Yes | Error data.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -301,7 +421,7 @@ workerInstance.onerror = function(e) { ### onmessage9+ -onmessage?: (event: MessageEvent\) => void +onmessage?: (event: MessageEvents) => void Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread. @@ -309,16 +429,25 @@ Defines the event handler to be called when the host thread receives a message s **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------------------- | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------------------- | +| event | [MessageEvents](#messageevents9) | Yes | Message received.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); workerInstance.onmessage = function(e) { - // e: MessageEvent. The usage is as follows: + // e: MessageEvents. The usage is as follows: // let data = e.data; console.log("onmessage"); } @@ -327,7 +456,7 @@ workerInstance.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (event: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. @@ -335,9 +464,18 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------- | +| event | [MessageEvents](#messageevents9) | Yes | Error data.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -348,6 +486,169 @@ workerInstance.onmessageerror= function(e) { } ``` +### addEventListener9+ + +addEventListener(type: string, listener: WorkerEventListener): void + +Adds an event listener for the worker thread. This API provides the same functionality as [on9+](#on9). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ---------------- | +| type | string | Yes | Type of the event to listen for.| +| listener | [WorkerEventListener](#workereventlistener9) | Yes | Callback to invoke when an event of the specified type occurs. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +``` + + +### removeEventListener9+ + +removeEventListener(type: string, callback?: WorkerEventListener): void + +Removes an event listener for the worker thread. This API provides the same functionality as [off9+](#off9). + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ---------------------------- | +| type | string | Yes | Type of the event for which the event listener is to be removed. | +| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.removeEventListener("alert"); +``` + + +### dispatchEvent9+ + +dispatchEvent(event: Event): boolean + +Dispatches the event defined for the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | --------------- | ---- | ---------------- | +| event | [Event](#event) | Yes | Event to dispatch.| + +**Return value** + +| Type | Description | +| ------- | ------------------------------- | +| boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) + +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. +// The event listener created by on will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will be always valid and will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); +``` + + +### removeAllListener9+ + +removeAllListener(): void + +Removes all event listeners for the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + +**Example** + +```js +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.removeAllListener(); +``` ## WorkerEventTarget9+ @@ -355,7 +656,7 @@ workerInstance.onmessageerror= function(e) { addEventListener(type: string, listener: WorkerEventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [on9+](#on9). **System capability**: SystemCapability.Utils.Lang @@ -366,6 +667,15 @@ Adds an event listener for the worker thread. | type | string | Yes | Type of the event to listen for.| | listener | [WorkerEventListener](#workereventlistener9) | Yes | Callback to invoke when an event of the specified type occurs. | +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -380,7 +690,7 @@ workerInstance.addEventListener("alert", (e)=>{ removeEventListener(type: string, callback?: WorkerEventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [off9+](#off9). **System capability**: SystemCapability.Utils.Lang @@ -389,12 +699,23 @@ 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 to be removed. | -| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. Callback of the event listener to remove.| +| callback | [WorkerEventListener](#workereventlistener9) | No| Callback to invoke when an event of the specified type occurs. | + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | **Example** ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeEventListener("alert"); ``` @@ -419,11 +740,53 @@ Dispatches the event defined for the worker thread. | ------- | ------------------------------- | | boolean | Returns **true** if the event is dispatched successfully; returns **false** otherwise.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); -workerInstance.dispatchEvent({type:"alert"}); +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) + +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. +// The event listener created by on will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); ``` @@ -435,18 +798,76 @@ Removes all event listeners for the worker thread. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeAllListener(); ``` ## ThreadWorkerGlobalScope9+ -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 [GlobalScope9+](#globalscope9). +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 **ThreadWorkerGlobalScope** class inherits from [GlobalScope9+](#globalscope9). + +### postMessage9+ + +postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; + +Sends a message to the host thread from the worker thread. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ------------------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + +**Example** + +```js +// main.js +import worker from '@ohos.worker'; +const workerInstance = new worker.ThreadWorker("workers/worker.js"); +workerInstance.postMessage("hello world"); +workerInstance.onmessage = function(e) { + // let data = e.data; + console.log("receive data from worker.js"); +} +``` + +```js +// worker.js +import worker from '@ohos.worker'; +const workerPort = worker.workerPort; +workerPort.onmessage = function(e){ + // let data = e.data; + var buffer = new ArrayBuffer(8); + workerPort.postMessage(buffer, [buffer]); +} +``` ### postMessage9+ @@ -463,6 +884,15 @@ Sends a message to the host thread from the worker thread. | message | Object | Yes | Message to be sent to the worker thread. | | options | [PostMessageOptions](#postmessageoptions) | No | **ArrayBuffer** instances that can be transferred. The **transferList** array cannot contain **null**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ----------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200006 | Serializing an uncaught exception failed. | + **Example** ```js @@ -479,10 +909,10 @@ workerInstance.onmessage = function(e) { ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e){ +const workerPort = worker.workerPort; +workerPort.onmessage = function(e){ // let data = e.data; - parentPort.postMessage("receive data from main.js"); + workerPort.postMessage("receive data from main.js"); } ``` @@ -495,6 +925,14 @@ Terminates the worker thread to stop it from receiving messages. **System capability**: SystemCapability.Utils.Lang +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | ------------------------------- | +| 10200004 | Worker instance is not running. | + **Example** ```js @@ -506,16 +944,16 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e) { - parentPort.close() +const workerPort = worker.workerPort; +workerPort.onmessage = function(e) { + workerPort.close() } ``` ### onmessage9+ -onmessage?: (event: MessageEvent\) => void +onmessage?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => void 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. @@ -523,9 +961,19 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------------ | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ---------------------------------------------------- | ---- | ------------------------ | +| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | +| ev | [MessageEvents](#messageevents9) | Yes | Message received.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -539,8 +987,8 @@ workerInstance.postMessage("hello world"); ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; -parentPort.onmessage = function(e) { +const workerPort = worker.workerPort; +workerPort.onmessage = function(e) { console.log("receive main.js message"); } ``` @@ -548,7 +996,7 @@ parentPort.onmessage = function(e) { ### onmessageerror9+ -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (this: ThreadWorkerGlobalScope, ev: MessageEvents) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. @@ -556,9 +1004,19 @@ Defines the event handler to be called when the worker thread receives a message **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | -------------------------------- | ---- | ---------- | +| this | [ThreadWorkerGlobalScope](#threadworkerglobalscope9) | Yes | Caller. | +| ev | [MessageEvents](#messageevents9) | Yes | Error data.| + +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | **Example** @@ -572,7 +1030,7 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js"); // worker.js import worker from '@ohos.worker'; const parentPort = worker.workerPort; -parentPort.onmessageerror= function(e) { +parentPort.onmessageerror = function(e) { console.log("worker.js onmessageerror") } ``` @@ -598,6 +1056,15 @@ Implements event listening. | ------------------------------------- | ------------------------------- | | void \| Promise<void> | Returns no value or returns a **Promise**.| +**Error codes** + +For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md). + +| ID| Error Message | +| -------- | -------------------------------------------- | +| 10200004 | Worker instance is not running. | +| 10200005 | The invoked API is not supported in workers. | + **Example** ```js @@ -610,13 +1077,13 @@ workerInstance.addEventListener("alert", (e)=>{ ## GlobalScope9+ -Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9). +Implements the running environment of the worker thread. The **GlobalScope** class inherits from [WorkerEventTarget](#workereventtarget9). ### Attributes **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| | self | [GlobalScope](#globalscope9) & typeof globalThis | Yes | No | **GlobalScope** itself. | @@ -634,7 +1101,7 @@ Defines the event handler to be called when an exception occurs during worker ex | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| ev | [ErrorEvent](#errorevent) | No | Error data.| +| ev | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -647,28 +1114,39 @@ const workerInstance = new worker.ThreadWorker("workers/worker.js") ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort -parentPort.onerror = function(e){ +const workerPort = worker.workerPort +workerPort.onerror = function(e){ console.log("worker.js onerror") } ``` +## MessageEvents9+ + +Holds the data transferred between worker threads. + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description | +| ---- | ---- | ---- | ---- | ------------------ | +| data | any | Yes | No | Data transferred between threads.| ## Worker(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker9+](#threadworker9) instead. Before using the following APIs, you must create a **Worker** instance. The **Worker** class inherits from [EventTarget](#eventtarget). -### constructor(deprecated) > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.constructor9+](#constructor9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker9+](#threadworker9) instead. + +### constructor(deprecated) constructor(scriptURL: string, options?: WorkerOptions) A constructor used to create a **Worker** instance. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.constructor9+](#constructor9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -714,7 +1192,7 @@ In the FA model: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -751,15 +1229,45 @@ In the stage model: } } ``` + ### postMessage(deprecated) +postMessage(message: Object, transfer: ArrayBuffer[]): void; + +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). + > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9) instead. + +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ----------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | **ArrayBuffer** instances that can be transferred.| + +**Example** + +```js +const workerInstance = new worker.Worker("workers/worker.js"); + +workerInstance.postMessage("hello world"); + +var buffer = new ArrayBuffer(8); +workerInstance.postMessage(buffer, [buffer]); +``` + +### postMessage(deprecated) postMessage(message: Object, options?: PostMessageOptions): void 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). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.postMessage9+](#postmessage9-1) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -775,20 +1283,17 @@ Sends a message to the worker thread. The data type of the message must be seque const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.postMessage("hello world"); - -var buffer = new ArrayBuffer(8); -workerInstance.postMessage(buffer, [buffer]); ``` ### on(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.on9+](#on9) instead. - on(type: string, listener: EventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [addEventListener(deprecated)](#addeventlistenerdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.on9+](#on9) instead. **System capability**: SystemCapability.Utils.Lang @@ -811,13 +1316,13 @@ workerInstance.on("alert", (e)=>{ ### once(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.once9+](#once9) instead. - once(type: string, listener: EventListener): void Adds an event listener for the worker thread and removes the event listener after it is invoked once. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.once9+](#once9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -839,12 +1344,12 @@ workerInstance.once("alert", (e)=>{ ### off(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.off9+](#off9) instead. - off(type: string, listener?: EventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [removeEventListener(deprecated)](#removeeventlistenerdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.off9+](#off9) instead. **System capability**: SystemCapability.Utils.Lang @@ -859,19 +1364,20 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); +// Use on, once, or addEventListener to add a listener for the "alert" event, and use off to remove the listener. workerInstance.off("alert"); ``` ### terminate(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.terminate9+](#terminate9) instead. - terminate(): void Terminates the worker thread to stop it from receiving messages. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.terminate9+](#terminate9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -884,20 +1390,20 @@ workerInstance.terminate(); ### onexit(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onexit9+](#onexit9) instead. - onexit?: (code: number) => void Defines the event handler to be called when the worker thread exits. The handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onexit9+](#onexit9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| code | number | No | Code indicating the worker thread exit state.| +| code | number | Yes | Code indicating the worker thread exit state.| **Example** @@ -906,25 +1412,32 @@ const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onexit = function(e) { console.log("onexit"); } + +// onexit is executed in either of the following ways: +// Main thread: +workerInstance.terminate(); + +// Worker thread: +//parentPort.close() ``` ### onerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onerror9+](#onerror9) instead. - onerror?: (err: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onerror9+](#onerror9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| err | [ErrorEvent](#errorevent) | No | Error data.| +| err | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -938,27 +1451,27 @@ workerInstance.onerror = function(e) { ### onmessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessage9+](#onmessage9) instead. - -onmessage?: (event: MessageEvent\) => void +onmessage?: (event: MessageEvent) => void Defines the event handler to be called when the host thread receives a message sent by the worker thread through **parentPort.postMessage**. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessage9+](#onmessage9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------------------- | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------------------- | +| event | [MessageEvent](#messageevent)| Yes | Message received.| **Example** ```js const workerInstance = new worker.Worker("workers/worker.js"); workerInstance.onmessage = function(e) { - // e: MessageEvent. The usage is as follows: + // e: MessageEvent. The usage is as follows: // let data = e.data; console.log("onmessage"); } @@ -967,20 +1480,20 @@ workerInstance.onmessage = function(e) { ### onmessageerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror9+](#onmessageerror9) instead. - -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (event: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be serialized. The event handler is executed in the host thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorker.onmessageerror9+](#onmessageerror9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------- | +| event | [MessageEvent](#messageevent)| Yes | Error data.| **Example** @@ -994,16 +1507,16 @@ workerInstance.onmessageerror= function(e) { ## EventTarget(deprecated) > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [WorkerEventTarget9+](#workereventtarget9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventTarget9+](#workereventtarget9) instead. ### addEventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [addEventListener9+](#addeventlistener9) instead. - addEventListener(type: string, listener: EventListener): void -Adds an event listener for the worker thread. +Adds an event listener for the worker thread. This API provides the same functionality as [on(deprecated)](#ondeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [addEventListener9+](#addeventlistener9) instead. **System capability**: SystemCapability.Utils.Lang @@ -1026,12 +1539,12 @@ workerInstance.addEventListener("alert", (e)=>{ ### removeEventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [removeEventListener9+](#removeeventlistener9) instead. - removeEventListener(type: string, callback?: EventListener): void -Removes an event listener for the worker thread. +Removes an event listener for the worker thread. This API provides the same functionality as [off(deprecated)](#offdeprecated). + +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeEventListener9+](#removeeventlistener9) instead. **System capability**: SystemCapability.Utils.Lang @@ -1046,19 +1559,22 @@ Removes an event listener for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeEventListener("alert"); ``` ### dispatchEvent(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [dispatchEvent9+](#dispatchevent9) instead. - dispatchEvent(event: Event): boolean Dispatches the event defined for the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [dispatchEvent9+](#dispatchevent9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1077,46 +1593,119 @@ Dispatches the event defined for the worker thread. ```js const workerInstance = new worker.Worker("workers/worker.js"); -workerInstance.dispatchEvent({type:"alert"}); -``` +// Usage 1: +workerInstance.on("alert_on", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.once("alert_once", (e)=>{ + console.log("alert listener callback"); +}) +workerInstance.addEventListener("alert_add", (e)=>{ + console.log("alert listener callback"); +}) +// The event listener created by once is removed after being executed once. +workerInstance.dispatchEvent({type:"alert_once", timeStamp:0});// timeStamp is not supported yet. +// The event listener created by on will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_on", timeStamp:0}); +// The event listener created by addEventListener will not be proactively deleted. +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); +workerInstance.dispatchEvent({type:"alert_add", timeStamp:0}); + +// Usage 2: +// The event type can be customized, and the special types "message", "messageerror", and "error" exist. +// When type = "message", the event handler defined by onmessage will also be executed. +// When type = "messageerror", the event handler defined by onmessageerror will also be executed. +// When type = "error", the event handler defined by onerror will also be executed. +// removeEventListener or off can be used to remove an event listener that is created by addEventListener, on, or once. + +workerInstance.addEventListener("message", (e)=>{ + console.log("message listener callback"); +}) +workerInstance.onmessage = function(e) { + console.log("onmessage : message listener callback"); +} +// When dispatchEvent is called to distribute the "message" event, the callback passed in addEventListener and onmessage will be invoked. +workerInstance.dispatchEvent({type:"message", timeStamp:0}); +``` ### removeAllListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [removeAllListener9+](#removealllistener9) instead. - removeAllListener(): void Removes all event listeners for the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [removeAllListener9+](#removealllistener9) instead. + **System capability**: SystemCapability.Utils.Lang **Example** ```js const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.addEventListener("alert", (e)=>{ + console.log("alert listener callback"); +}) workerInstance.removeAllListener(); ``` ## DedicatedWorkerGlobalScope(deprecated) +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). + > **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. +> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9) instead. -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). +### postMessage9+ +postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; -### postMessage(deprecated) +Sends a message to the host thread from the worker thread. -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. +**System capability**: SystemCapability.Utils.Lang + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------- | ---- | ----------------------------------------------------- | +| message | Object | Yes | Message to be sent to the worker thread. | +| transfer | ArrayBuffer[] | Yes | An **ArrayBuffer** object can be transferred. The value **null** should not be passed in the array.| + +**Example** + +```js +// main.js +import worker from '@ohos.worker'; +const workerInstance = new worker.Worker("workers/worker.js"); +workerInstance.postMessage("hello world"); +workerInstance.onmessage = function(e) { + // let data = e.data; + console.log("receive data from worker.js"); +} +``` +```js +// worker.js +import worker from '@ohos.worker'; +const parentPort = worker.parentPort; +parentPort.onmessage = function(e){ + // let data = e.data; + let buffer = new ArrayBuffer(5) + parentPort.postMessage(buffer, [buffer]); +} +``` + +### postMessage(deprecated) postMessage(messageObject: Object, options?: PostMessageOptions): void Sends a message to the host thread from the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).postMessage9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1148,16 +1737,15 @@ parentPort.onmessage = function(e){ } ``` - ### close(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. - close(): void Terminates the worker thread to stop it from receiving messages. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).close9+ instead. + **System capability**: SystemCapability.Utils.Lang **Example** @@ -1179,20 +1767,21 @@ parentPort.onmessage = function(e) { ### onmessage(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. - -onmessage?: (event: MessageEvent\) => void +onmessage?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void 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. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessage9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ------------------------ | -| event | [MessageEvent](#messageevent) | No | Message received.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------------------------------------ | ---- | ------------------------ | +| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller. | +| ev | [MessageEvent](#messageevent) | Yes | Message received.| **Example** @@ -1214,20 +1803,21 @@ parentPort.onmessage = function(e) { ### onmessageerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. - -onmessageerror?: (event: MessageEvent\) => void +onmessageerror?: (this: DedicatedWorkerGlobalScope, ev: MessageEvent) => void Defines the event handler to be called when the worker thread receives a message that cannot be deserialized. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [ThreadWorkerGlobalScope9+](#threadworkerglobalscope9).onmessageerror9+ instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ----------------------------- | ---- | ---------- | -| event | [MessageEvent](#messageevent) | No | Error data.| +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | ---------- | +| this | [DedicatedWorkerGlobalScope](#dedicatedworkerglobalscopedeprecated) | Yes | Caller.| +| ev | [MessageEvent](#messageevent)| Yes | Error data.| **Example** @@ -1240,7 +1830,7 @@ const workerInstance = new worker.Worker("workers/worker.js"); // worker.js import worker from '@ohos.worker'; const parentPort = worker.parentPort; -parentPort.onmessageerror= function(e) { +parentPort.onmessageerror = function(e) { console.log("worker.js onmessageerror") } ``` @@ -1252,7 +1842,7 @@ Specifies the object whose ownership needs to be transferred during data transfe **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | +| Name | Type | Readable| Writable| Description | | -------- | -------- | ---- | ---- | --------------------------------- | | transfer | Object[] | Yes | Yes | **ArrayBuffer** array used to transfer the ownership.| @@ -1263,21 +1853,21 @@ Defines the event. **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | -| --------- | -------- | ---- | ---- | ---------------------------------- | -| type | string | Yes | No | Type of the event. | -| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created.| +| Name | Type | Readable| Writable| Description | +| --------- | ------ | ---- | ---- | -------------------------------------------- | +| type | string | Yes | No | Type of the event. | +| timeStamp | number | Yes | No | Timestamp (accurate to millisecond) when the event is created. This parameter is not supported yet.| ## EventListener(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [WorkerEventListener9+](#workereventlistener9) instead. - (evt: Event): void | Promise<void> Implements event listening. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [WorkerEventListener9+](#workereventlistener9) instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** @@ -1308,38 +1898,38 @@ Provides detailed information about the exception that occurs during worker exec **System capability**: SystemCapability.Utils.Lang -| Name | Type| Readable| Writable| Description | -| -------- | -------- | ---- | ---- | -------------------- | -| message | string | Yes | No | Information about the exception.| -| filename | string | Yes | No | File where the exception is located.| -| lineno | number | Yes | No | Serial number of the line where the exception is located. | -| colno | number | Yes | No | Serial number of the column where the exception is located. | -| error | Object | Yes | No | Type of the exception. | +| Name | Type | Readable| Writable| Description | +| -------- | ------ | ---- | ---- | -------------------- | +| message | string | Yes | No | Information about the exception.| +| filename | string | Yes | No | File where the exception is located.| +| lineno | number | Yes | No | Serial number of the line where the exception is located. | +| colno | number | Yes | No | Serial number of the column where the exception is located. | +| error | Object | Yes | No | Type of the exception. | -## MessageEvent +## MessageEvent\ Holds the data transferred between worker threads. **System capability**: SystemCapability.Utils.Lang | Name| Type| Readable| Writable| Description | -| ---- | -------- | ---- | ---- | ------------------ | -| data | T | Yes | No | Data transferred between threads.| +| ---- | ---- | ---- | ---- | ------------------ | +| data | T | Yes | No | Data transferred between threads.| ## WorkerGlobalScope(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9) instead. - Implements the running environment of the worker thread. The **WorkerGlobalScope** class inherits from [EventTarget](#eventtarget). +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9) instead. + ### Attributes **System capability**: SystemCapability.Utils.Lang -| Name| Type | Readable| Writable| Description | +| Name| Type | Readable| Writable| Description | | ---- | ------------------------------------------------------------ | ---- | ---- | ------------------------------------- | | name | string | Yes | No | **Worker** instance specified when there is a new **Worker** instance.| | self | [WorkerGlobalScope](#workerglobalscope) & typeof globalThis | Yes | No | **WorkerGlobalScope**. | @@ -1347,20 +1937,20 @@ Implements the running environment of the worker thread. The **WorkerGlobalScope ### onerror(deprecated) -> **NOTE**
-> This API is deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. - onerror?: (ev: ErrorEvent) => void Defines the event handler to be called when an exception occurs during worker execution. The event handler is executed in the worker thread. +> **NOTE**
+> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [GlobalScope9+](#globalscope9).onerror instead. + **System capability**: SystemCapability.Utils.Lang **Parameters** | Name| Type | Mandatory| Description | | ------ | ------------------------- | ---- | ---------- | -| ev | [ErrorEvent](#errorevent) | No | Error data.| +| ev | [ErrorEvent](#errorevent) | Yes | Error data.| **Example** @@ -1402,7 +1992,7 @@ Exception: When an object created through a custom class is passed, no serializa ```js // main.js import worker from '@ohos.worker'; -const workerInstance = new worker.Thread("workers/worker.js"); +const workerInstance = new worker.ThreadWorker("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. @@ -1412,17 +2002,14 @@ workerInstance.onmessage = function(d) { ```js // worker.js import worker from '@ohos.worker'; -const parentPort = worker.workerPort; +const workerPort = worker.workerPort; class MyModel { + name = "undefined" Init() { - this.name = "wzy" - this.age = 18 - } - SetName() { - this.name = "WZY" + this.name = "MyModel" } } -parentPort.onmessage = function(d) { +workerPort.onmessage = function(d) { console.log("worker.js onmessage"); let data = d.data; let func1 = function() { @@ -1436,14 +2023,14 @@ parentPort.onmessage = function(d) { } } 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. + // workerPort.postMessage(func1); A serialization error occurs when passing func1. + // workerPort.postMessage(obj1); A serialization error occurs when passing obj1. + workerPort.postMessage(obj2); // No serialization error occurs when passing obj2. } -parentPort.onmessageerror = function(e) { +workerPort.onmessageerror = function(e) { console.log("worker.js onmessageerror"); } -parentPort.onerror = function(e) { +workerPort.onerror = function(e) { console.log("worker.js onerror"); } ``` @@ -1460,6 +2047,8 @@ Each actor concurrently processes tasks of the main thread. For each actor, ther - To proactively destroy a worker thread, you can call **terminate()** or **parentPort.close()** of the newly created **Worker** instance. - Since API version 9, if a **Worker** instance in a non-running state (such as destroyed or being destroyed) calls an API, a business error is thrown. - Creating and terminating worker threads consume performance. Therefore, you are advised to manage available workers and reuse them. +- Do not use both **new worker.Worker** and **new worker.ThreadWorker** to create a **Worker** project. Otherwise, **Worker** functions abnormally. Since API version 9, you are advised to use [new worker.ThreadWorker](#constructor9). In API version 8 and earlier versions, you are advised to use [new worker.Worker](#constructordeprecated). +- When creating a **Worker** project, do not import any UI construction method (such as .ets file) to the worker thread file (for example, **worker.ts** used in this document). Otherwise, the worker module becomes invalid. To check whether any UI construction method has been imported, decompress the generated HAP file, find **worker.js** in the directory where the worker thread is created, and search for the keyword **View** globally. If the keyword exists, a UI construction method has been packaged in **worker.js**. If this is your case, change the directory level of **src** in the statement **import "xxx" from src** in the worker thread file. ## Sample Code > **NOTE**
@@ -1500,23 +2089,23 @@ workerInstance.onexit = function() { import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. -const parentPort = worker.workerPort +const workerPort = worker.workerPort // In versions earlier than API version 9, use the following to 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) { +workerPort.onmessage = function(e) { // data carries the information sent by the main thread. let data = e.data; console.log("worker.ts onmessage"); // The worker thread sends information to the main thread. - parentPort.postMessage("123") + workerPort.postMessage("123") } // Trigger a callback when an error occurs in the worker thread. -parentPort.onerror= function(e) { +workerPort.onerror= function(e) { console.log("worker.ts onerror"); } ``` @@ -1525,7 +2114,7 @@ Configuration of the **build-profile.json5** file: "buildOption": { "sourceOption": { "workers": [ - "./src/main/ets/MainAbility/workers/worker.ts" + "./src/main/ets/entryability/workers/worker.ts" ] } } @@ -1562,20 +2151,20 @@ workerInstance.onexit = function() { import worker from '@ohos.worker'; // Create an object in the worker thread for communicating with the main thread. -const parentPort = worker.workerPort +const workerPort = worker.workerPort // The worker thread receives information from the main thread. -parentPort.onmessage = function(e) { +workerPort.onmessage = function(e) { // data carries the information sent by the main thread. let data = e.data; console.log("worker.ts onmessage"); // The worker thread sends information to the main thread. - parentPort.postMessage("123") + workerPort.postMessage("123") } // Trigger a callback when an error occurs in the worker thread. -parentPort.onerror= function(e) { +workerPort.onerror= function(e) { console.log("worker.ts onerror"); } ``` @@ -1589,3 +2178,4 @@ Configuration of the **build-profile.json5** file: } } ``` + diff --git a/en/application-dev/reference/apis/js-apis-xml.md b/en/application-dev/reference/apis/js-apis-xml.md index 945c5219bedb22f5efdd6f53b5d55d4cdd97f260..2f793c39a2234eb16b30d634d53279d1b1c70de3 100644 --- a/en/application-dev/reference/apis/js-apis-xml.md +++ b/en/application-dev/reference/apis/js-apis-xml.md @@ -1,4 +1,4 @@ -# XML Parsing and Generation +# @ohos.xml (XML Parsing and Generation) > **NOTE** > @@ -24,17 +24,24 @@ A constructor used to create an **XmlSerializer** instance. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** for storing the XML information to write.| -| encoding | string | No| Encoding format.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------------ | +| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** for storing the XML information to write.| +| encoding | string | No | Encoding format. | **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); +let arrayBuffer = new ArrayBuffer(2048); +let thatSer = new xml.XmlSerializer(arrayBuffer,"utf-8"); +thatSer.setDeclaration(); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -48,20 +55,27 @@ Sets an attribute. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Key of the attribute.| -| value | string | Yes| Value of the attribute.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | --------------- | +| name | string | Yes | Key of the attribute. | +| value | string | Yes | Value of the attribute.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); -thatSer.setAttributes("importance", "high"); +thatSer.setAttributes("importance1", "high1"); thatSer.endElement(); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -75,17 +89,24 @@ Adds an empty element. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the empty element to add.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| name | string | Yes | Name of the empty element to add.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.addEmptyElement("b"); // => +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.addEmptyElement("d"); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -100,10 +121,20 @@ Sets a declaration. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); -thatSer.setDeclaration() // => ; +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // ``` @@ -117,20 +148,29 @@ Writes the start tag based on the given element name. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| name | string | Yes| Name of the element.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| name | string | Yes | Name of the element.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.startElement("notel"); -thatSer.endElement();// => ''; +thatSer.setDeclaration(); +thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` - ### endElement endElement(): void @@ -142,14 +182,20 @@ Writes the end tag of the element. **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); -let bufView = new DataView(arrayBuffer); -let thatSer = new xml.XmlSerializer(bufView); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); +let thatSer = new xml.XmlSerializer(arrayBuffer); +thatSer.setDeclaration(); thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); -thatSer.startElement("table"); -thatSer.setAttributes("importance", "high"); -thatSer.setText("Happy"); -thatSer.endElement(); // => Happy +thatSer.startElement("note"); +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` @@ -163,20 +209,28 @@ Sets the namespace for an element tag. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| prefix | string | Yes| Prefix of the element and its child elements.| -| namespace | string | Yes| Namespace to set.| +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | ------------------------------ | +| prefix | string | Yes | Prefix of the element and its child elements. | +| namespace | string | Yes | Namespace to set.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.setDeclaration(); thatSer.setNamespace("h", "http://www.w3.org/TR/html4/"); thatSer.startElement("note"); -thatSer.endElement();// = >'\r\n'; +thatSer.endElement(); +let result = '\r\n'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(JSON.stringify(view1)) //\r\n ``` ### setComment @@ -189,18 +243,24 @@ Sets the comment. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Comment to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------- | +| text | string | Yes | Comment to set.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.startElement("note"); -thatSer.setComment("Hi!"); -thatSer.endElement(); // => '\r\n \r\n'; +thatSer.setComment("Hello, World!"); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //' ``` @@ -214,16 +274,24 @@ Sets CDATA attributes. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| CDATA attribute to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ----------------- | +| text | string | Yes | CDATA attribute to set.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1028); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.setCDATA('root SYSTEM') // => ''; +thatSer.setCDATA('root SYSTEM') +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //''' ``` @@ -237,19 +305,27 @@ Sets **Text**. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Content of the **Text** to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ---------------- | +| text | string | Yes | Content of the **Text** to set.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); thatSer.startElement("note"); thatSer.setAttributes("importance", "high"); thatSer.setText("Happy1"); -thatSer.endElement(); // => 'Happy1'; +thatSer.endElement(); +let result = 'Happy1'; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) // 'Happy1' ``` @@ -263,16 +339,24 @@ Sets **DocType**. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| text | string | Yes| Content of **DocType** to set.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------- | +| text | string | Yes | Content of **DocType** to set.| **Example** ```js -let arrayBuffer = new ArrayBuffer(1024); +const myMAX = 2048; +let arrayBuffer = new ArrayBuffer(myMAX); let thatSer = new xml.XmlSerializer(arrayBuffer); -thatSer.setDocType('root SYSTEM'); // => ''; +thatSer.setDocType('root SYSTEM "http://www.test.org/test.dtd"'); +let result = ''; +let view = new Uint8Array(arrayBuffer); +let view1 = ""; +for (let i = 0; i < result.length; ++i) { + view1 = view1 + String.fromCodePoint(view[i]); +} +console.log(view1) //'' ``` @@ -289,28 +373,49 @@ Creates and returns an **XmlPullParser** object. The **XmlPullParser** object pa **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| buffer | ArrayBuffer \| DataView | Yes| **ArrayBuffer** or **DataView** that contains XML text information.| -| encoding | string | No| Encoding format. Only UTF-8 is supported.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------------- | ---- | ------------------------------------------ | +| buffer | ArrayBuffer \| DataView | Yes | **ArrayBuffer** or **DataView** that contains XML text information.| +| encoding | string | No | Encoding format. Only UTF-8 is supported. | **Example** ```js let strXml = - '' + - '' + - ' Happy' + - ' Work' + - ' Play' + - ''; + '' + + ']>' + + '' + + ' ' + + ' ' + + ' John & Hans' + + ' Happy' + + ' Happy' + + ' Work' + + ' Play' + + ' ' + + ' ' + + ' ' + + ' ' + + ' Apples' + + ' Bananas' + + ' ' + + ' ' + + ''; let arrayBuffer = new ArrayBuffer(strXml.length); let bufView = new Uint8Array(arrayBuffer); let strLen = strXml.length; -for (var i = 0; i < strLen; ++i) { - bufView[i] = strXml.charCodeAt(i);// Set the ArrayBuffer mode. +for (let i = 0; i < strLen; ++i) { + bufView[i] = strXml.charCodeAt(i); } -let that = new xml.XmlPullParser(arrayBuffer); +let that = new xml.XmlPullParser(arrayBuffer, 'UTF-8'); +let str1 = ''; +function func1(name, value){ + str1 += name+':'+value; + return true; +} +let options = {supportDoctype:true, ignoreNameSpace:true, tagValueCallbackFunction:func1} +that.parse(options); +console.log(str1) //'note:company:title:title:lens:lens:a:b:h:table:h:tr:h:td:h:td:' ``` @@ -324,9 +429,9 @@ Parses XML information. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| option | [ParseOptions](#parseoptions) | Yes| Options for controlling and obtaining the parsed information.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------------- | ---- | -------------------------------- | +| option | [ParseOptions](#parseoptions) | Yes | Options for controlling and obtaining the parsed information.| **Example** @@ -341,7 +446,7 @@ let strXml = let arrayBuffer = new ArrayBuffer(strXml.length); let bufView = new Uint8Array(arrayBuffer); let strLen = strXml.length; -for (var tmp = 0; tmp < strLen; ++tmp) { +for (let tmp = 0; tmp < strLen; ++tmp) { bufView[tmp] = strXml.charCodeAt(tmp); } let that = new xml.XmlPullParser(arrayBuffer); @@ -372,13 +477,13 @@ Defines the XML parsing options. **System capability**: SystemCapability.Utils.Lang -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| supportDoctype | boolean | No| Whether to ignore **Doctype**. The default value is **false**.| -| ignoreNameSpace | boolean | No| Whether to ignore **Namespace**. The default value is **false**.| -| tagValueCallbackFunction | (name: string, value: string)=> boolean | No| Callback used to return **tagValue**.| -| attributeValueCallbackFunction | (name: string, value: string)=> boolean | No| Callback used to return **attributeValue**.| -| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo))=> boolean | No| Callback used to return **tokenValue**.| +| Name | Type | Mandatory| Description | +| ------------------------------ | ------------------------------------------------------------ | ---- | --------------------------------------- | +| supportDoctype | boolean | No | Whether to ignore **Doctype**. The default value is **false**.| +| ignoreNameSpace | boolean | No | Whether to ignore **Namespace**. The default value is **false**. | +| tagValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **tagValue**. | +| attributeValueCallbackFunction | (name: string, value: string) => boolean | No | Callback used to return **attributeValue**. | +| tokenValueCallbackFunction | (eventType: [EventType](#eventtype), value: [ParseInfo](#parseinfo)) => boolean | No | Callback used to return **tokenValue**. | ## ParseInfo @@ -395,10 +500,42 @@ Obtains the column line number, starting from 1. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------- | | number | Column number obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getColumnNumber(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:1key:2 value:77key:10 value:81key:2 value:88key:4 value:93key:3 value:101key:10 value:105key:2 value:111key:4 value:115key:3 value:122key:10 value:126key:2 value:132key:4 value:136key:3 value:143key:3 value:150key:1 value:299 +``` ### getDepth @@ -410,10 +547,45 @@ Obtains the depth of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------------- | | number | Depth obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getDepth(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:0key:2 value:1key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:10 value:1key:2 value:2key:4 value:2key:3 value:2key:3 value:1key:1 value:0 +// Note: +// key indicates the event type, and value indicates the parsing depth. You can learn the specific parsed event based on EVENTTYPE. In this example, key: value means: +// 0(START_DOCUMENT):0 (START_DOCUMENT is being parsed, and the depth is 0), 2(START_TAG):1 (START_TAG is being parsed, and the depth is 1), 10(WHITESPACE):1 (WHITESPACE is being parsed, and the depth is 1), 2(START_TAG):2 (START_TAG is being parsed, and the depth is 2), ... +``` ### getLineNumber @@ -425,10 +597,42 @@ Obtains the current line number, starting from 1. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | -------------- | | number | Line number obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getLineNumber(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:1key:2 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:10 value:1key:2 value:1key:4 value:1key:3 value:1key:3 value:1key:1 value:1 +``` ### getName @@ -440,11 +644,42 @@ Obtains the name of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------ | | string | Element name obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getName(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:notekey:10 value:key:2 value:titlekey:4 value:key:3 value:titlekey:10 value:key:2 value:todokey:4 value:key:3 value:todokey:10 value:key:2 value:todokey:4 value:key:3 value:todokey:3 value:notekey:1 value: +``` ### getNamespace getNamespace(): string @@ -455,11 +690,42 @@ Obtains the namespace of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------------ | | string | Namespace obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getNamespace(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:3 value:key:1 value: +``` ### getPrefix getPrefix(): string @@ -470,10 +736,42 @@ Obtains the prefix of this element. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------ | | string | Element prefix obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getPrefix(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:10 value:key:2 value:key:4 value:key:3 value:key:3 value:key:1 value: +``` ### getText @@ -485,11 +783,42 @@ Obtains the text of the current event. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ------------------------ | | string | Text content obtained.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getText(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:key:2 value:key:10 value: key:2 value:key:4 value:Happykey:3 value:key:10 value: key:2 value:key:4 value:Workkey:3 value:key:10 value: key:2 value:key:4 value:Playkey:3 value:key:3 value:key:1 value: +``` ### isEmptyElementTag isEmptyElementTag(): boolean @@ -500,11 +829,42 @@ Checks whether the current element is empty. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | ---------------------------- | | boolean | Returns **true** if the element is empty; returns **false** otherwise.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.isEmptyElementTag(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:falsekey:2 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:10 value:falsekey:2 value:falsekey:4 value:falsekey:3 value:falsekey:3 value:falsekey:1 value:false +``` ### isWhitespace isWhitespace(): boolean @@ -515,11 +875,42 @@ Checks whether the current text event contains only whitespace characters. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------- | -------------------------------------- | | boolean | Returns **true** if the text event contains only whitespace characters; returns **false** otherwise.| +**Example** +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.isWhitespace(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:truekey:2 value:falsekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:10 value:truekey:2 value:truekey:4 value:falsekey:3 value:truekey:3 value:truekey:1 value:true +``` ### getAttributeCount getAttributeCount(): number @@ -529,10 +920,42 @@ Obtains the number of attributes for the current start tag. **System capability**: SystemCapability.Utils.Lang **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------ | ---------------------- | | number | Number of attributes obtained.| +**Example** + +```js +let strXml = + '' + + '' + + ' Happy' + + ' Work' + + ' Play' + + ''; +let arrayBuffer = new ArrayBuffer(strXml.length); +let bufView = new Uint8Array(arrayBuffer); +let strLen = strXml.length; +for (let tmp = 0; tmp < strLen; ++tmp) { + bufView[tmp] = strXml.charCodeAt(tmp); +} +let that = new xml.XmlPullParser(arrayBuffer); +let arrTag = {}; +let str = ""; +let i = 0; +function func(key, value){ + arrTag[i] = 'key:'+key+' value:'+ value.getAttributeCount(); + str += arrTag[i]; + i++; + return true; // Determines whether to continuely parse, which is used to continue or terminate parsing. +} +let options = {supportDoctype:true, ignoreNameSpace:true, tokenValueCallbackFunction:func} +that.parse(options); +console.log(str); +// Output: +// key:0 value:0key:2 value:2key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:10 value:0key:2 value:0key:4 value:0key:3 value:0key:3 value:0key:1 value:0 +``` ## EventType @@ -540,16 +963,16 @@ Enumerates the events. **System capability**: SystemCapability.Utils.Lang -| Name| Value| Description| -| -------- | -------- | -------- | -| START_DOCUMENT | 0 | Indicates a start document event.| -| END_DOCUMENT | 1 | Indicates an end document event.| -| START_TAG | 2 | Indicates a start tag event.| -| END_TAG | 3 | Indicates an end tag event.| -| TEXT | 4 | Indicates a text event.| -| CDSECT | 5 | Indicates a CDATA section event.| -| COMMENT | 6 | Indicates an XML comment event.| -| DOCDECL | 7 | Indicates an XML document type declaration event.| -| INSTRUCTION | 8 | Indicates an XML processing instruction event.| -| ENTITY_REFERENCE | 9 | Indicates an entity reference event.| -| WHITESPACE | 10 | Indicates a whitespace character event.| +| Name | Value | Description | +| ---------------- | ---- | --------------------- | +| START_DOCUMENT | 0 | Indicates a start document event. | +| END_DOCUMENT | 1 | Indicates an end document event. | +| START_TAG | 2 | Indicates a start tag event. | +| END_TAG | 3 | Indicates an end tag event. | +| TEXT | 4 | Indicates a text event. | +| CDSECT | 5 | Indicates a CDATA section event. | +| COMMENT | 6 | Indicates an XML comment event. | +| DOCDECL | 7 | Indicates an XML document type declaration event.| +| INSTRUCTION | 8 | Indicates an XML processing instruction event.| +| ENTITY_REFERENCE | 9 | Indicates an entity reference event. | +| WHITESPACE | 10 | Indicates a whitespace character event. | diff --git a/en/application-dev/reference/apis/js-apis-zlib.md b/en/application-dev/reference/apis/js-apis-zlib.md index 967def0ecbdfda71fe88bc55ac02e6d395046a00..8ab71a62ddea41f2ffd92fd323fd46eada2614ad 100644 --- a/en/application-dev/reference/apis/js-apis-zlib.md +++ b/en/application-dev/reference/apis/js-apis-zlib.md @@ -1,6 +1,6 @@ -# zlib +# @ohos.zlib (Zip) -The **zlib** module provides APIs for file compression and decompression. +The **Zip** module provides APIs for file compression and decompression. > **NOTE** > @@ -25,9 +25,9 @@ Zips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to zip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| -| outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | -| options | [Options](#options) | No | Optional parameters for the zip operation. | +| inFile | string | Yes | Path of the folder or file to zip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| +| outFile | string | Yes | Path of the zipped file. The file name extension is .zip. | +| options | [Options](#options) | Yes | Optional parameters for the zip operation. | **Return value** @@ -39,6 +39,7 @@ Zips a file. This API uses a promise to return the result. ```typescript // Zip a file. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -59,6 +60,7 @@ zlib.zipFile(inFile, outFile, options).then((data) => { ```typescript // Zip a folder. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/xxx'; let outFile = '/xxx/xxx.zip'; @@ -89,9 +91,9 @@ Unzips a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to unzip. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| -| outFile | string | Yes | Path of the unzipped file. | -| options | [Options](#options) | No | Optional parameters for the unzip operation. | +| inFile | string | Yes | Path of the file to unzip. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| +| outFile | string | Yes | Path of the unzipped file. | +| options | [Options](#options) | Yes | Optional parameters for the unzip operation. | **Return value** @@ -103,6 +105,7 @@ Unzips a file. This API uses a promise to return the result. ```typescript // Unzip a file. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; @@ -131,24 +134,24 @@ Compresses a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | **Error codes** +For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). | ID| Error Message | -| ------ | -------------------------------------- | -| 401 | wrong param type | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| -------- | --------------------------------------| +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | **Example** ```typescript // Compress a file. -// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -160,12 +163,12 @@ let options = { try { zlib.compressFile(inFile, outFile, options, (errData) => { - if (erData !== null) { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + if (errData !== null) { + console.log(`errData is errCode:${errData.code} message:${errData.message}`); } }) } catch(errData) { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + console.log(`errData is errCode:${errData.code} message:${errData.message}`); } ``` @@ -179,21 +182,22 @@ Compresses a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the folder or file to compress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the folder or file to compress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the compressed file. | | options | [Options](#options) | Yes | Compression parameters. | **Error codes** +For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). + | ID| Error Message | -| ------ | -------------------------------------- | -| 401 | wrong param type | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| -------- | ------------------------------------- | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | ```typescript // Compress a file. -// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xxx/filename.xxx'; let outFile = '/xxx/xxx.zip'; @@ -207,10 +211,10 @@ try { zlib.compressFile(inFile, outFile, options).then((data) => { console.info('compressFile success'); }).catch((errData) => { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + console.log(`errData is errCode:${errData.code} message:${errData.message}`); }) } catch(errData) { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + console.log(`errData is errCode:${errData.code} message:${errData.message}`); } ``` @@ -228,24 +232,25 @@ Decompresses a file. This API uses an asynchronous callback to return the result | Name | Type | Mandatory| Description | | ----------------------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | | AsyncCallback<**void**> | callback | No | Callback used to return the result. If the operation is successful, **null** is returned; otherwise, a specific error code is returned. | **Error codes** -| ID| Error Message | -| ------ | -------------------------------------- | -| 401 | wrong param type | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). + +| ID| Error Message +| -------- | --------------------------------------| +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | **Example** ```typescript // Decompress a file. -// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; @@ -257,18 +262,18 @@ let options = { try { zlib.decompressFile(inFile, outFile, options, (errData) => { - if (erData !== null) { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + if (errData !== null) { + console.log(`errData is errCode:${errData.code} message:${errData.message}`); } }) } catch(errData) { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + console.log(`errData is errCode:${errData.code} message:${errData.message}`); } ``` decompressFile(inFile: string, outFile: string, options: Options): Promise\; -Decompress a file. This API uses a promise to return the result. +Decompresses a file. This API uses a promise to return the result. **System capability**: SystemCapability.BundleManager.Zlib @@ -276,21 +281,22 @@ Decompress a file. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ------- | ------------------- | ---- | ------------------------------------------------------------ | -| inFile | string | Yes | Path of the file to decompress. For details about the path, see [FA Model](js-apis-Context.md) or [Stage Model](js-apis-application-context.md).| +| inFile | string | Yes | Path of the file to decompress. The path must be an application sandbox path, which can be obtained from the context. For details about the context, see [FA Model](js-apis-inner-app-context.md) and [Stage Model] (js-apis-application-context.md).| | outFile | string | Yes | Path of the decompressed file. | | options | [Options](#options) | Yes | Decompression parameters. | **Error codes** +For details about the error codes, see [zlib Error Codes](../errorcodes/errorcode-zlib.md). + | ID| Error Message | -| ------ | -------------------------------------- | -| 401 | wrong param type | -| 900001 | The Input source file is invalid. | -| 900002 | The Input destination file is invalid. | +| ------ | ------------------------------------- | +| 900001 | The input source file is invalid. | +| 900002 | The input destination file is invalid. | ```typescript // Decompress a file. -// The path used in the code must be the application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through context. +// The path used in the code must be an application sandbox path, for example, /data/storage/el2/base/haps. You can obtain the path through the context. import zlib from '@ohos.zlib'; let inFile = '/xx/xxx.zip'; let outFile = '/xxx'; @@ -301,13 +307,13 @@ let options = { }; try { - zlib.deCompressFile(inFile, outFile, options).then((data) => { - console.info('deCompressFile success'); + zlib.decompressFile(inFile, outFile, options).then((data) => { + console.info('decompressFile success'); }).catch((errData) => { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + console.log(`errData is errCode:${errData.code} message:${errData.message}`); }) } catch(errData) { - console.log(`errData is errCode:${errData.errCode} message:${errData.message}`); + console.log(`errData is errCode:${errData.code} message:${errData.message}`); } ``` @@ -315,11 +321,11 @@ try { **System capability**: SystemCapability.BundleManager.Zlib -| Name | Type | Mandatory| Description | -| -------- | ---------------- | ---- | --------------------------------------------------------- | -| level | CompressLeve | No | See [zip.CompressLevel](#zipcompresslevel). | -| memLevel | MemLevel | No | See [zip.MemLevel](#zipmemlevel). | -| strategy | CompressStrategy | No | See [zip.CompressStrategy](#zipcompressstrategy).| +| Name | Type | Readable| Writable| Description | +| -------- | ---------------- | ---- | ---- | ---------------------------------------------------------- | +| level | CompressLevel | Yes | No | See [zip.CompressLevel](#zipcompresslevel). | +| memLevel | MemLevel | Yes | No | See [zip.MemLevel](#zipmemlevel). | +| strategy | CompressStrategy | Yes | No | See [zip.CompressStrategy](#zipcompressstrategy).| ## zip.CompressLevel