diff --git a/CODEOWNERS b/CODEOWNERS index cd5e192f6dfec673acfd1a1c594cb33b3a173978..8914fcf1ec8cc5ec63e710e9a9bbc511956cbb11 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -164,6 +164,24 @@ zh-cn/application-dev/reference/arkui-js/ @HelloCrease zh-cn/application-dev/reference/arkui-ts/ @HelloCrease zh-cn/application-dev/reference/native-apis @RayShih zh-cn/application-dev/reference/native-lib @RayShih +zh-cn/application-dev/quick-start/start-overview.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-js.md @ge-yafang +zh-cn/application-dev/quick-start/start-with-js-low-code.md @ge-yafang +zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang +zh-cn/application-dev/quick-start/package-structure.md @RayShih +zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih +zh-cn/application-dev/quick-start/syscap.md @RayShih +zh-cn/application-dev/napi/napi-guidelines.md @RayShih +zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang +zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease +zh-cn/application-dev/reference/js-service-widget-ui/ @HelloCrease +zh-cn/application-dev/website.md @zengyawen +zh-cn/application-dev/faqs/ @zengyawen +zh-cn/application-dev/file-management/ @qinxiaowang +zh-cn/application-dev/application-test/ @HelloCrease + zh-cn/application-dev/reference/apis/js-apis-DataUriUtils.md @RayShih zh-cn/application-dev/reference/apis/js-apis-ability-errorCode.md @RayShih zh-cn/application-dev/reference/apis/js-apis-ability-wantConstant.md @RayShih @@ -186,7 +204,6 @@ zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @RayShih zh-cn/application-dev/reference/apis/js-apis-service-extension-ability.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-StartOptions.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-staticSubscriberExtensionAbility.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-uripermissionmanager.md @RayShih zh-cn/application-dev/reference/apis/js-apis-application-Want.md @RayShih zh-cn/application-dev/reference/apis/js-apis-wantAgent.md @RayShih zh-cn/application-dev/reference/apis/js-apis-dataAbilityHelper.md @RayShih @@ -209,7 +226,7 @@ zh-cn/application-dev/reference/apis/js-apis-application-shellCmdResult.md @RayS zh-cn/application-dev/reference/apis/js-apis-commonEvent.md @RayShih zh-cn/application-dev/reference/apis/js-apis-emitter.md @RayShih zh-cn/application-dev/reference/apis/js-apis-notification.md @RayShih -zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-eventhub.md @RayShih zh-cn/application-dev/reference/apis/js-apis-Bundle.md @RayShih zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @RayShih @@ -277,15 +294,15 @@ zh-cn/application-dev/reference/apis/js-apis-http.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-request.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-socket.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-webSocket.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-tagSession.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-bluetooth.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfcTag.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfcTech.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-tagSession.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-connectedTag.md @RayShih zh-cn/application-dev/reference/apis/js-apis-rpc.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-wifi.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-wifiext.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-accessibility.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-wifi.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-wifiext.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-accessibility.md @RayShih zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hichecker.md @zengyawen @@ -293,31 +310,31 @@ zh-cn/application-dev/reference/apis/js-apis-hidebug.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hilog.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracechain.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-hitracemeter.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-inputmethod.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-inputmethodengine.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-pasteboard.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-system-time.md @zengyawen -zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-screen-lock.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-system-time.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-wallpaper.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-timer.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-battery-info.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-brightness.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-device-info.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-battery-info.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-brightness.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-device-info.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-device-manager.md -zh-cn/application-dev/reference/apis/js-apis-geolocation.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-geolocation.md @RayShih zh-cn/application-dev/reference/apis/js-apis-inputconsumer.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputdevice.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputeventclient.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-inputmonitor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-power.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-runninglock.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-power.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-runninglock.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-sensor.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-system-sensor.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @qinxiaowang -zh-cn/application-dev/reference/apis/js-apis-thermal.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-parameter.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-thermal.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-update.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-usb.md @ge-yafang -zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.mdd @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-colorSpaceManager.md @ge-yafang zh-cn/application-dev/reference/apis/js-apis-vibrator.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-appAccount.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @zengyawen @@ -349,24 +366,84 @@ zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @HelloCrease zh-cn/application-dev/reference/apis/js-apis-uiappearance.md @HelloCrease -zh-cn/application-dev/quick-start/start-overview.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-ets-low-code.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js.md @ge-yafang -zh-cn/application-dev/quick-start/start-with-js-low-code.md @ge-yafang -zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @ge-yafang -zh-cn/application-dev/quick-start/package-structure.md @RayShih -zh-cn/application-dev/quick-start/basic-resource-file-categories.md @RayShih -zh-cn/application-dev/quick-start/syscap.md @RayShih -zh-cn/application-dev/napi/napi-guidelines.md @RayShih -zh-cn/application-dev/napi/drawing-guidelines.md @ge-yafang -zh-cn/application-dev/napi/rawfile-guidelines.md @HelloCrease -zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen -zh-cn/application-dev/reference/js-service-widget-ui @HelloCrease -zh-cn/application-dev/website.md @zengyawen -zh-cn/application-dev/faqs/ @zengyawen zh-cn/application-dev/reference/apis/js-apis-useriam-faceauth.md @zengyawen zh-cn/application-dev/reference/apis/js-apis-userfilemanager.md @qinxiaowang zh-cn/application-dev/reference/apis/js-apis-cryptoFramework.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-buffer.md @zengyawen zh-cn/application-dev/reference/apis/Readme-CN.md @zengyawen -zh-cn/application-dev/file-management/ @qinxiaowang \ No newline at end of file +zh-cn/application-dev/reference/apis/development-intro.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-abilityLifecycleCallback.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-abilityManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-applicationContext.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-EnvironmentCallback.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-AbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ApplicationInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-BundleInstaller.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-CustomizeData.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-defaultAppManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ExtensionAbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-HapModuleInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle-InnerBundleManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-LauncherAbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-Metadata.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ModuleInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-PermissionDef.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bytrace.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-cardEmulation.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationExtraParams.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-continuation-continuationResult.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-dispatchInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-errorManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-inputevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-ability.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-inputmethod-extension-context.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-keycode.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-keyevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-logs.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-mouseevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-nfcController.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-nfctech.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-pointer.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-processrunninginformation.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-securityLabel.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-app.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-battery.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-bluetooth.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-brightness.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-configuration.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-device.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-fetch.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-file.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-system-location.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-mediaquery.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-network.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-notification.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-package.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-system-prompt.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-request.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-system-router.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-system-timer.md @ge-yafang +zh-cn/application-dev/reference/apis/js-apis-system-vibrate.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-touchevent.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-accessibility-config.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-application-quickFixManager.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-Bundle-BundleStatusCallback.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-bundle-PackInfo.md @RayShih +zh-cn/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md @HelloCrease +zh-cn/application-dev/reference/apis/js-apis-fileAccess.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-fileExtensionInfo.md @qinxiaowang +zh-cn/application-dev/reference/apis/js-apis-net-ethernet.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-net-policy.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-net-sharing.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-net-statistics.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-tlsSocket.md @zengyawen +zh-cn/application-dev/reference/apis/js-apis-reminderAgentManager.md @HelloCrease diff --git a/en/application-dev/ability/context-userguide.md b/en/application-dev/ability/context-userguide.md index d3e681244166cafecff86575dd1850db4ebf7f90..4abf217eee28052d3163d32aa0bce18893e1df08 100644 --- a/en/application-dev/ability/context-userguide.md +++ b/en/application-dev/ability/context-userguide.md @@ -56,7 +56,7 @@ The methods are used to set the display orientation of the current ability. **Example** ```javascript import featureAbility from '@ohos.ability.featureAbility' -import bundle from '../@ohos.bundle'; +import bundle from '@ohos.bundle'; export default { onCreate() { @@ -79,7 +79,7 @@ The following describes the contexts provided by the stage model in detail. ### application/Context -**application/Context** is the base class context that provides basic application information such as **resourceManager**, **applicationInfo**, **cacheDir**, and **area**. It also provides basic application methods such as **createBundleContext**. +**application/Context** is the base class context. It provides basic application information, such as **resourceManager**, **applicationInfo**, **cacheDir**, and **area**. It also provides basic application methods such as **createModuleContext**. **d.ts statement** diff --git a/en/application-dev/ability/figures/contextIntroduction.png b/en/application-dev/ability/figures/contextIntroduction.png index 7345a1a5a6a3471782e9399129c98f3d529bbfd5..50ec4d39f722431513051be8f6674f15307117f4 100644 Binary files a/en/application-dev/ability/figures/contextIntroduction.png and b/en/application-dev/ability/figures/contextIntroduction.png differ diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index fcd7a5dcfdde6547237f34f83dbb9bf2488d2255..3457aa29249a7c569053a09b6374cf03ce0d8868 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -12,8 +12,8 @@ An ability can be launched in the **standard**, **singleton**, or **specified** | Launch Type | Description |Action | | ----------- | ------- |---------------- | -| standard | Multi-instance | A new instance is started each time an ability starts.| -| singleton | Singleton | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| +| standard | Standard mode. | A new instance is started each time an ability starts.| +| singleton | Singleton mode. | The ability has only one instance in the system. If an instance already exists when an ability is started, that instance is reused.| | specified | Instance-specific| The internal service of an ability determines whether to create multiple instances during running.| By default, the singleton mode is used. The following is an example of the `module.json5` file: diff --git a/en/application-dev/database/database-datashare-guidelines.md b/en/application-dev/database/database-datashare-guidelines.md index 495f3b538b48b22d2d97f213d0e32189be799560..064c3e393fe27cedceb1f3f7d2d1e03b8ec22db6 100644 --- a/en/application-dev/database/database-datashare-guidelines.md +++ b/en/application-dev/database/database-datashare-guidelines.md @@ -52,9 +52,9 @@ Examples are given below. 3. Implement the data provider services. For example, implement data storage of the data provider by using a database, reading and writing files, or accessing the network. ```ts - let DB_NAME = "DB00.db"; - let TBL_NAME = "TBL00"; - let DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + const DB_NAME = "DB00.db"; + const TBL_NAME = "TBL00"; + const DDL_TBL_CREATE = "CREATE TABLE IF NOT EXISTS " + TBL_NAME + " (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, age INTEGER, isStudent BOOLEAN, Binary BINARY)"; @@ -132,9 +132,9 @@ Examples are given below. 1. Import the dependencies. ```ts - import Ability from '@ohos.application.Ability' - import dataShare from '@ohos.data.dataShare' - import dataSharePredicates from '@ohos.data.dataSharePredicates' + import Ability from '@ohos.application.Ability'; + import dataShare from '@ohos.data.dataShare'; + import dataSharePredicates from '@ohos.data.dataSharePredicates'; ``` 2. Define the URI string for communicating with the data provider. @@ -164,29 +164,25 @@ Examples are given below. ```ts // Construct a piece of data. - var valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; - var updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; - let da = new dataSharePredicates.DataSharePredicates(); - var valArray = new Array("*"); - let people = new Array( - { "name": "LiSi", "age": 41, "Binary": ar }, - { "name": "WangWu", "age": 21, "Binary": arr }, - { "name": "ZhaoLiu", "age": 61, "Binary": arr }); + let valuesBucket = { "name": "ZhangSan", "age": 21, "isStudent": false, "Binary": new Uint8Array([1, 2, 3]) }; + let updateBucket = { "name": "LiSi", "age": 18, "isStudent": true, "Binary": new Uint8Array([1, 2, 3]) }; + let predicates = new dataSharePredicates.DataSharePredicates(); + let valArray = new Array("*"); // Insert a piece of data. dsHelper.insert(dseUri, valuesBucket, (err, data) => { console.log("dsHelper insert result: " + data); }); - // Delete data. - dsHelper.delete(dseUri, da, (err, data) => { - console.log("dsHelper delete result: " + data); - }); // Update data. - dsHelper.update(dseUri, da, updateBucket, (err, data) => { + dsHelper.update(dseUri, predicates, updateBucket, (err, data) => { console.log("dsHelper update result: " + data); }); // Query data. - dsHelper.query(dseUri, da, valArray, (err, data) => { + dsHelper.query(dseUri, predicates, valArray, (err, data) => { console.log("dsHelper query result: " + data); }); + // Delete data. + dsHelper.delete(dseUri, predicates, (err, data) => { + console.log("dsHelper delete result: " + data); + }); ``` diff --git a/en/application-dev/database/database-datashare-overview.md b/en/application-dev/database/database-datashare-overview.md index f603c4dd54840118471cba6c344de58121577d57..019adeb3fa6850ed5407e0107d5996054ef11de7 100644 --- a/en/application-dev/database/database-datashare-overview.md +++ b/en/application-dev/database/database-datashare-overview.md @@ -22,7 +22,7 @@ Before you get started, familiarize yourself with the following concepts: An application that accesses the data or services provided by a data provider. It is also called a client. -- Value bucket (**ValuesBucket**) +- **ValuesBucket** One or more data records stored in the form of key-value (KV) pairs. The keys are of the string type. The values can be of the number, string, Boolean, or Unit8Array type. diff --git a/en/application-dev/database/database-distributedobject-overview.md b/en/application-dev/database/database-distributedobject-overview.md index 80985ed39b8c91a5c9635e0be8fd00f4be2da702..9fb93eba7c13f85da0cdccb9036df26e4d8d8ce0 100644 --- a/en/application-dev/database/database-distributedobject-overview.md +++ b/en/application-dev/database/database-distributedobject-overview.md @@ -12,7 +12,7 @@ The distributed data object management framework provides object-oriented in-mem - **Distributed data object** - A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **put** and **get** operations in the corresponding database, respectively. + A distributed data object is an encapsulation of the JS object type. Each distributed data object instance creates a data table in the in-memory database. The in-memory databases created for different applications are isolated from each other. Reading data from and writing data to a distributed data object are mapped to the **get** and **put** operations in the corresponding database, respectively. The distributed data object can be in the following states in its lifecycle: diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index 61aa2294c3f8ee077241e347e47e7780f50c4359..c4f6250f5ae91a645fe6aba6b81ec98df8eb2329 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -88,15 +88,22 @@ Use the following APIs to delete a **Preferences** instance or data file. 2. Obtain a **Preferences** instance. Read the specified file and load its data to the **Preferences** instance for data operations. - + FA model: ```js // Obtain the context. import featureAbility from '@ohos.ability.featureAbility' - var context = featureAbility.getContext() - + let context = featureAbility.getContext(); + + let preferences = null; let promise = data_preferences.getPreferences(context, 'mystore'); + + promise.then((pref) => { + preferences = pref; + }).catch((err) => { + console.info("Failed to get the preferences."); + }) ``` Stage model: @@ -104,14 +111,21 @@ Use the following APIs to delete a **Preferences** instance or data file. ```ts // Obtain the context. import Ability from '@ohos.application.Ability' - var context - class MainAbility extends Ability{ + let context = null; + let preferences = null; + export default class MainAbility extends Ability { onWindowStageCreate(windowStage){ - context = this.context + context = this.context; } } - + let promise = data_preferences.getPreferences(context, 'mystore'); + + promise.then((pref) => { + preferences = pref; + }).catch((err) => { + console.info("Failed to get the preferences."); + }) ``` 3. Write data. @@ -119,35 +133,27 @@ Use the following APIs to delete a **Preferences** instance or data file. Use the **preferences.put()** method to write data to the **Preferences** instance. ```js - promise.then((preferences) => { - let putPromise = preferences.put('startup', 'auto'); - putPromise.then(() => { - console.info("Put the value of 'startup' successfully."); - }).catch((err) => { - console.info("Failed to put the value of 'startup'. Cause: " + err); - }) + let putPromise = preferences.put('startup', 'auto'); + putPromise.then(() => { + console.info("Put the value of 'startup' successfully."); }).catch((err) => { - console.info("Failed to get the preferences."); + console.info("Failed to put the value of 'startup'. Cause: " + err); }) ``` - + 4. Read data. Use the **preferences.get()** method to read data. ```js - promise.then((preferences) => { - let getPromise = preferences.get('startup', 'default'); - getPromise.then((value) => { + let getPromise = preferences.get('startup', 'default'); + getPromise.then((value) => { console.info("The value of 'startup' is " + value); - }).catch((err) => { - console.info("Failed to get the value of 'startup'. Cause: " + err); - }) }).catch((err) => { - console.info("Failed to get the preferences.") - }); + console.info("Failed to get the value of 'startup'. Cause: " + err); + }) ``` - + 5. Store data persistently. Use the **flush()** method to flush data from the **Preferences** instance to its file. @@ -161,11 +167,12 @@ Use the following APIs to delete a **Preferences** instance or data file. Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. ```js - var observer = function (key) { + let observer = function (key) { console.info("The key" + key + " changed."); } preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { + // The data is changed from 'auto' to 'manual'. + preferences.put('startup', 'manual', function (err) { if (err) { console.info("Failed to put the value of 'startup'. Cause: " + err); return; diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md index bd38925cbe8a17e5cb6319ffc9729ef263945e9c..70fb8cbbee58dd51b8edacf8f7d6bc58e874859d 100644 --- a/en/application-dev/database/database-relational-guidelines.md +++ b/en/application-dev/database/database-relational-guidelines.md @@ -140,7 +140,7 @@ You can obtain the distributed table name for a remote device based on the local | Class | API | Description | | -------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of that device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| +| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.| **Registering an RDB Store Observer** diff --git a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md index f18f59468d0650400adfb50b87645c763a740b9c..60aa41fedd15531c583c48200eddc3c91e5a8fde 100644 --- a/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md +++ b/en/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md @@ -22,8 +22,8 @@ import stats from '@ohos.bundleState'; | function queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void | Queries the priority group of this application. This API uses an asynchronous callback to return the result.| | function queryAppUsagePriorityGroup(): Promise<number>; | Queries the priority group of this application. This API uses a promise to return the result.| | function isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void | Checks whether the application specified by **bundleName** is in the idle state. | -| function getRecentlyUsedModules(callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **1000**.| -| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**.| +| function getRecentlyUsedModules(callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains a maximum of 1000 FA usage records. | +| function getRecentlyUsedModules(maxNum: number, callback: AsyncCallback<BundleActiveModuleInfo>): void | Obtains the number of FA usage records specified by **maxNum**, which cannot exceed 1000.| | function queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries the number of notifications from all applications based on the specified start time and end time.| | function queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback<Array<BundleActiveEventState>>): void | Queries statistics about system events (hibernation, wakeup, unlocking, and screen locking) that occur between the specified start time and end time.| | function queryAppUsagePriorityGroup(bundleName : string, callback: AsyncCallback<number>): void | Queries the priority group of the application specified by **bundleName**. This API uses an asynchronous callback to return the result.| @@ -326,14 +326,14 @@ import stats from '@ohos.bundleState'; ```js import stats from '@ohos.bundleState' - // Promise mode without parameters + // Promise mode when bundleName is not specified stats.queryAppUsagePriorityGroup().then(res => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch(err => { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup promise failed. because: ' + err.code); }); - // Asynchronous callback mode without parameters + // Asynchronous callback mode when bundleName is not specified stats.queryAppUsagePriorityGroup((err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback failed. because: ' + err.code); @@ -341,16 +341,16 @@ import stats from '@ohos.bundleState'; console.log('BUNDLE_ACTIVE queryAppUsagePriorityGroup callback succeeded. result: ' + JSON.stringify(res)); } }); - - // Promise mode with parameters - stats.queryAppUsagePriorityGroup(this.bundleName).then(res => { + let bundleName = "com.ohos.camera"; + // Promise mode when bundleName is specified + stats.queryAppUsagePriorityGroup(bundleName).then(res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch(err => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); }); - // Asynchronous callback mode with parameters - stats.queryAppUsagePriorityGroup(this.bundleName, (err, res) => { + // Asynchronous callback mode when bundleName is specified + stats.queryAppUsagePriorityGroup(bundleName, (err, res) => { if (err) { console.log('BUNDLE_ACTIVE QueryPackageGroup callback failed. because: ' + err.code); } else { @@ -437,3 +437,4 @@ import stats from '@ohos.bundleState'; } }); ``` + diff --git a/en/application-dev/faqs/faqs-ui-ets.md b/en/application-dev/faqs/faqs-ui-ets.md index fd21421cd95edc2bc838b8401724fae10448d9fd..86a05c91851d6844dcc08e368d81b936b7d1b8ac 100644 --- a/en/application-dev/faqs/faqs-ui-ets.md +++ b/en/application-dev/faqs/faqs-ui-ets.md @@ -202,7 +202,7 @@ struct DialogTest { Applicable to: OpenHarmony SDK 3.2.5.3, stage model of API version 9 -The **\** component is a scrollable container. By default, it taks up the entire screen height. When any component with a fixed height takes up part of the screen height, you need to explicitly specify **layoutWeight(1)** for the parent container of the **\** component to take up the remaining height instead of the entire screen height. +The **\** component is a scrollable container. By default, it takes up the entire screen height. When any component with a fixed height takes up part of the screen height, you need to explicitly specify **layoutWeight(1)** for the parent container of the **\** component to take up the remaining height instead of the entire screen height. ## How do I center child components in a grid container? diff --git a/en/application-dev/faqs/faqs-ui-js.md b/en/application-dev/faqs/faqs-ui-js.md index 5d39db33199fddf298e66e4bd290999b58d6dddb..7d4ae1dcb80b63a4632e3a30627ff53f37e63c37 100644 --- a/en/application-dev/faqs/faqs-ui-js.md +++ b/en/application-dev/faqs/faqs-ui-js.md @@ -30,7 +30,7 @@ let options = {trim : false, declarationKey:"_declaration", nameKey : "_name", elementsKey : "_elements"} let result:any = conv.convert(xml, options) // Convert fields in the XML file into JavaScript objects. console.log('Test: ' + JSON.stringify(result)) -console.log('Test: ' + result._declaration._attributes.version) // vesion field in XML file +console.log('Test: ' + result._declaration._attributes.version) // version field in XML file console.log('Test: ' + result._elements[0]._elements[0]._elements[0]._text) // title field in XML file ``` diff --git a/en/application-dev/media/image.md b/en/application-dev/media/image.md index 8e6eca83375ea64b2948325fc1f7bf7f28746767..f3bb5fc9b59c8b290692e877033e78a5d9d4edef 100644 --- a/en/application-dev/media/image.md +++ b/en/application-dev/media/image.md @@ -21,45 +21,43 @@ let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { // Create a PixelMap object. const color = new ArrayBuffer(96); let opts = { alphaType: 0, editable: true, pixelFormat: 4, scaleMode: 1, size: { height: 2, width: 3 } } - image.createPixelMap(color, opts, pixelmap => { - expect(pixelmap !== null).assertTrue(); - console.info('TC_001-1 success'); - done(); - }) +image.createPixelMap(color, opts, pixelmap => { + console.log('Succeeded in creating pixelmap.'); +}) + // Read pixels. pixelmap.readPixels(area,(data) => { - if(data !== null) { - var bufferArr = new Uint8Array(area.pixels); + if(data !== null) { + var bufferArr = new Uint8Array(area.pixels); var res = true; for (var i = 0; i < bufferArr.length; i++) { - console.info('TC_021-1 buffer ' + bufferArr[i]); - if(res) { - if(bufferArr[i] == 0) { - res = false; - console.info('TC_021-1 Success'); - expect(true).assertTrue(); - done(); - break; - } - } + console.info(' buffer ' + bufferArr[i]); + if(res) { + if(bufferArr[i] == 0) { + res = false; + console.log('readPixels end.'); + break; } + } + } + } +}) // Store pixels. const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer,() => { -var bufferArr = new Uint8Array(readBuffer); -var res = true; -for (var i = 0; i < bufferArr.length; i++) { - if(res) { - if (bufferArr[i] !== 0) { - res = false; - console.info('TC_020-1 Success'); - expect(true).assertTrue(); - done(); - break; + var bufferArr = new Uint8Array(readBuffer); + var res = true; + for (var i = 0; i < bufferArr.length; i++) { + if(res) { + if (bufferArr[i] !== 0) { + res = false; + console.log('readPixelsToBuffer end.'); + break; + } } } -} +}) // Write pixels. pixelmap.writePixels(area,() => { @@ -71,56 +69,51 @@ pixelmap.writePixels(area,() => { if(res) { if (readArr[i] !== 0) { res = false; - console.info('TC_022-1 Success'); - expect(true).assertTrue(); - done(); + console.log('readPixels end.please check buffer'); break; } } } + }) +}) // Write pixels to the buffer. pixelmap.writeBufferToPixels(writeColor).then(() => { const readBuffer = new ArrayBuffer(96); pixelmap.readPixelsToBuffer(readBuffer).then (() => { - var bufferArr = new Uint8Array(readBuffer); - var res = true; - for (var i = 0; i < bufferArr.length; i++) { - if(res) { - if (bufferArr[i] !== i) { - res = false; - console.info('TC_023 Success'); - expect(true).assertTrue() - done(); + var bufferArr = new Uint8Array(readBuffer); + var res = true; + for (var i = 0; i < bufferArr.length; i++) { + if(res) { + if (bufferArr[i] !== i) { + res = false; + console.log('readPixels end.please check buffer'); break; } } } + }) +}) // Obtain image information. pixelmap.getImageInfo( imageInfo => { if (imageInfo !== null) { - console.info('TC_024-1 imageInfo is ready'); - expect(imageInfo.size.height == 4).assertTrue(); - expect(imageInfo.size.width == 6).assertTrue(); - expect(imageInfo.pixelFormat == 4).assertTrue(); - done(); + console.log('Succeeded in getting imageInfo'); } }) // Release the PixelMap object. pixelmap.release(()=>{ - expect(true).assertTrue(); - console.log('TC_027-1 suc'); - done(); + console.log('Succeeded in releasing pixelmap'); }) -let path = '/data/local/tmp/test.jpg'; // Create an image source (uri). -const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.jpg' +let path = '/data/local/tmp/test.jpg'; +const imageSourceApi = image.createImageSource(path); // Create an image source (fd). -const imageSourceApi = image.createImageSource(29); +let fd = 29; +const imageSourceApi = image.createImageSource(fd); // Create an image source (data). const data = new ArrayBuffer(96); @@ -128,15 +121,15 @@ const imageSourceApi = image.createImageSource(data); // Release the image source. imageSourceApi.release(() => { - console.info('TC_044-1 Success'); - }) + console.log('Succeeded in releasing imagesource'); +}) // Encode the image. const imagePackerApi = image.createImagePacker(); +const imageSourceApi = image.createImageSource(0); +let packOpts = { format:"image/jpeg", quality:98 }; imagePackerApi.packing(imageSourceApi, packOpts, data => { - console.info('TC_062-1 finished'); - expect(data !== null).assertTrue(); - done(); + console.log('Succeeded in packing'); }) // Release the ImagePacker object. @@ -164,59 +157,40 @@ let decodingOptions = { // Create a pixel map in callback mode. imageSourceApi.createPixelMap(decodingOptions, pixelmap => { - console.info('TC_050 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); - }) -} + console.log('Succeeded in creating pixelmap.'); +}) // Create a pixel map in promise mode. imageSourceApi.createPixelMap().then(pixelmap => { - console.info('TC_050-11 createPixelMap '); - expect(pixelmap !== null ).assertTrue(); - done(); + console.log('Succeeded in creating pixelmap.'); }) // Capture error information when an exception occurs during function invoking. catch(error => { - console.log('TC_050-11 error: ' + error); - expect().assertFail(); - done(); + console.log('Failed in creating pixelmap.' + error); }) // Obtain the number of bytes in each line of pixels. pixelmap.getBytesNumberPerRow( num => { - console.info('TC_025-1 num is ' + num); - expect(num == expectNum).assertTrue(); - done(); + console.log('Succeeded in getting BytesNumber PerRow.'); }) // Obtain the total number of pixel bytes. pixelmap.getPixelBytesNumber(num => { - console.info('TC_026-1 num is ' + num); - expect(num == expectNum).assertTrue(); - done(); + console.log('Succeeded in getting PixelBytesNumber.'); }) // Obtain the pixel map information. pixelmap.getImageInfo( imageInfo => {}) - -// Print the failure information. -console.info('TC_024-1 imageInfo is empty'); -expect(false).assertTrue() // Release the PixelMap object. pixelmap.release(()=>{ - expect(true).assertTrue(); - console.log('TC_027-1 suc'); - done(); + console.log('Succeeded in releasing pixelmap'); }) // Capture release failure information. catch(error => { - console.log('TC_027-1 error: ' + error); - expect().assertFail(); - done(); + console.log('Failed in releasing pixelmap.' + error); }) ``` @@ -230,9 +204,7 @@ const imageSourceApi = image.createImageSource(path); // '/data/local/tmp/test.p // Print the error message if the image source fails to be created. if (imageSourceApi == null) { - console.info('TC_062 create image source failed'); - expect(false).assertTrue(); - done(); + console.log('Failed in creating imageSource.'); } // Create an image packer if the image source is successfully created. @@ -240,9 +212,7 @@ const imagePackerApi = image.createImagePacker(); // Print the error information if the image packer fails to be created. if (imagePackerApi == null) { - console.info('TC_062 create image packer failed'); - expect(false).assertTrue(); - done(); + console.log('Failed in creating imagePacker.'); } // Set encoding parameters if the image packer is successfully created. @@ -252,19 +222,15 @@ let packOpts = { format:["image/jpeg"], // The supported encoding format is jpg. // Encode the image. imagePackerApi.packing(imageSourceApi, packOpts) .then( data => { - console.info('TC_062 finished'); - expect(data !== null).assertTrue(); - done(); + console.log('Succeeded in packing'); }) - + // Release the image packer after the encoding is complete. imagePackerApi.release(); // Obtain the image source information. imageSourceApi.getImageInfo(imageInfo => { - console.info('TC_045 imageInfo'); - expect(imageInfo !== null).assertTrue(); - done(); + console.log('Succeeded in getting imageInfo'); }) // Update incremental data. diff --git a/en/application-dev/napi/napi-guidelines.md b/en/application-dev/napi/napi-guidelines.md index f471f4a6eed7d3eb2c96dab8cae4cb7480a13616..188b4f1336e2c56562f594e42dc26cabf8a8fc55 100644 --- a/en/application-dev/napi/napi-guidelines.md +++ b/en/application-dev/napi/napi-guidelines.md @@ -17,11 +17,11 @@ You can `import` the native .so that contains the JS processing logic. For examp ### .so Naming Rules -Each module has a .so file. For example, if the module name is `hello`, name the .so file **libhello.so**. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. +Each module has a .so file. For example, if the module name is `hello`, name the .so file `libhello.so`. The `nm_modname` field in `napi_module` must be `hello`, which is the same as the module name. The sample code for importing the .so file is `import hello from 'libhello.so'`. ### JS Objects and Threads -The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. +The Ark engine prevents NAPIs from being called to operate JS objects in non-JS threads. Otherwise, the application will crash. Observe the following rules: * The NAPIs can be used only in JS threads. * **env** is bound to a thread and cannot be used across threads. The JS object created by a NAPI can be used only in the thread, in which the object is created, that is, the JS object is bound to the **env** of the thread. @@ -640,8 +640,3 @@ export default { } } ``` -## Samples -The following samples are provided for native API development: -- [`NativeAPI`: NativeAPI (eTS) (API8)](https://gitee.com/openharmony/app_samples/tree/master/Native/NativeAPI) -- [First Native C++ Application (eTS) (API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) -- [Native Component (eTS) (API9) ](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) diff --git a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md index 1894942945c53a4d36bc2f9c892de28359faa9ff..b789e20218f1d8508ce5dbf1b515179e6f23b9ef 100644 --- a/en/application-dev/notification/background-agent-scheduled-reminder-guide.md +++ b/en/application-dev/notification/background-agent-scheduled-reminder-guide.md @@ -37,9 +37,7 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind import reminderAgent from '@ohos.reminderAgent'; import notification from '@ohos.notification'; export default { - // For a JS project: - // timer: { - // For an eTS project: + // eTS project: let timer : reminderAgent.ReminderRequestTimer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 10, @@ -69,9 +67,7 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind Sample code for defining a reminder agent for a calendar event: ```js - // For a JS project: - // calendar: { - // For an eTS project: + // eTS project: let calendar : reminderAgent.ReminderRequestCalendar = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, dateTime: { @@ -117,9 +113,7 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind Sample code for defining a reminder agent for an alarm: ```js - // For a JS project: - // alarm: { - // For an eTS project: + // eTS project: let alarm : reminderAgent.ReminderRequestAlarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 11, @@ -171,4 +165,3 @@ For details about the APIs, see [reminderAgent](../reference/apis/js-apis-remind ``` - diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md index d5a6d7bdfbc6dcdd5b94d36e155d4650fc70630c..37d55ef434d0cec71eed60862e13f1de0d9e13fb 100644 --- a/en/application-dev/notification/common-event.md +++ b/en/application-dev/notification/common-event.md @@ -13,14 +13,14 @@ Each application can subscribe to common events as required. After your applicat ## Common Event Subscription Development ### When to Use -You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md). +You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#support). ### Available APIs | API | Description| | ---------------------------------------------------------------------------------------------- | ----------- | -| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| -| commonEvent.createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | -| commonEvent.subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| +| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.| +| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. | +| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.| ### How to Develop 1. Import the **commonEvent** module. @@ -82,8 +82,8 @@ You can use the **publish** APIs to publish a custom common event, which can car ### Available APIs | API | Description| | ---------------------------------- | ------ | -| commonEvent.publish(event: string, callback: AsyncCallback) | Publishes a common event.| -| commonEvent.publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| +| publish(event: string, callback: AsyncCallback) | Publishes a common event.| +| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.| ### How to Develop #### Development for Publishing a Common Event @@ -119,7 +119,7 @@ import commonEvent from '@ohos.commonEvent' // Attributes of a common event. var options = { code: 1, // Result code of the common event - data: "initial data",// Result data of the common event + data: "initial data";// Result data of the common event } ``` @@ -144,7 +144,7 @@ You can use the **unsubscribe** API to unsubscribe from a common event. ### Available APIs | API | Description| | ---------------------------------- | ------ | -| commonEvent.unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| +| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.| ### How to Develop 1. Import the **commonEvent** module. @@ -153,7 +153,7 @@ You can use the **unsubscribe** API to unsubscribe from a common event. import commonEvent from '@ohos.commonEvent'; ``` -2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#Common-Event-Subscription-Development). +2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#common-event-subscription-development). 3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event. ```js diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md index 8be39b2cc823398e4572a77469909f9fd06e2a5f..b1df6ce3e2c022accb06bc1070740b7d7b3e7433 100644 --- a/en/application-dev/notification/notification-brief.md +++ b/en/application-dev/notification/notification-brief.md @@ -7,16 +7,13 @@ Common Event Service (CES) enables applications to publish, subscribe to, and un ![ces](figures/ces.png) - System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events. - - Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications. - The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: +The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications: - - Display received SMS messages and instant messages. - - - Display push messages of applications, such as advertisements, version updates, and news notifications. - - - Display ongoing events, such as music playback, navigation information, and download progress. +- Display received SMS messages and instant messages. +- Display push messages of applications, such as advertisements, version updates, and news notifications. +- Display ongoing events, such as music playback, navigation information, and download progress. Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions. diff --git a/en/application-dev/quick-start/package-structure.md b/en/application-dev/quick-start/package-structure.md index 076bc9474ba724746938c1a4da837a3679c73d5a..6c1ecfe7be836e8b17dcb7d6d1045354d5aa386d 100644 --- a/en/application-dev/quick-start/package-structure.md +++ b/en/application-dev/quick-start/package-structure.md @@ -2,19 +2,19 @@ # Application Package Structure Configuration File -In an application development project, you need to declare the package structure of the application in the **config.json** file. +When developing an application in the Feature Ability (FA) model, you must declare the package structure of the application in the **config.json** file. ## Internal Structure of the config.json File -The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. See Table 1 for details. +The **config.json** file consists of three mandatory tags, namely, **app**, **deviceConfig**, and **module**. For details, see Table 1. Table 1 Internal structure of the config.json file | Tag | Description | Data Type| Initial Value Allowed| | ------------ | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of an application. Different HAP files of the same application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| deviceConfig | Application configuration applied to a specific type of device. For details, see [Internal Structure of the deviceconfig Tag](#internal-structure-of-the-deviceconfig-tag).| Object | No | -| module | Configuration of a HAP file. The **module** configuration is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | +| app | Global configuration of the application. Different HAP files of the same application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | +| deviceConfig | Application configuration applied to a specific type of device. For details, see [Internal Structure of the deviceconfig Tag](#internal-structure-of-the-deviceconfig-tag).| Object | No | +| module | Configuration of a HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | Example of the **config.json** file: @@ -86,12 +86,15 @@ The **app** tag contains the global configuration information of the application Table 2 Internal structure of the app tag -| Attribute | Description | Data Type| Initial Value Allowed | -| ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| bundleName | Bundle name of the application. It uniquely identifies the application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The value is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String | No | -| vendor | Description of the application vendor. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| version | Version information of the application. For details, see Table 3. | Object | No | -| apiVersion | OpenHarmony API version on which the application depends. For details, see Table 4. | Object | Yes (initial value: left empty)| +| Attribute | Description | Data Type| Initial Value Allowed | +| ----------------- | ------------------------------------------------------------ | -------- | --------------------------- | +| bundleName | Bundle name, which uniquely identifies an application. The bundle name can contain only letters, digits, underscores (_), and periods (.). It must start with a letter. The value is a string with 7 to 127 bytes of a reverse domain name, for example, **com.example.myapplication**. It is recommended that the first level be the domain suffix "com" and the second level be the vendor/individual name. More levels are also accepted.| String | No | +| vendor | Description of the application vendor. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | +| version | Version of the application. For details, see Table 3. | Object | No | +| apiVersion | OpenHarmony API version on which the application depends. For details, see Table 4. | Object | Yes (initial value: left empty) | +| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8.| Boolean | Yes (initial value: **false**)| +| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8. | Boolean | Yes (initial value: **true**) | +| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | Table 3 Internal structure of version @@ -99,7 +102,7 @@ Table 3 Internal structure of version | ------------------------ | ------------------------------------------------------------ | -------- | -------------------------- | | name | Application version number visible to users. The value can be customized and cannot exceed 127 bytes. The customization rules are as follows:
API 5 and earlier versions: A three-segment version number is recommended, for example, A.B.C (also compatible with A.B). In the version number, A, B, and C are integers ranging from 0 to 999. Other formats are not supported.
A indicates the major version number.
B indicates the minor version number.
C indicates the patch version number.
API 6 and later versions: A four-segment version number is recommended, for example, A.B.C.D. In the version number, A, B, and C are integers ranging from 0 to 99, and D is an integer ranging from 0 to 999.
A indicates the major version number.
B indicates the minor version number.
C indicates the feature version number.
D indicates the patch version number.| Number | No | | code | Application version number used only for application management by OpenHarmony. This version number is not visible to users of the application. The value rules are as follows:
API 5 and earlier versions: It is a non-negative integer less than 32 bits in binary mode, converted from the value of version.name as follows: The conversion rules are as follows:
Value of **code** = A * 1,000,000 + B * 1,000 + C. For example, if the value of **version.name** is 2.2.1, the value of **code** is 2002001.
API 6 and later versions: The value of **code** is not associated with the value of **version.name** and can be customized. The value is a non-negative integer ranging from 2 to 31. Note that the value must be updated each time the application version is updated. The value for a later version must be greater than that for an earlier version.| Number | No | -| minCompatibleVersionCode | Minimum compatible version of the application. It is used to check whether the application is compatible with the version on other devices in the cross-device scenario.
The value rules are the same as those of **version.code**.| Number | No (initial value: **code** attribute value)| +| minCompatibleVersionCode | Earliest version compatible with the application. It is used in the cross-device scenario to check whether the application is compatible with a specific version on other devices.
The value rules are the same as those of **version.code**.| Number | No (initial value: **code** attribute value)| Table 4 Internal structure of apiVersion @@ -116,15 +119,15 @@ Example of the app tag structure: "bundleName": "com.example.myapplication", "vendor": "example", "version": { - "code": 1, - "name": "1.0" + "code": 1, + "name": "1.0" }, "apiVersion": { - "compatible": 4, - "target": 5, - "releaseType": "Beta1" + "compatible": 4, + "target": 5, + "releaseType": "Beta1" } - } +} ``` ### Internal Structure of the deviceConfig Tag @@ -133,13 +136,13 @@ The **deviceConfig** tag contains the application configuration information on t Table 5 Internal structure of the deviceConfig tag -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------ | ----------------------------------------------- | -------- | ------------------ | -| default | Application configuration applied to all types of devices. See Table 6. | Object | No | -| tablet | Application configuration specific to tablets. See Table 6. | Object | Yes (initial value: left empty)| -| tv | Application configuration specific to smart TVs. See Table 6. | Object | Yes (initial value: left empty)| -| car | Application configuration specific to head units. See Table 6. | Object | Yes (initial value: left empty)| -| wearable | Application configuration specific to wearables. See Table 6. | Object | Yes (initial value: left empty)| +| Attribute| Description | Data Type| Initial Value Allowed | +| -------- | ----------------------------------------- | -------- | ------------------ | +| default | Application configuration applied to all types of devices. For details, see Table 6.| Object | No | +| tablet | Application configuration specific to tablets. For details, see Table 6. | Object | Yes (initial value: left empty)| +| tv | Application configuration specific to smart TVs. For details, see Table 6. | Object | Yes (initial value: left empty)| +| car | Application configuration specific to head units. For details, see Table 6. | Object | Yes (initial value: left empty)| +| wearable | Application configuration specific to wearables. For details, see Table 6.| Object | Yes (initial value: left empty)| For details about the internal structures of device attributes, see Table 6. @@ -147,12 +150,13 @@ Table 6 Internal structure of device attributes | Attribute | Description | Data Type| Initial Value Allowed | | ------------------ | ------------------------------------------------------------ | -------- | ----------------------- | -| process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. The value can contain a maximum of 31 characters.| String | Yes | +| process | Process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. The value can contain a maximum of 31 characters.| String | Yes | +| keepAlive | Whether the application is always kept alive. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | | supportBackup | Whether the application supports backup and restoration. The value **false** means that the application does not support backup or restoration.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**)| | compressNativeLibs | Whether the **libs** libraries are packaged in the HAP file after being compressed. The value **false** means that the **libs** libraries are stored without being compressed and will be directly loaded during the installation of the HAP file.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **true**) | | directLaunch | Whether the application can be started when the device is locked. The value **true** means that the application can be started when the device is locked. Devices running OpenHarmony do not support this attribute.| Boolean | Yes (initial value: **false**)| -| ark | Maple configuration. See Table 7. | Object | Yes (initial value: left empty) | -| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code. See Table 9.| Object | Yes (initial value: left empty) | +| ark | Maple configuration. For details, see Table 7. | Object | Yes (initial value: left empty) | +| network | Network security configuration. You can customize the network security settings of the application in the security statement of the configuration file without modifying the application code. For details, see Table 9.| Object | Yes (initial value: left empty) | Table 7 Internal structure of the ark attribute @@ -179,32 +183,32 @@ Table 10 Internal structure of the securityConfig attribute | Attribute | Sub-attribute | Description | Data Type| Initial Value Allowed | | -------------- | ------------------ | ------------------------------------------------------------ | -------- | ---------------- | -| domainSettings | - | Security settings of the custom network domain. This attribute allows nested domains. To be more specific, the **domainSettings** object of a large domain can be nested with the **domainSettings** objects of small network domains.| Object| Yes (initial value: left empty)| -| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute.
**true**: Plaintext traffic can be transmitted.
**false**: Plaintext traffic cannot be transmitted.| Boolean| No | -| | domains | Domain name configuration. This attribute consists of the **subdomains** and **name** sub-attributes.
**subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches.
**name** (string): indicates the domain name.| Object array| No | +| domainSettings | - | Security settings of the custom network domain. This attribute allows nested domains. That is, the **domainSettings** object of a network domain can be nested with the **domainSettings** objects of smaller network domains.| Object| Yes (initial value: left empty)| +| | cleartextPermitted | Whether plaintext traffic can be transmitted in the custom network domain. If both **cleartextTraffic** and **security** are declared, whether plaintext traffic can be transmitted in the custom network domain is determined by the **cleartextPermitted** attribute.
**true**: Plaintext traffic can be transmitted.
**false**: Plaintext traffic cannot be transmitted.| Boolean| No | +| | domains | Domain name. This attribute consists of two sub-attributes: **subdomains** and **name**.
**subdomains** (boolean): specifies whether the domain name contains subdomains. If this sub-attribute is set to **true**, the domain naming convention applies to all related domains and subdomains (including the lower-level domains of the subdomains). Otherwise, the convention applies only to exact matches.
**name** (string): indicates the domain name.| Object array| No | Example of the deviceConfig tag structure: ```json "deviceConfig": { - "default": { - "process": "com.example.test.example", - "supportBackup": false, - "network": { - "cleartextTraffic": true, - "securityConfig": { - "domainSettings": { - "cleartextPermitted": true, - "domains": [ - { - "subdomains": true, - "name": "example.ohos.com" - } - ] - } - } - } - } + "default": { + "process": "com.example.test.example", + "supportBackup": false, + "network": { + "cleartextTraffic": true, + "securityConfig": { + "domainSettings": { + "cleartextPermitted": true, + "domains": [ + { + "subdomains": true, + "name": "example.ohos.com" + } + ] + } + } + } + } } ``` @@ -214,76 +218,78 @@ The **module** tag contains the configuration information of the HAP file. For d Table 11 Internal structure of the module tag -| Attribute | Description | Data Type | Initial Value Allowed | -| --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | -| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| String | No if any ability using the Page template exists | -| package | Structure name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | -| name | Class name of the HAP file. The value is in the reverse domain name notation. The prefix must be the same as the package name specified by the **package** label at the same level. The value can also start with a period (.). The value is a string with a maximum of 255 bytes.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | -| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | -| supportedModes | Mode supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty) | -| deviceType | Type of device on which the abilities can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No | -| distro | Distribution description of the current HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 12.| Object | No | -| metaData | Metadata of the HAP file. For details, see Table 13. | Object | Yes (initial value: left empty) | -| abilities | All abilities in the current module. The value is an array of objects, each of which represents a shortcut object. For details, see Table 17.| Object array | Yes (initial value: left empty) | -| js | A set of JS modules developed using the ArkUI framework. Each element in the set represents the information about a JS module. For details, see Table 22.| Object array | Yes (initial value: left empty) | -| shortcuts | Shortcut information of the application. The value is an array of objects, each of which represents a shortcut object. For details, see Table 25.| Object array | Yes (initial value: left empty) | -| reqPermissions | Permissions that the application applies for from the system before its running. For details, see Table 21. | Object array | Yes (initial value: left empty) | -| colorMode | Color mode of the application.
**dark**: Resources applicable for the dark mode are selected.
**light**: Resources applicable for the light mode are selected.
**auto**: Resources are selected based on the color mode of the system.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **auto**) | -| distroFilter | Application distribution rules.
AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29. | Object | Yes (initial value: left empty)
Set this attribute when an application has multiple entry modules. | -| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | -| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | -| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | +| Attribute | Description | Data Type | Initial Value Allowed | +| ----------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | +| mainAbility | Ability displayed on the Service Center icon. When the resident process is started, the **mainAbility** is started.| String | No if any ability using the Page template exists | +| package | Package name of the HAP file, which must be unique in the application. The value is a string with a maximum of 127 bytes, in the reverse domain name notation. It is recommended that the value be the same as the project directory of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | No | +| name | Class name of the HAP file. The value is in the reverse domain name notation, with the prefix same as the package name specified by **package** at the same level. It can also start with a period (.). The value is a string with a maximum of 255 bytes.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | No | +| description | Description of the HAP file. The value is a string with a maximum of 255 bytes. If the value exceeds the limit or needs to support multiple languages, you can use a resource index to the description. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | +| supportedModes | Mode supported by the application. Currently, only the **drive** mode is defined. This attribute applies only to head units.| String array| Yes (initial value: left empty) | +| deviceType | Type of device on which the ability can run. The device types predefined in the system include **tablet**, **tv**, **car**, and **wearable**.| String array| No | +| distro | Distribution description of the HAP file. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 12.| Object | No | +| metaData | Metadata of the HAP file. For details, see Table 13. | Object | Yes (initial value: left empty) | +| abilities | All abilities in the current module. The value is an array of objects, each of which represents a shortcut object. For details, see Table 17.| Object array | Yes (initial value: left empty) | +| js | A set of JS modules developed using ArkUI. Each element in the set represents the information about a JS module. For details, see Table 22.| Object array | Yes (initial value: left empty) | +| shortcuts | Shortcuts of the application. The value is an array of objects, each of which represents a shortcut object. For details, see Table 25.| Object array | Yes (initial value: left empty) | +| reqPermissions | Permissions that the application requests from the system when it is running. For details, see Table 21. | Object array | Yes (initial value: left empty) | +| colorMode | Color mode of the application. Available values are as follows:
**"dark"**: Resources applicable for the dark mode are selected.
**"light"**: Resources applicable for the light mode are selected.
**"auto"**: Resources are selected based on the color mode of the system.
This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **auto**) | +| distroFilter | Distribution rules of the application.
AppGallery uses these rules to distribute HAP files to the matching devices. Distribution rules cover three factors: API version, screen shape, and screen resolution. AppGallery distributes a HAP file to the device whose on the mapping between **deviceType** and these three factors. For details, see Table 29.| Object | Yes (initial value: left empty) Set this attribute when an application has multiple entry modules.| +| reqCapabilities | Device capabilities required for running the application. | String array| Yes (initial value: left empty) | +| commonEvents | Static broadcast. For details, see Table 35. | Object array | Yes (initial value: left empty) | +| entryTheme | Keyword of an OpenHarmony internal theme. Set it to the resource index of the name.| String | Yes (initial value: left empty) | +| testRunner | Test runner configuration. For details, see Table 36. | Object | Yes (initial value: left empty) | +| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The caller of the application must have these permissions to properly call the app. For details, see Table 37.| Object | Yes (initial value: left empty) | Example of the **module** tag structure: ```json "module": { - "mainAbility": "MainAbility", - "package": "com.example.myapplication.entry", - "name": ".MyOHOSAbilityPackage", - "description": "$string:description_application", - "supportModes": [ - "drive" - ], - "deviceType": [ - "car" - ], - "distro": { - "moduleName": "ohos_entry", - "moduleType": "entry" - }, - "abilities": [ - ... - ], - "shortcuts": [ - ... - ], - "js": [ - ... - ], - "reqPermissions": [ - ... - ], - "colorMode": "light" + "mainAbility": "MainAbility", + "package": "com.example.myapplication.entry", + "name": ".MyOHOSAbilityPackage", + "description": "$string:description_application", + "supportModes": [ + "drive" + ], + "deviceType": [ + "car" + ], + "distro": { + "moduleName": "ohos_entry", + "moduleType": "entry" + }, + "abilities": [ + ... + ], + "shortcuts": [ + ... + ], + "js": [ + ... + ], + "reqPermissions": [ + ... + ], + "colorMode": "light" } ``` Table 12 Internal structure of the distro attribute -| Attribute | Description | Data Type| Initial Value Allowed| -| ---------------- |------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -------- | ---------- | -| moduleName | Name of the current HAP file. The maximum length is 31 characters. | String | No | -| moduleType | Type of the current HAP file. The value can be **entry** or **feature**. For the HAR type, set this attribute to **har**. | String | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.
Pay attention to the following:
When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap **must be **true**.
When **entry.hap** is set to **false**, **feature.hap** related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | -| deliveryWithInstall | Whether the HAP file supports the installation with application.
**true**: The HAP file supports the installation with application.
**false**: The HAP file does not support the installation with application. | Boolean | No | +| Attribute | Description | Data Type| Initial Value Allowed| +| ---------------- | ------------------------------------------------------------ | -------- | ---------- | +| moduleName | Name of the HAP file. The maximum length is 31 characters. | String | No | +| moduleType | Type of the HAP file. The value can be **entry** or **feature**. For the HAR type, set this attribute to **har**.| String | No | +| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.
Pay attention to the following:
- When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap **must be **true**.
- When **entry.hap** is set to **false**, **feature.hap** related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | +| deliveryWithInstall | Whether the HAP file is installed with application.
**true**: The HAP file is installed together with the application.
**false**: The HAP file is not installed together with the application.| Boolean| No| Example of the **distro** attribute structure: ```json "distro": { - "moduleName": "ohos_entry", - "moduleType": "entry", - "installationFree": true, + "moduleName": "ohos_entry", + "moduleType": "entry", + "installationFree": true, "deliveryWithInstall": true } ``` @@ -300,9 +306,9 @@ Table 14 Internal structure of the parameters attribute | Attribute | Description | Data Type| Initial Value Allowed | | ----------- | ------------------------------------------------------------ | -------- | ------------------ | -| description | Description of the parameter. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| -| name | Name of the parameter. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the parameter, for example, **Integer**. | String | No | +| description | Description of the parameter passed for calling the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| +| name | Name of the parameter passed for calling the ability. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| +| type | Type of the parameter passed for calling the ability, for example, **Integer**. | String | No | Table 15 Internal structure of the results attribute @@ -310,15 +316,15 @@ Table 15 Internal structure of the results attribute | ----------- | ------------------------------------------------------------ | -------- | -------------------- | | description | Description of the return value. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty)| | name | Name of the return value. The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty)| -| type | Type of the return value, for example, **Integer**. | String | No | +| type | Type of the return value, for example, **Integer**. | String | No | Table 16 Internal structure of the customizeData attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ---------------------------------------------------------- | -------- | -------------------- | -| name | Key of a data element. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of a data element. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Custom format of the data element. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty)| +| name | Key of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| extra | Custom format of the data item. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty)| Example of the **metaData** attribute structure: @@ -347,19 +353,19 @@ Table 17 Internal structure of the abilities attribute | Attribute | Description | Data Type | Initial Value Allowed | | ---------------- | ------------------------------------------------------------ | ---------- | -------------------------------------------------------- | | process | Name of the process running the application or ability. If the **process** attribute is configured in the **deviceConfig** tag, all abilities of the application run in this process. You can set the **process** attribute for a specific ability in the **abilities** attribute, so that the ability can run in the particular process. If this attribute is set to the name of the process running other applications, all these applications can run in the same process, provided they have the same unified user ID and the same signature. Devices running OpenHarmony do not support this attribute.| String | Yes (initial value: left empty) | -| name | Name of the ability. The value is a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDE tools. The value can contain a maximum of 127 characters.| String | No | +| name | Ability name. The value can be a reverse domain name, in the format of "*Bundle name*.*Class name*", for example, **"com.example.myapplication.MainAbility"**. Alternatively, the value can start with a period (.) followed by the class name, for example, **".MainAbility"**.
The ability name must be unique in an application. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.
Note: If you use DevEco Studio to create the project, an ability named **MainAbility** will be created together with the default configuration in the **config.json** file. The value of this attribute can be customized if you use other IDEs. The value can contain a maximum of 127 characters. | String | No | | description | Description of the ability. The value can be a string or a resource index to descriptions in multiple languages. The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | -| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels.| String | Yes (initial value: left empty) | -| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters.| String | Yes (initial value: left empty) | +| icon | Index to the ability icon file. Example value: **$media:ability_icon**. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the icon of the ability is also used as the icon of the application. If multiple abilities address this condition, the icon of the first candidate ability is used as the application icon.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. | String | Yes (initial value: left empty) | +| label | Ability name visible to users. The value can be a name string or a resource index to names in multiple languages. In the **skills** attribute of the ability, if the **actions** value contains **action.system.home** and the **entities** value contains **entity.system.home**, the label of the ability is also used as the label of the application. If multiple abilities address this condition, the label of the first candidate ability is used as the application label.
Note: The **icon** and **label** values of an application are visible to users. Ensure that at least one of them is different from any existing icons or labels. The value can be a reference to a string defined in a resource file or a string enclosed in brackets ({}). The value can contain a maximum of 255 characters. | String | Yes (initial value: left empty) | | uri | Uniform Resource Identifier (URI) of the ability. The value can contain a maximum of 255 characters. | String | Yes (No for abilities using the Data template) | -| launchType | Startup type of the ability. The value can be **standard** or **singleton**.
**standard**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**singleton**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton startup type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: **"singleton"**) | +| launchType | Launch type of the ability. Available values are as follows:
**"standard"**: Multiple **Ability** instances can be created during startup. Most abilities can use this type.
**"singleton"**: Only a single **Ability** instance can be created across all task stacks during startup. For example, a globally unique incoming call screen uses the singleton startup type. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. | String | Yes (initial value: **"singleton"**) | | visible | Whether the ability can be called by other applications.
**true**: The ability can be called by other applications.
**false**: The ability cannot be called by other applications.| Boolean | Yes (initial value: **false**) | -| permissions | Permissions required for abilities of another application to call the current ability, generally in the format of a reverse domain name. The value can be either the permissions predefined in the OS or your custom permissions.| String array| Yes (initial value: left empty) | +| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | | skills | Types of the **want** that can be accepted by the ability. | Object array | Yes (initial value: left empty) | | deviceCapability | Device capabilities required to run the ability.| String array| Yes (initial value: left empty) | | metaData | Metadata. For details, see Table 13. | Object | Yes (initial value: left empty) | -| type | Type of the ability. Available values are as follows:
**page**: FA developed using the Page template to provide the capability of interacting with users.
**service**: PA developed using the Service template to provide the capability of running tasks in the background.
**data**: PA developed using the Data template to provide unified data access for external systems.
**CA**: ability that can be started by other applications as a window.| String | No | -| orientation | Display orientation of the ability. This attribute applies only to the ability using the Page template. Available values are as follows:
unspecified: indicates that the system automatically determines the display orientation of the ability.
**landscape**: indicates the landscape orientation.
**portrait**: indicates the portrait orientation.
**followRecent**: indicates that the orientation follows the most recent application in the stack.| String | Yes (initial value: **"unspecified"**) | +| type | Ability type. Available values are as follows:
**"page"**: FA developed using the Page template to provide the capability of interacting with users.
**"service"**: PA developed using the Service template to provide the capability of running tasks in the background.
**"data"**: PA developed using the Data template to provide unified data access for external systems.
**"CA"**: ability that can be started by other applications as a window. | String | No | +| orientation | Display orientation of the ability. This attribute applies only to the ability using the Page template. Available values are as follows:
**"unspecified"**: indicates that the system automatically determines the display orientation of the ability.
**"landscape"**: indicates the landscape orientation.
**"portrait"**: indicates the portrait orientation.
**"followRecent"**: indicates that the orientation follows the most recent application in the stack. | String | Yes (initial value: **"unspecified"**) | | backgroundModes | Background service type of the ability. You can assign multiple background service types to a specific ability. This attribute applies only to the ability using the Service template. Available values are as follows:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**pictureInPicture**: picture in picture (PiP) and small-window video playback services
**voip**: voice/video call and VoIP services
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services
**wifiInteraction**: WLAN scanning, connection, and transmission services
**screenFetch**: screen recording and screenshot services
**multiDeviceConnection**: multi-device interconnection service| String array| Yes (initial value: left empty) | | grantPermission | Whether permissions can be granted for any data in the ability. | Boolean | Yes (initial value: left empty) | | readPermission | Permission required for reading data in the ability. This attribute applies only to the ability using the Data template. The value is a string with a maximum of 255 bytes. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty) | @@ -367,15 +373,16 @@ Table 17 Internal structure of the abilities attribute | configChanges | System configurations that the ability concerns. Upon any changes on the concerned configurations, the **onConfigurationUpdated** callback will be invoked to notify the ability. Available values are as follows:
**mcc**: indicates that the mobile country code (MCC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MCC is updated.
**mnc**: indicates that the mobile network code (MNC) of the IMSI is changed. Typical scenario: A SIM card is detected, and the MNC is updated.
**locale**: indicates that the locale is changed. Typical scenario: The user has selected a new language for the text display of the device.
**layout**: indicates that the screen layout is changed. Typical scenario: Currently, different display forms are all in the active state.
**fontSize**: indicates that font size is changed. Typical scenario: A new global font size is set.
**orientation**: indicates that the screen orientation is changed. Typical scenario: The user rotates the device.
**density**: indicates that the display density is changed. Typical scenario: The user may specify different display ratios, or different display forms are active at the same time.
**size**: indicates that the size of the display window is changed.
**smallestSize**: indicates that the length of the shorter side of the display window is changed.
**colorMode**: indicates that the color mode is changed.| String array| Yes (initial value: left empty) | | mission | Task stack of the ability. This attribute applies only to the ability using the Page template. By default, all abilities in an application belong to the same task stack. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: bundle name of the application) | | targetAbility | Target ability that this ability alias points to. This attribute applies only to the ability using the Page template. If the **targetAbility** attribute is set, only **name**, **icon**, **label**, **visible**, **permissions**, and **skills** take effect in the current ability (ability alias). Other attributes use the values of the **targetAbility** attribute. The target ability must belong to the same application as the alias and must be declared in **config.json** ahead of the alias. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| String | Yes (initial value: left empty, indicating that the current ability is not an alias)| -| multiUserShared | Whether the ability supports data sharing among multiple users. This attribute applies only to the ability using the Data template. If this attribute is set to **true**, only one copy of data is stored for multiple users. Note that this attribute will invalidate the **visible** attribute. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**) | -| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean | Yes (initial value: **false**) | -| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean | Yes (initial value: **false**) | -| forms | Details about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | -| srcLanguage | Programming language used to develop the ability. | String | The value can be **js**, or **ets**. | -| srcPath | Path of the JS code and components corresponding to the ability. | String | Yes (initial value: left empty) | +| multiUserShared | Whether the ability supports data sharing among multiple users. This attribute applies only to the ability using the Data template. If this attribute is set to **true**, only one copy of data is stored for multiple users. Note that this attribute will invalidate the **visible** attribute. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | +| supportPipMode | Whether the ability allows the user to enter the Picture in Picture (PiP) mode. The PiP mode enables the user to watch a video in a small window that hovers on top of a full screen window (main window). This attribute applies only to the ability using the Page template. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types.| Boolean| Yes (initial value: **false**) | +| formsEnabled | Whether the ability can provide forms. This attribute applies only to the ability using the Page template.
**true**: This ability can provide forms.
**false**: This ability cannot provide forms.| Boolean| Yes (initial value: **false**) | +| forms | Information about the forms used by the ability. This attribute is valid only when **formsEnabled** is set to **true**. For details, see Table 27.| Object array | Yes (initial value: left empty) | +| srcLanguage | Programming language used to develop the ability. The value can be **"js"** or **"ets"**. | String | Yes | +| srcPath | Path of the JS component code corresponding to the ability. | String | Yes (initial value: left empty) | | uriPermission | Application data that the ability can access. This attribute consists of the **mode** and **path** sub-attributes. This attribute is valid only for the capability of the type provider. Devices running OpenHarmony do not support this attribute. For details, see Table 18.| Object | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | Yes (initial value: left empty) | -| startWindowBackground | Index to the background color resource file of the ability startup page. Example value: **$color:red**. | String | Yes (initial value: left empty) | +| startWindowIcon | Index to the icon file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$media:icon**.| String | Yes (initial value: left empty)| +| startWindowBackground | Index to the background color resource file of the ability startup page. This attribute applies only to the ability using the Page template. Example: **$color:red**.| String | Yes (initial value: left empty)| +| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. This attribute applies only to the ability using the Page template. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| Table 18 Internal structure of the uriPermission attribute @@ -395,8 +402,7 @@ Example of the **abilities** attribute structure: "label": "$media:example", "launchType": "standard", "orientation": "unspecified", - "permissions": [ - ], + "permissions": [], "visible": true, "skills": [ { @@ -416,7 +422,8 @@ Example of the **abilities** attribute structure: ], "type": "page", "startWindowIcon": "$media:icon", - "startWindowBackground": "$color:red" + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true }, { "name": ".PlayService", @@ -456,20 +463,20 @@ Table 19 Internal structure of the skills attribute | Attribute| Description | Data Type | Initial Value Allowed | | -------- | ------------------------------------------------------------ | ---------- | -------------------- | | actions | Actions of the **want** that can be accepted by the ability. Generally, the value is an **action** value predefined in the system.| String array| Yes (initial value: left empty)| -| entities | Entities of the **want** that can be accepted by the ability, such as video and Home application.| String array| Yes (initial value: left empty)| +| entities | Entities of the **want** that can be accepted by the ability, such as video and home applications.| String array| Yes (initial value: left empty)| | uris | URIs of the **want** that can be accepted by the ability. For details, see Table 20.| Object array | Yes (initial value: left empty)| Table 20 Internal structure of the uris attribute | Attribute | Description | Data Type| Initial Value Allowed | | ------------- | -------------------------- | -------- | -------------------- | -| scheme | Scheme in the URI. | String | No | -| host | Host in the URI. | String | Yes (initial value: left empty)| -| port | Port number in the URI. | String | Yes (initial value: left empty)| -| pathStartWith | **pathStartWith** value in the URI.| String | String | -| path | Path in the URI. | String | Yes (initial value: left empty)| -| pathRegx | **pathRegx** value in the URI. | String | Yes (initial value: left empty)| -| type | Type of the URI. | String | Yes (initial value: left empty)| +| scheme | Scheme of the URI. | String | No | +| host | Host value of the URI. | String | Yes (initial value: left empty)| +| port | Port number of the URI. | String | Yes (initial value: left empty)| +| pathStartWith | **pathStartWith** value of the URI.| String | Yes (initial value: left empty)| +| path | **path** value of the URI. | String | Yes (initial value: left empty)| +| pathRegx | **pathRegx** value of the URI. | String | Yes (initial value: left empty)| +| type | **type** value of the URI. | String | Yes (initial value: left empty)| Example of the **skills** attribute structure: @@ -484,48 +491,49 @@ Example of the **skills** attribute structure: ], "uris": [ { - "scheme": "http", - "host": "www.example.com", - "port": "8080", - "path": "query/student/name", - "type": "text/*" - } - ] + "scheme": "http", + "host": "www.example.com", + "port": "8080", + "path": "query/student/name", + "type": "text/*" + } + ] } ] ``` Table 21 reqPermissions -| Attribute | Description | **Type**| **Value Range** | **Default Value** | **Restrictions** | -| --------- | ------------------------------------------------------------ | -------- | ----------------------------------------------------------- | ---------------------- | ------------------------------------------------------------ | -| name | Permission name, which is mandatory. | String | Custom | None | Parsing will fail if this field is not set. | -| reason | Reason for applying for the permission, which is mandatory only when applying for the **user_grant** permission.| String | The displayed text cannot exceed 256 bytes. | Empty | If the requested permission is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required.| -| usedScene | Application scenario and timing for using the permission, which is mandatory when the requested permission is **user_grant**. This attribute consists of the **ability** and **when** sub-attributes. Multiple abilities can be configured.| Object | **ability**: ability name; **when**: **inuse** or **always**| **ability**: left empty; **when**: **inuse**| If the requested permission is **user_grant**, the **ability** sub-attribute is mandatory and **when** is optional. | +| Attribute | Description | Data Type| Initial Value Allowed | +| ---------- | ------------------------------------------------------------ | -------- | ------------------ | +| name | Name of the permission to request.| String| No| +| reason | Reason for requesting the permission. The value cannot exceed 256 bytes. Multi-language adaptation is required.| String| No if the requested permission is **user_grant** (if it is left empty, application release will be rejected)| +| usedScene | Application scenario and timing for using the permission. This attribute consists of the **ability** and **when** sub-attributes. **ability**: ability name. Multiple ability names can be configured. **when**: time for using the permission. The options are **inuse** and **always**.| Object| **ability**: mandatory for the **user_grant** permission and can be left empty in other cases
**when**: initial value allowed (initial value: **inuse**)| +For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). Table 22 Internal structure of the js attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | ------------------------ | -| name | Name of a JavaScript component. The default value is **default**. | String | No | -| pages | Route information about all pages in the JavaScript component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | +| name | Name of the JS component. The default value is **default**. | String | No | +| pages | Route information about all pages in the JS component, including the page path and page name. The value is an array, in which each element represents a page. The first element in the array represents the home page of the JavaScript FA.| Array | No | | window | Window-related configurations. This attribute applies only to the default, tablet, smart TV, head unit, and wearable device types. For details, see Table 23.| Object | Yes | -| type | Type of the JavaScript component. Available values are as follows:
**normal**: indicates that the JavaScript component is an application instance.
**form**: indicates that the JavaScript component is a widget instance.| String | Yes (initial value: **normal**)| -| mode | Development mode of the JavaScript component. For details, see Table 24. | Object | Yes (initial value: left empty) | +| type | Type of the JS component. Available values are as follows:
**"normal"**: indicates that the JavaScript component is an application instance.
**"form"**: indicates that the JavaScript component is a widget instance. | String | Yes (initial value: **"normal"**) | +| mode | Development mode of the JS component. For details, see Table 24. | Object | Yes (initial value: left empty) | Table 23 Internal structure of the window attribute | Attribute | Description | Data Type| Initial Value Allowed | | --------------- | ------------------------------------------------------------ | -------- | ----------------------- | -| designWidth | Baseline width for page design, in pixels. The size of an element is scaled by the actual device width.| Number | Yes (initial value: 720px) | -| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean| Yes (initial value: **false**)| +| designWidth | Baseline width for page design. The size of an element is scaled by the actual device width.| Number | Yes (initial value: 720px) | +| autoDesignWidth | Whether to automatically calculate the baseline width for page design. If it is set to **true**, the **designWidth** attribute becomes invalid. The baseline width is calculated based on the device width and screen density.| Boolean | Yes (initial value: **false**)| Table 24 Internal structure of the mode attribute | Attribute| Description | Data Type | Initial Value Allowed | | -------- | -------------------- | ----------------------------------- | --------------------------- | -| type | Type of the JavaScript component.| String. The value can be **pageAbility** or **form**.| Yes (initial value: **pageAbility**)| -| syntax | Syntax type of the JavaScript component.| String. The value can be **hml** or **ets**. | Yes (initial value: **hml**) | +| type | Type of the JS component. The value can be **"pageAbility"** or **"form"**. | String | Yes (initial value: **"pageAbility"**) | +| syntax | Syntax type of the JS component. The value can be **"hml"** or **"ets"**. | String | Yes (initial value: **"hml"**) | Example of the **js** attribute structure: @@ -550,8 +558,8 @@ Table 25 Internal structure of the shortcuts attribute | Attribute | Description | Data Type| Initial Value Allowed | | ---------- | ------------------------------------------------------------ | -------- | ------------------ | -| shortcutId | Shortcut ID. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed by the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty)| +| shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty)| | icon | Icon of the shortcut. The value is a resource index to the description. | String | Yes (initial value: left empty)| | intents | Intents to which the shortcut points. The attribute consists of the **targetClass** and **targetBundle** sub-attributes. For details, see Table 26.| Object array| Yes (initial value: left empty)| @@ -559,7 +567,7 @@ Table 26 Internal structure of the intents attribute | Attribute | Description | Data Type| Initial Value Allowed | | ------------ | --------------------------------------- | -------- | -------------------- | -| targetClass | Class name for the target ability of the shortcut. | String | Yes (initial value: left empty)| +| targetClass | Target class of the shortcut. | String | Yes (initial value: left empty)| | targetBundle | Application bundle name for the target ability of the shortcut.| String | Yes (initial value: left empty)| Example of the **shortcuts** attribute structure: @@ -583,29 +591,29 @@ Table 27 Internal structure of the forms attribute | Attribute | Description | Data Type | Initial Value Allowed | | ------------------- | ------------------------------------------------------------ | ---------- | ------------------------ | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | +| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | | description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | -| type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget.| String | No | +| isDefault | Whether the widget is a default one. Each ability has only one default widget.
**true**: The widget is the default one.
**false**: The widget is not the default one.| Boolean | No | +| type | Type of the widget. Available values are as follows:
**JS**: indicates a JavaScript-programmed widget. | String | No | | colorMode | Color mode of the widget. Available values are as follows:
**auto**: The widget adopts the auto-adaptive color mode.
**dark**: The widget adopts the dark color mode.
**light**: The widget adopts the light color mode.| String | Yes (initial value: **auto**)| -| supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | -| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | -| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | +| supportDimensions | Grid styles supported by the widget. Available values are as follows:
1 * 2: indicates a grid with one row and two columns.
2 * 1: indicates a grid with two rows and one column.
2 * 2: indicates a grid with two rows and two columns.
2 * 4: indicates a grid with two rows and four columns.
4 * 4: indicates a grid with four rows and four columns.| String array| No | +| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String | No | +| updateEnabled | Whether the widget can be updated periodically. Available values are as follows:
**true**: The widget can be updated periodically, depending on the update way you select, either at a specified interval (**updateDuration**) or at the scheduled time (**scheduledUpdateTime**). **updateDuration** is preferentially recommended.
**false**: The widget cannot be updated periodically.| Boolean | No | | scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes (initial value: **0:0**) | | updateDuration | Interval to update the widget. The value is a natural number, in the unit of 30 minutes.
If the value is **0**, this field does not take effect.
If the value is a positive integer ***N***, the interval is calculated by multiplying ***N*** and 30 minutes.| Number | Yes (initial value: **0**) | -| formConfigAbility | Link to a specific page of the application. The value is a URI. | String | Yes (initial value: left empty) | +| formConfigAbility | Name of the facility or activity used to adjust the ability. | String | Yes (initial value: left empty) | | formVisibleNotify | Whether the widget is allowed to use the widget visibility notification. | String | Yes (initial value: left empty) | -| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String | No | -| metaData | Metadata of the widget. This attribute contains the array of the **customizeData** attribute. For details, see Table 13. | Object | Yes (initial value: left empty) | -| customizeData | Custom information about the widget. For details, see Table 28. | Object array | Yes (initial value: left empty) | +| jsComponentName | Component name of the widget. The value is a string with a maximum of 127 bytes. This attribute is required only by JavaScript-programmed widgets.| String | No | +| metaData | Metadata of the widget. The value contains value of the **customizeData** attribute. For details, see Table 13. | Object | Yes (initial value: left empty) | +| customizeData | Custom information of the widget. For details, see Table 28. | Object array | Yes (initial value: left empty) | Table 28 Internal structure of the customizeData attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | --------------------------------------------------- | -------- | -------------------- | -| name | Name in the custom name-value pair. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value in the custom name-value pair. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| extra | Format of the current custom data. The value is the resource value of **extra**.| String | Yes (initial value: left empty)| +| name | Key name that identifies a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| extra | Current format of the custom data. The value indicates the resource.| String | Yes (initial value: left empty)| Example of the **forms** attribute structure: @@ -629,9 +637,9 @@ Example of the **forms** attribute structure: ] }, { - "name": "Form_JS", + "name": "Form_Js", "description": "It's JS Form", - "type": "JS", + "type": "Js", "colorMode": "auto", "isDefault": false, "updateEnabled": true, @@ -662,13 +670,13 @@ Example of the **forms** attribute structure: Table 29 Internal structure of the distroFilter attribute -| Attribute | Description | Data Type| Initial Value Allowed| -| ------------- | ------------------------------------------------------------ | -------- | ---------- | -| apiVersion | Supported API versions. For details, see Table 30. | Object | No | -| screenShape | Supported screen shapes. For details, see Table 31. | Object array| No | -| screenWindow | Supported window resolutions when the application is running. This attribute applies only to the lite wearables. For details, see Table 32.| Object array| No | -| screenDensity | Pixel density of the screen, in dots per inch (DPI). For details, see Table 33. | Object array| No | -| countryCode | Country code used during application distribution. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported. For details, see Table 34.| Object array| No | +| Attribute | Description | Data Type| Initial Value Allowed | +| ------------- | ------------------------------------------------------------ | -------- | -------------------- | +| apiVersion | Supported API versions. For details, see Table 30. | Object | Yes (initial value: left empty)| +| screenShape | Supported screen shapes. For details, see Table 31. | Object array| Yes (initial value: left empty)| +| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables. For details, see Table 32.| Object array| Yes (initial value: left empty)| +| screenDensity | Pixel density of the screen, in dots per inch (dpi). For details, see Table 33. | Object array| Yes (initial value: left empty)| +| countryCode | Country code used for distributing the application. For details, see the ISO-3166-1 standard. Multiple enumerated values of countries and regions are supported. For details, see Table 34.| Object array| Yes (initial value: left empty)| Table 30 Internal structure of the apiVersion attribute @@ -727,7 +735,7 @@ Example of the **distroFilter** attribute structure: }, "countryCode": { "policy":"include", - "value":["CN", "HK"] + "value":["CN","HK"] } } ``` @@ -738,7 +746,7 @@ Table 35 Internal structure of the commonEvents attribute | ---------- | ------------------------------------------------------------ | ---------- | ------------------ | | name | Name of a static broadcast. | String | No | | permission | Permission needed to implement the static common event. | String array| Yes (initial value: left empty)| -| data | Additional data array to be carried by the current static common event. | String array| Yes (initial value: left empty)| +| data | Additional data array to be carried by the current static common event. | String array| Yes (initial value: left empty)| | type | Type array of the current static common event. | String array| Yes (initial value: left empty)| | events | A set of events for the wants that can be received. The value can be system predefined or custom.| String array| No | @@ -746,17 +754,44 @@ Example of the **commonEvents** attribute structure: ```json "commonEvents": [ - { - "name":"MainAbility", - "permission": "string", - "data":[ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - } + { + "name":"MainAbility", + "permission": "string", + "data":[ + "string", + "string" + ], + "events": [ + "string", + "string" + ] + } ] ``` + +Table 36 Internal structure of the testRunner attribute + +| Attribute| Description | Data Type| Initial Value Allowed| +| -------- | -------------------- | -------- | ---------- | +| name | Name of the test runner object.| String | No | +| srcPath | Path of the test runner code.| String | No | + +```json +"testRunner": { + "name": "myTestRUnnerName", + "srcPath": "etc/test/TestRunner.ts" +} +``` + +Table 37 Internal structure of the definePermissions attribute +**definePermission** applies only to system applications and does not take effect for third-party applications. + +| Attribute | Description | Data Type| Initial Value Allowed| +| ----------------------- | ------------------------------------------------------------ | -------- | ---------- | +| name | Permission name. | String | No | +| grantMode | Permission grant mode.
Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user. | String | Yes (initial value: **"system_grant"**) | +| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | +| provisionEnable | Whether the permission can be requested in provision mode. | Boolean | Yes (initial value: **true**) | +| distributedSceneEnabled | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | +| label | Brief description of the permission. The value is a resource index. | String | Yes | +| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes | diff --git a/en/application-dev/quick-start/stage-structure.md b/en/application-dev/quick-start/stage-structure.md index bd1eb5a1a3f52c392a645b8958e02e2f59e39e29..03845296847a43338cca31673b76e46b8c496bbf 100644 --- a/en/application-dev/quick-start/stage-structure.md +++ b/en/application-dev/quick-start/stage-structure.md @@ -2,20 +2,22 @@ # Application Package Structure Configuration File -When developing an application in the FA model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json** file. +When developing an application in the Feature Ability (FA) model, you need to declare the package structure of the application in the **config.json** file. Similarly, when developing an application in the stage model, you need to declare the package structure of the application in the **module.json5** and **app.json** files. -## Internal Structure of the module.json File +## Configuration File Internal Structure -The **module.json** file consists of two tags: **app** and **module**. See Table 1 for details. +The configuration files each consist of two mandatory tags, namely, **app** and **module**. For details, see Table 1. -Table 1 Internal structure of the module.json file +Table 1 Configuration file internal structure | Tag| Description | Data Type| Initial Value Allowed| | -------- | ------------------------------------------------------------ | -------- | ---------- | -| app | Global configuration of an application. Different HAP files of an application must use the same **app** configuration. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | -| module | Configuration of a HAP file. The **module** configuration is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | +| app | Global configuration of the application. For details, see [Internal Structure of the app Tag](#internal-structure-of-the-app-tag).| Object | No | +| module | Configuration of the HAP file. It is valid only for the current HAP file. For details, see [Internal Structure of the module Tag](#internal-structure-of-the-module-tag).| Object | No | -Example of the **module.json** file: +### Internal Structure of the app Tag + +Code snippet in the **app.json** file: ```json { @@ -25,8 +27,8 @@ Example of the **module.json** file: "versionCode": 1, "versionName": "1.0", "minCompatibleVersionCode": 1, - "apiCompatibleVersion": 7, - "apiTargetVersion": 8, + "minAPIVersion": 7, + "targetAPIVersion": 8, "apiReleaseType": "Release", "debug": false, "icon": "$media:app_icon", @@ -37,20 +39,56 @@ Example of the **module.json** file: "car": { "apiCompatibleVersion": 8 } - }, + } +} +``` + +This tag is an application-level attribute that applies to all the HAP files and components in the application. For the internal structure of the tag, see Table 2. + +Table 2 Internal structure of the app tag + +| Attribute | Description | Data Type| Initial Value Allowed | +| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | +| bundleName | Bundle name that uniquely identifies the application. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*, where the first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
For an application compiled with the system source code, its bundle name must be in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony. | String | No | +| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | +| icon | Icon of the application. The value is the index to the resource file. | String | No | +| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | +| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | +| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | +| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | +| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | +| minCompatibleVersionCode | Earliest version that the application is compatible with. It is used to determine cross-device compatibility. | Number | Yes (initial value: value of **versionCode**)| +| minAPIVersion | Minimum API version required for running the application. | Integer | Yes (initial value: value of **compatibleSdkVersion** in **bundle-profile.json5**)| +| targetAPIVersion | Target API version required for running the application. | Integer | Yes (initial value: value of **compileSdkVersion** in **bundle-profile.json5**)| +| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | +| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | +| entityType | Category of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: **"unspecified"**) | +| singleton | Whether to enable singleton mode for the application. This attribute applies only to system applications and does not take effect for third-party applications. If this attribute is set to **true**, the application always runs in singleton mode, even in multi-user scenarios. This attribute is supported since API version 8. | Boolean | Yes (initial value: **false**) | +| removable | Whether the application can be uninstalled. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | +| keepAlive | Whether the application is always running. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the application is always kept alive: The system automatically launches the application at startup and restarts it after it exits.| Boolean | Yes (initial value: **false**) | +| userDataClearable | Whether user data of the application can be cleared. This attribute applies only to system applications and does not take effect for third-party applications. It is supported since API version 8.| Boolean | Yes (initial value: **true**) | +| accessible | Whether the installation directory of the application is accessible. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** means that the installation directory can be accessed by third-party applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | +| multiProjects | Whether multiple projects are supported.| Boolean| Yes (initial value: **false**)| +| deviceType | Supported device types, such as **tablet**, **tv**, **wearable**, and **car**. The following attributes may be included: **minAPIVersion**, **distributedNotificationEnabled**, **keepAlive**, and **removable**.| Object | Yes (initial value: settings under **"app"**)| + +### Internal Structure of the module Tag + +Code snippet in the **module.json5** file: + +```json +{ "module": { "name": "myHapName", "type": "entry|feature|har", "srcEntrance" : "./MyAbilityStage.js", "description" : "$string:description_application", - "process": "string", "mainElement": "MainAbility", "deviceTypes": [ "tablet", "tv", "wearable", "car", - "router", + "router" ], "deliveryWithInstall": true, "installationFree": false, @@ -67,18 +105,6 @@ Example of the **module.json** file: "resource": "$profile:config_file2" } ], - "metadata": [ - { - "name": "string", - "value": "string", - "resource": "$profile:config_file1" - }, - { - "name": "string", - "value": "string", - "resource": "$profile:config_file2" - } - ], "abilities": [ { "name": "MainAbility", @@ -109,38 +135,18 @@ Example of the **module.json** file: "voip", "taskKeeping" ], - } - ], - "abilities": [ + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red" + }, { - "name": "MainAbility", - "srcEntrance" : "./login/MyMainAbility.ts", - "description": "$string:description_main_ability", + "name": "sampleAbility", + "srcEntrance" : "./login/sampleAbility.ts", + "description": "$string:description_sample_ability", "icon": "$media:icon", "label": "HiMusic", "visible": true, - "skills": [ - { - "actions": [ - "action.system.home" - ], - "entities": [ - "entity.system.home" - ], - "uris": [ ] - } - ], - "backgroundModes": [ - "dataTransfer", - "audioPlayback", - "audioRecording", - "location", - "bluetoothInteraction", - "multiDeviceConnection", - "wifiInteraction", - "voip", - "taskKeeping" - ], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red" } ], "requestPermissions": [ @@ -159,79 +165,56 @@ Example of the **module.json** file: } ``` -### Internal Structure of the app Tag - -This tag is an application-level attribute that affects all the HAP files and components in the application. For the internal structure of the tag, see Table 2. - -Table 2 Internal structure of the app tag - -| Attribute | Description | Data Type| Initial Value Allowed | -| ------------------------------ | ------------------------------------------------------------ | -------- | ------------------------------------------- | -| bundleName | Bundle name that uniquely identifies the application. This attribute cannot be left empty. The value must comply with the following rules:
(1) Consists of letters, digits, underscores (_), and periods (.).
(2) Starts with a letter.
(3) Contains 7 to 127 bytes.
You are advised to use the reverse domain name notion, for example, *com.example.xxx*. The first part is the domain suffix **com**, the second part is the vendor/individual name, and the third part is the application name, which can be of multiple levels.
The application compiled with the system source code must be named in the format of **com.ohos.*xxx***, where **ohos** signifies OpenHarmony.| String | No | -| debug | Whether the application can be debugged. | Boolean | Yes (initial value: **false**) | -| icon | Icon of the application. The value is the index to the resource file. | String | No | -| label | Name of the application. The value is a resource index to descriptions in multiple languages.| String | No | -| description | Description of the application. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| vendor | Application vendor. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| versionCode | Version number of the application. The value is a 32-bit non-negative integer and less than 2 to the power of 31. It is used only to determine whether a version is later than another version. A larger value indicates a later version. Ensure that a new version of the application uses a value greater than any of its predecessors. | Number | No | -| versionName | Text description of the version number, which is displayed to users.
The value consists of only digits and dots. The four-segment format *A.B.C.D* is recommended, wherein:
Segment 1: major version number, which ranges from 0 to 99. A major version consists of major new features or large changes.
Segment 2: minor version number, which ranges from 0 to 99. A minor version consists of some new features and large bug fixes.
Segment 3: feature version number, which ranges from 0 to 99. A feature version consists of scheduled new features.
Segment 4: maintenance release number or patch number, which ranges from 0 to 999. A maintenance release or patch consists of resolution to security flaws or minor bugs.| String | No | -| minCompatibleVersionCode | Minimum API version compatible with the application. | Number | Yes (initial value: value of **versionCode**)| -| minAPIVersion | Minimum API version required for running the application. | Number | No | -| targetAPIVersion | Target API version required for running the application. | Integer | No | -| apiReleaseType | Type of the target API version required for running the application. The value can be **CanaryN**, **BetaN**, or **Release**, where **N** represents a positive integer.
**Canary**: indicates a restricted release.
**Beta**: indicates a publicly released beta version.
**Release**: indicates a publicly released official version.| String | Yes (initial value: **"Release"**) | -| distributedNotificationEnabled | Whether the distributed notification feature is enabled for the application. | Boolean | Yes (initial value: **true**) | -| entityType | Type of the application, which can be **game**, **media**, **communication**, **news**, **travel**, **utility**, **shopping**, **education**, **kids**, **business**, and **photography**.| String | Yes (initial value: unspecified) | - -### Internal Structure of the module Tag - This tag stores the HAP configuration, which only applies to the current HAP file. Table 3 Internal structure of the module tag -| Attribute | Description | Data Type | Initial Value Allowed | -| ------------------- | ------------------------------------------------------------ | ---------- | ------------------------------------- | -| name | Name of the current module. After the module is packed into a HAP file, this attribute indicates the name of the HAP file. The value is a string with a maximum of 31 bytes and must be unique in the entire application.| String | No | -| type | Type of the current HAP file. There are three types: **entry**, **feature**, and **har**.| String | No | -| srcEntrance | Path of the entry JS code corresponding to the HAP file. The value is a string with a maximum of 127 bytes.| String | Yes | -| description | Description of the HAP file. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| process | Process of the HAP file. The value is a string with a maximum of 31 bytes. If a process is configured under **hap**, all abilities of the application run in this process.| String | Yes (initial value: name of the HAP file) | -| mainElement | Entrance ability name or extension name of the HAP file. Only the ability or extension whose value is **mainElement** can be displayed in the Service Center. This attribute cannot be left at the initial value for an OpenHarmony atomic service.| String | Yes for an OpenHarmony application | -| deviceTypes | Types of the devices on which the HAP file can run. Table 4 lists the device types predefined by the system.
Different from **syscap**, which is based on the device capability (such as Bluetooth and Wi-Fi), **deviceTypes** is based on the device type.| String array| No (can be left empty) | -| deliveryWithInstall | Whether the current HAP file will be installed when the user installs the application. The value **true** means that the HAP file will be automatically installed when the user installs the application, and **false** means the opposite.| Boolean | No | -| installationFree | Whether the HAP file supports the installation-free feature.
**true**: The HAP file supports the installation-free feature and meets installation-free constraints.
**false**: The HAP file does not support the installation-free feature.

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

When **entry.hap** is set to **true**, all **feature.hap** fields related to **entry.hap** must be **true**.
When **entry.hap** is set to **false**, **feature.hap** fields related to **entry.hap** can be set to **true** or **false** based on service requirements. | Boolean | No | +| virtualMachine | Type of the target virtual machine (VM) where the current HAP file is running. It is used for cloud distribution, such as the application market and distribution center.
If the target VM type is Ark, the value is **ark**. Otherwise, the value is **default**. This attribute is automatically inserted when the IDE builds the HAP file. When the decompression tool parses the HAP file, if the HAP file does not contain this attribute, the value is set to **default**. | String | Yes (initial value: **default**) | +| uiSyntax(deprecated) | Syntax type of the JS component. This attribute is deprecated since API version 9.
**"hml"**: indicates that the JS component is developed using HML, CSS, or JS.
**"ets"**: indicates that the JS component is developed using the eTS declarative syntax.| String | Yes (initial value: **"hml"**) | +| pages | Profile resource used to list information about each page in the JS component. For details about how to use **pages**, see the **pages** example.| Object | No in the ability scenario | +| metadata | Custom metadata of the HAP file. The configuration is valid only for the current module, ability, or extensionAbility. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | +| abilities | Ability configuration, which is valid only for the current ability. For details, see [Internal Structure of the abilities Attribute](#internal-structure-of-the-abilities-attribute).| Object | Yes (initial value: left empty) | +| extensionAbilities | Extension ability configuration, which is valid only for the current Extension ability. For details, see [Internal structure of the extensionAbility attribute](#internal-structure-of-the-extensionability-attribute).| Object | Yes (initial value: left empty) | +| definePermissions | Permissions defined for the HAP file. This attribute applies only to system applications and does not take effect for third-party applications. The callers must acquire these permissions before calling the application. For details, see [Internal structure of the definePermissions attribute](#internal-structure-of-the-definepermissions-attribute).| Object | Yes (initial value: left empty)| +| requestPermissions | A set of permissions that the application needs to request from the system when the application is running. For details, see [Internal structure of the requestPermissions attribute](#internal-structure-of-the-requestpermissions-attribute). | Object | Yes (initial value: left empty) | +| testRunner | Test runner configuration. For details, see [Internal structure of the testRunner attribute](#internal-structure-of-the-testrunner-attribute).| Object | Yes (initial value: left empty) | Table 4 System-defined deviceTypes values -| Device Type | Value | Description | -| ------------ | ------------ | -------------------------------------------------------- | -| tablet | tablet | Tablet, speaker with a screen | -| smart TV | tv | N/A | -| smart watch | wearable | Smart watch, kids' watch, especially a watch that provides call features| -| head unit | car | N/A | -| router | router | Router | +| Value | Device Type | +| -------- | -------------------------------------------------------- | +| tablet | Tablet, speaker with a screen | +| tv | Smart TV | +| wearable | Smart watch, kids' watch, especially a watch that provides call features| +| car | Head unit | +| router | Router | Example of the **deviceTypes** attribute structure: ```json { - "module": { - "name": "myHapName", + "module": { + "name": "myHapName", "type": "har", "deviceTypes" : [ "wearable" ] - } + } } ``` -Example of the **pages** attribute structure:: +Example of the **pages** attribute structure: ```json { @@ -269,8 +252,8 @@ Table 5 Internal structure of the metadata attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------------- | -| name | Name of a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| -| value | Value of a data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | +| name | Name of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty)| +| value | Value of the data item. The value is a string with a maximum of 255 bytes. | String | Yes (initial value: left empty) | | resource | Custom data format. The value is an index to the resource that identifies the data.| String | Yes (initial value: left empty) | Example of the **metadata** attribute structure: @@ -304,17 +287,28 @@ Table 6 Internal structure of the abilities attribute | --------------- | ------------------------------------------------------------ | ---------- | ------------------------------------------------------------ | | name | Logical name of the ability, which must be unique in the entire application. The value is a string with a maximum of 127 bytes.| String | No | | srcEntrance | JS code path corresponding to the ability. The value is a string with a maximum of 127 bytes.| String | No | -| launchType | Ability startup mode. The value can be **standard**, **singleton**, or **specified**. The default value is **singleton**. The value **standard** indicates common multi-instance, the value **singleton** indicates a singleton, and the value **specified** indicates one or more specified instances, depending on the internal service of the ability.| String | Yes (initial value: **singleton**) | +| launchType | Ability startup mode. Available values are as follows:
**"standard"**: indicates common multi-instance.
**"singleton"**: indicates a singleton.
**"specified"**: indicates one or more specified instances, depending on the internal service of the ability. | String | Yes (initial value: **singleton**) | | description | Ability description. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the ability. The value is the index to the resource file. This attribute can be left empty, and the default value is an empty array.
If **ability** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| -| permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value must be the same as the **name** value of a permission defined in the **defPermissions** attribute. | String array| Yes (initial value: left empty) | -| metadata | Metadata about the ability. For details about metadata, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | +| icon | Icon of the ability. The value is the index to the resource file. | String | Yes (initial value: left empty)
If **ability** is set to **MainElement**, this attribute is mandatory.| +| permissions | Permissions required for abilities of another application to call the current ability. The value is an array of permission names predefined by the system, generally in the format of a reverse domain name the reverse domain name format (a maximum of 255 bytes).| String array| Yes (initial value: left empty) | +| metadata | Metadata of the ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Array | Yes (initial value: left empty) | | visible | Whether the ability can be invoked by other applications. The value **true** means that the ability can be invoked by other applications, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | | continuable | Whether the ability can be migrated. The value **true** means that the ability can be migrated, and **false** means the opposite.| Boolean | Yes (initial value: **false**) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.
For details about the internal structure of **skills**, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute).| Array | Yes (initial value: left empty) | +| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | | backgroundModes | Continuous task modes of the ability.
Continuous tasks are classified into the following types:
**dataTransfer**: service for downloading, backing up, sharing, or transferring data from the network or peer devices
**audioPlayback**: audio playback service
**audioRecording**: audio recording service
**location**: location and navigation services
**bluetoothInteraction**: Bluetooth scanning, connection, and transmission services (wearables)
**multiDeviceConnection**: multi-device interconnection service
**wifiInteraction**: Wi-Fi scanning, connection, and transmission services (multi-screen cloning)
**voip**: voice/video call and VoIP services
**taskKeeping**: computing service
| String | Yes (initial value: left empty) | -| startWindowIcon | Index to the icon file of the ability startup page. Example value: **$media:icon**. | String | No | -| startWindowBackground | Index to the background color resource file of the ability startup page. Example value: **$color:red**. | String | No | +| startWindowIcon | Index to the icon file of the ability startup page. Example: **$media:icon**.| String | No| +| startWindowBackground | Index to the background color resource file of the ability startup page. Example: **$color:red**.| String | No| +| removeMissionAfterTerminate | Whether to remove the relevant task from the task list after the ability is destroyed. The value **true** means to remove the relevant task from the task list after the ability is destroyed, and **false** means the opposite.| Boolean | Yes (initial value: **false**)| +| orientation | Display orientation of the ability when it is started. Available values are as follows:
**"unspecified"**: The device orientation is auto-set by the system.
**"landscape"**: The device is in landscape orientation.
**"portrait"**: The device is in portrait orientation.
**"landscape_inverted"**: The device is in inverted landscape orientation.
**"portrait_inverted"**: The device is in inverted portrait orientation.
**"auto_rotation"**: The device orientation is determined by the sensor.
**auto_rotation_landscape**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape.
**auto_rotation_portrait**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait.
**auto_rotation_restricted**: The device orientation is determined by the sensor when the sensor switch is enabled.
**auto_rotation_landscape_restricted**: The device orientation is determined by the sensor in the horizontal direction, including landscape and reverse landscape, when the sensor switch is enabled.
**auto_rotation_portrait_restricted**: The device orientation is determined by the sensor in the vertical direction, including portrait and reverse portrait, when the sensor switch is enabled.
**locked**: Auto rotate is disabled.| String | Yes (initial value: **"unspecified"**)| +|supportWindowMode|Window display mode of the ability. Available values are as follows:
**fullscreen**: full-screen mode.
**split**: split-screen mode.
**floating**: floating window mode.|Array | Yes (initial value:
["fullscreen", "split", "floating"])| +|priority|Priority of the ability. This attribute applies only to system applications and does not take effect for third-party applications. During implicit query, an ability with a higher the priority is closer to the top of the returned list. The value is an integer ranging from 0 to 10. A larger value indicates a higher priority.|Number| Yes (initial value: **0**)| +|maxWindowRatio|Maximum aspect ratio of the ability.| Number |Yes (initial value: maximum aspect ratio of the platform)| +|minWindowRatio|Minimum aspect ratio of the ability.| Number |Yes (initial value: minimum aspect ratio supported by the platform)| +|maxWindowWidth|Maximum window width of the ability, in vp.| Number |Yes (initial value: maximum window width supported by the platform)| +|minWindowWidth|Minimum window width of the ability, in vp.| Number |Yes (initial value: minimum window width supported by the platform)| +|maxWindowHeight|Maximum window height of the ability, in vp.| Number |Yes (initial value: maximum window height supported by the platform)| +|minWindowHeight|Minimum window height of the ability, in vp.| Number |Yes (initial value: minimum window height supported by the platform)| +| excludeFromMissions | Whether the ability is excluded from the recent tasks list. This attribute applies only to system applications and does not take effect for third-party applications. The value **true** indicates that the task is excluded from the recent tasks list, and **false** indicates that the task is displayed in the recent tasks list.| Boolean | Yes (initial value: **false**)| Example of the **abilities** attribute structure: @@ -323,7 +317,7 @@ Example of the **abilities** attribute structure: "abilities": [{ "name": "MainAbility", "srcEntrance": "./ets/login/MyLoginAbility.ts", - "launchType":"standard" + "launchType":"standard", "description": "$string:description_main_ability", "icon": "$media:icon", "label": "Login", @@ -347,7 +341,19 @@ Example of the **abilities** attribute structure: "voip", "taskKeeping" ], - }], + "startWindowIcon": "$media:icon", + "startWindowBackground": "$color:red", + "removeMissionAfterTerminate": true, + "orientation": " ", + "supportWindowMode": ["fullscreen", "split", "floating"], + "maxWindowRatio": 3.5, + "minWindowRatio": 0.5, + "maxWindowWidth": 2560, + "minWindowWidth": 1400, + "maxWindowHeight": 300, + "minWindowHeight": 200, + "excludeFromMissions": false + }] } ``` @@ -361,17 +367,17 @@ Table 7 Internal structure of the skills attribute | -------- | ------------------------------------------------------------ | ---------- | -------------------- | | actions | A set of want action values that can be received. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| | entities | Categories of abilities that can receive the want. The value can be a value predefined by the system or a custom value.| String array| Yes (initial value: left empty)| -| uris | Data specification to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details about the internal structure of **uris**, see Table 8.| Object array | Yes (initial value: left empty)| +| uris | Data specifications to be added to the want filter. The specification can be of data type only (**mimeType** attribute), URI only, or both. For details, see Table 8.| Object array | Yes (initial value: left empty)| Table 8 Internal structure of the uris attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------- | -------- | -------------------- | -| scheme | Scheme in the URI.| String | No | -| host | Host in the URI. | String | Yes (initial value: left empty)| -| port | Port number in the URI. | String | Yes (initial value: left empty)| -| path | Path in the URI. | String | Yes (initial value: left empty)| -| type | Type of the URI. | String | Yes (initial value: left empty)| +| scheme | Scheme of the URI.| String | No | +| host | Host value of the URI. | String | Yes (initial value: left empty)| +| port | Port number of the URI. | String | Yes (initial value: left empty)| +| path | **path** value of the URI. | String | Yes (initial value: left empty)| +| type | **type** value of the URI. | String | Yes (initial value: left empty)| Example of the **skills** attribute structure: @@ -396,10 +402,10 @@ Example of the **skills** attribute structure: "pathRegex":"/query/.*", "path":"path", "type": "text/*" - }, + } ] } - ], + ] } ], "extensionAbilities": [ @@ -419,34 +425,34 @@ Example of the **skills** attribute structure: "pathRegex":"/query/.*", "path":"path", "type": "text/*" - }, + } ] } - ], + ] } - ], + ] } ``` #### Internal Structure of the extensionAbility Attribute -The **extensionAbility** attribute describes the configuration information of **extensionAbility**. The configuration is valid only for the current extensionAbility. +The **extensionAbility** attribute describes the configuration information of the current Extension ability. Table 9 Internal structure of the extensionAbility attribute | Attribute | Description | Data Type | Initial Value Allowed | | ----------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Logical name of the current extensionAbility. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String | No | -| srcEntrance | JS code path corresponding to extensionAbility. The value is a string with a maximum of 127 bytes.| String | No | -| description | Description of the extensionAbility. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | -| icon | Icon of the extensionAbility. The value is the index to the resource file. If **extensionAbility** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty) | -| label | Name of the extensionAbility displayed to users. The value is a resource index to names in multiple languages.
If **extensionAbility** is set to **MainElement**, this attribute is mandatory and the value must be unique in the application.| String | No | -| type | Type of the extension capability. The value can be form, workScheduler, inputMethod, service, accessibility, dataShare, fileShare, staticSubscriber, wallpaper, or backup. | String | No | +| name | Logical name of the current Extension ability. The value is a string with a maximum of 127 bytes. The name must be unique in the entire application.| String | No | +| srcEntrance | JS code path corresponding to the Extension ability. The value is a string with a maximum of 127 bytes.| String | No | +| description | Description of the Extension ability. The value can be a string or a resource index to descriptions in multiple languages.| String | Yes (initial value: left empty) | +| icon | Icon of the Extension ability. The value is the index to the resource file. If **extensionAbility** is set to **MainElement**, this attribute is mandatory.| String | Yes (initial value: left empty) | +| label | Name of the Extension ability displayed to users. The value is a resource index to names in multiple languages.
If **extensionAbility** is set to **MainElement**, this attribute is mandatory and the value must be unique in the application.| String | No | +| type | Type of the Extension ability. The value can be **"form"**, **"workScheduler"**, **"inputMethod"**, **"service"**, **"accessibility"**, **"dataShare"**, **"fileShare"**, **"staticSubscriber"**, **"wallpaper"**, **"backup"**, **"window"**, **"enterpriseAdmin"**, **"thumbnail"**, or **"preview"**.| String | No | | permissions | A set of permissions that need to be applied for when the capability of another application is invoked. The value is a string array. Each array element is a permission name, which is usually represented by a reverse domain name (a maximum of 255 bytes). The permission can be predefined by the system or customized by the application. For the latter, the value must be the same as the **name** value of a permission defined in the **defPermissions** attribute.| String array| Yes (initial value: left empty) | | uri | Data URI provided by the ability. The value is an array containing a maximum of 255 characters and is in the format of a reverse domain name. This attribute is mandatory when **type** is set to **extensionAbility** of the dataShare type.| String | Yes (initial value: left empty) | -| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application,
but not for an OpenHarmony service.
For details about the internal structure of **skills**, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute).| Array | Yes (initial value: left empty) | -| metadata | Metadata of extensionAbility. For details about metadata, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Object | Yes (initial value: left empty) | -| visible | Whether extensionAbility can be invoked by other applications. The value is of the Boolean type. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| | Yes (initial value: **false**)| +| skills | Feature set of wants that can be received by the ability.
Configuration rule: In an entry package, you can configure multiple abilities with the **skills** attribute (where **action.system.home** and **entity.system.home** are configured) that has the entry capability. The **label** and **icon** in the first ability that has **skills** configured are used as the **label** and **icon** of the entire service/application.
The **skills** attribute with the entry capability can be configured for the feature package of an OpenHarmony application, but not for an OpenHarmony service.
For details, see [Internal Structure of the skills Attribute](#internal-structure-of-the-skills-attribute). | Array | Yes (initial value: left empty) | +| metadata | Metadata of the Extension ability. For details, see [Internal Structure of the metadata Attribute](#internal-structure-of-the-metadata-attribute).| Object | Yes (initial value: left empty) | +| visible | Whether extensionAbility can be invoked by other applications. The value is of the Boolean type. The value **true** means that it can be invoked by other applications, and the value **false** means the opposite.| Boolean | Yes (initial value: **false**)| Example of the **extensionAbility** attribute structure: @@ -475,29 +481,47 @@ Example of the **extensionAbility** attribute structure: "name": "ohos.extability.form", "resource": "$profile:form_config", } - ], + ] } ] } ``` +#### Internal Structure of the definePermissions Attribute + +The **definePermissions** attribute indicates the permissions defined for the HAP file. + +Table 10 Internal structure of the definePermissions attribute + +| Attribute | Description | Data Type| Initial Value Allowed | +| ---------------------- | ------------------------------------------------------------ | -------- | ------------------------------ | +| name | Permission name. | String | No | +| grantMode | Permission grant mode. Available values are as follows:
**"system_grant"**: The permission is automatically granted by the system after the application is installed.
**"user_grant"**: The permission must be dynamically requested and can be used only after being granted by the user.| String | Yes (initial value: **"system_grant"**)| +| availableLevel | Permission level. Available values are as follows:
**"system_core"**: core system permission.
**"system_basic"**: basic system permission.
**"normal"**: normal permission, which is open to all applications. | String | Yes (initial value: **"normal"**) | +| provisionEnable | Whether to enable provision mode for requesting permissions, including higher-level permissions. The value **true** indicates that provision mode is enabled.| Boolean | Yes (initial value: **true**) | +| distributedSceneEnable | Whether the permission can be used in distributed scenarios. | Boolean | Yes (initial value: **false**) | +| label | Brief description of the permission. The value is a resource index. | String | Yes (initial value: left empty) | +| description | Detailed description of the permission, which can be a string or a resource index.| String | Yes (initial value: left empty) | + #### Internal Structure of the requestPermissions Attribute -This attribute identifies a set of permissions that the application needs to apply for from the system when the application is running. +This attribute identifies a set of permissions that the application needs to request from the system when the application is running. -Table 10 requestPermissions attributes +Table 11 Internal structure of the requestPermissions attribute -| Attribute | Description | **Type** | **Value Range** | **Default Value** | **Restrictions** | -| --------- | ------------------------------------------------------------ | ------------------------------- | ----------------------------------------------------------- | ---------------------- | ------------------------------------------------------------ | -| name | Permission name. This attribute is mandatory. | String | Custom | None | Parsing will fail if this field is not set. | -| reason | Reason for requesting the permission. This attribute is mandatory when the requested permission is **user_grant**. | String | The maximum length is 256 bytes. | Empty | If the requested permission is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required. | -| usedScene | Application scenario and timing for using the permission, which is mandatory when the requested permission is **user_grant**. This attribute consists of the **ability** and **when** sub-attributes. Multiple abilities can be configured. | **ability**: string array; **when**: string | **ability**: ability name; **when**: **inuse** or **always** | **ability**: left empty; **when**: **inuse** | If the requested permission is **user_grant**, the **ability** sub-attribute is mandatory and **when** is optional. | +| Attribute | Description | Type | Value Range | Default Value | Restrictions | +| --------- | ------------------------------------------------------------ | ---------------------------------------- | ------------------------------------------------------------ | -------------------- | ------------------------------------------------------------ | +| name | Permission name. This attribute is mandatory. | String | Custom | N/A | Parsing will fail if this attribute is not set. | +| reason | Reason for requesting the permission. This attribute is mandatory when the permission to request is **user_grant**. | String | Resource reference of the string type in `$string: ***` format | Empty | If the permission to request is **user_grant**, this attribute is required for the application to be released to AppGallery. Multi-language adaptation is required.| +| usedScene | Application scenario and timing for using the permission. This attribute is mandatory when the permission to request is **user_grant**. It consists of the **abilities** and **when** sub-attributes. Multiple abilities can be configured.| **abilities**: string array; **when**: string| **abilities**: array of ability names; **when**: **inuse** and **always**| **abilities**: left empty; **when**: left empty| If the permission to request is **user_grant**, the **abilities** sub-attribute is mandatory and **when** is optional. | Example of the **requestPermissions** attribute structure: ```json { + "name": "ohos.abilitydemo.permission.PROVIDER", + "reason": "$string:reason", "usedScene": { "abilities": [ "AudioAbility", @@ -507,34 +531,38 @@ Example of the **requestPermissions** attribute structure: } } ``` +For details, see [Access Control (Permission) Development](../security/accesstoken-guidelines.md#fa-model). #### Internal Structure of the form Attribute The **forms** attribute indicates the service widget configuration. The service widget is an application brief view that can be displayed on the home screen and periodically updated. You can include the **forms** attribute in any of the following modes: 1. Set **type** to **form** in **extensions**. -2. Specify the **form** information in **metadata**, where: - - **name** indicates the name of the service widget, for example, **ohos.extability.form**. - - **resource** indicates where the resources of the service widget are stored. - -Table 11 Internal structure of the forms attribute - -| Attribute | Description | Data Type | Initial Value Allowed | -| ----------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | -| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | -| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | -| src | UI code of a JS service widget. It is recommended that you use the adaptive layout to display a service widget of different specifications. If the layout of a service widget of different specifications differs greatly, you are advised to use different service widgets.| String | Yes (initial value: left empty) | -| window | Adaptive capability of a JS service widget. For details about the window structure, see Table 12. | Object | Yes (initial value: left empty) | -| isDefault | Whether the service widget is the default one. Each ability has only one default service widget. **true**: The service widget is the default one. **false**: The service widget is not the default one.| Boolean | No | -| colorMode | Theme style of the service widget. The value can be **auto**, **dark**, or **light**.| String | Yes (initial value: **auto**) | -| supportDimensions | Dimensions supported by the service widget. The value can be **1 * 2**, **2 * 2**, **2 * 4**, or **4 * 4**, where the number before the asterisk (*) indicates the number of rows, and the number after the asterisk (*) indicates the number of columns.| String array| No | -| defaultDimension | Default grid style of the widget. The value must be available in the **supportDimensions** array of the widget.| String | No | -| updateDuration | Update frequency of a widget. The unit is 30 minutes. The value is a multiple of 30. The highest frequency of refreshing a widget is once every 30 minutes. You can also use scheduled refresh to refresh a widget at a fixed time or once every 30 minutes. If both of them are configured, the scheduled refresh takes precedence.| Number | Yes (initial value: left empty) | -| metadata | Custom information about a widget. For details about the internal structure of metadata, see Table 5. | Object | Yes (initial value: left empty) | -| formConfigAbility | Ability name for widget adjustment. The value is a string of up to 127 characters. The value must be in the following format:
ability:// Name of an ability.
The name must be the same as that of the current application.| String | Yes (initial value: left empty) | -| formVisibleNotify | Whether the widget is allowed to use the visibility notification. The value is **true** or **false**.| Boolean | Yes (initial value: **false**)| - -Table 12 Internal structure of window + +2. Specify the **form** information in **metadata**, where: + - **name** indicates the name of the service widget, for example, **ohos.extability.form**. + - **resource** indicates where the resources of the service widget are stored. + +Table 12 Internal structure of the forms attribute + +| Attribute | Description | Data Type | Initial Value Allowed | +| ------------------- | ------------------------------------------------------------ | ---------- | ----------------------------- | +| name | Class name of the widget. The value is a string with a maximum of 127 bytes. | String | No | +| description | Description of the widget. The value can be a string or a resource index to descriptions in multiple languages. The value is a string with a maximum of 255 bytes.| String | Yes (initial value: left empty) | +| src | UI code of a JS service widget. It is recommended that you use the adaptive layout to display a service widget of different specifications. If the layout of a service widget of different specifications differs greatly, you are advised to use different service widgets.| String | Yes (initial value: left empty) | +| window | Adaptive capability of a JS service widget. For details, see Table 12. | Object | Yes (initial value: left empty) | +| isDefault | Whether the widget is a default one. Each ability has only one default widget. **true**: The service widget is the default one. **false**: The service widget is not the default one.| Boolean | No | +| colorMode | Color mode of the widget. The value can be **auto**, **dark**, or **light**.| String | Yes (initial value: **auto**) | +| supportDimensions | Dimensions supported by the service widget. The value can be **1 * 2**, **2 * 1**, **2 * 2**, **2 * 4**, or **4 * 4**, where the number before the asterisk (*) indicates the number of rows, and the number after the asterisk (*) indicates the number of columns.| String array| No | +| defaultDimension | Default grid style of the widget. The value must be from the **supportDimensions** array of the widget.| String | No | +| updateEnabled | Whether the widget can be updated periodically. The value **true** indicates that the widget can be updated periodically, and **false** indicates that the widget cannot be updated periodically.| Boolean | No | +| scheduledUpdateTime | Scheduled time to update the widget. The value is in 24-hour format and accurate to minute. | String | Yes | +| updateDuration | Update frequency of a widget. The unit is 30 minutes. The value is a multiple of 30. The highest frequency of refreshing a widget is once every 30 minutes. You can also use scheduled refresh to refresh a widget at a fixed time or once every 30 minutes. If both of them are configured, the scheduled refresh takes precedence.| Number | Yes (initial value: left empty) | +| metadata | Metadata of the widget. For details, see Table 5. | Object | Yes (initial value: left empty) | +| formConfigAbility | Ability name for widget adjustment. The value is a string of up to 127 characters. The value must be in the following format:
ability:// Name of an ability.
The name must be the same as that of the current application.| String | Yes (initial value: left empty) | +| formVisibleNotify | Whether the widget is allowed to use the visibility notification. The value is **true** or **false**.| Boolean | Yes (initial value: **false**)| + +Table 13 Internal structure of the window attribute | Attribute | Description | Data Type| Initial Value Allowed | | --------------- | ------------------------------------------------------------ | -------- | -------------------- | @@ -564,10 +592,12 @@ Define the **form_config.json** file (this file name is customizable) in **resou "scheduledUpdateTime": "10:30", "updateDuration": 1, "defaultDimension": "2*2", + "updateEnabled": true, + "scheduledUpdateTime": "21:33", "supportDimensions": [ "2*2" ], - "metadata": [ + "metadata": [ { "name": "string", "value": "string", @@ -579,22 +609,18 @@ Define the **form_config.json** file (this file name is customizable) in **resou } ``` -Define metadata information in the **extension** component of the **module.json** file. +Define metadata information in the **extension** component of the **module.json5** file. ```json { - "extensionAbilities": [ - { - "name": "MyForm", - "type": "form", - "metadata": [ - { - "name": "ohos.extability.form", - "resource": "$profile:form_config", - } - ], - } - ] + "extensionAbilities": [{ + "name": "MyForm", + "type": "form", + "metadata": [{ + "name": "ohos.extability.form", + "resource": "$profile:form_config" + }] + }] } ``` @@ -604,16 +630,16 @@ This attribute identifies the shortcut information of an application. The value Specify the **shortcut** information in **metadata**, where: -- **name** indicates the name of the shortcut, for example, **ohos.ability.shortcut**. +- **name** indicates the name of the shortcut, for example, **ohos.ability.shortcuts**. - **resource** indicates where the resources of the shortcut are stored. -Table 13 Internal structure of the shortcuts attribute +Table 14 Internal structure of the shortcuts attribute | Attribute | Description | Data Type| Initial Value Allowed | | ---------- | ------------------------------------------------------------ | -------- | -------------------------- | | shortcutId | ID of the shortcut. The value is a string with a maximum of 63 bytes. | String | No | -| label | Label of the shortcut, that is, the text description displayed by the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty) | +| label | Label of the shortcut, that is, the text description displayed for the shortcut. The value can be a string or a resource index to the description. The value is a string with a maximum of 63 bytes.| String | Yes (initial value: left empty) | | icon | Icon of the shortcut. The value is the index to the resource file. | String | Yes (initial value: left empty)| | wants | Wants to which the shortcut points. The attribute consists of the **bundleName** and **abilityName** sub-attributes.
**bundleName**: target bundle name of the shortcut; string type.
**abilityName**: target component name of the shortcut; string type.| Object | Yes (initial value: left empty) | @@ -621,45 +647,37 @@ Define the **shortcut_config.json** file (this file name is customizable) in **r ```json { - "shortcuts": [ - { - "shortcutId": "id_test1", - "label": "$string:shortcut", - "icon": "$media:aa_icon", - "wants": [ - { - "bundleName": "com.ohos.hello" - "abilityName": "MainAbility" - } - ] - } - ] + "shortcuts": [{ + "shortcutId": "id_test1", + "label": "$string:shortcut", + "icon": "$media:aa_icon", + "wants": [{ + "bundleName": "com.ohos.hello", + "abilityName": "MainAbility" + }] + }] } ``` -Define the **metadata** information under **module** in the **config.json** file as follows: +Define the **metadata** information under **module** in the **module.json5** file as follows: ```json { "module": { "name": "MyAbilityStage", - "abilities" : [ - { - "name" : "MyAbility", - "srcEntrance": "./abilities/MyAbility.ts", - "skills": [{ - "actions": ["action.system.home"], - "entities": ["entity.system.home"], - "uris": [] - }], - "metadata": [ - { - "name": "ohos.ability.shortcut", - "resource": "$profile:shortcuts_config", - } - ], - } - ] + "abilities": [{ + "name": "MyAbility", + "srcEntrance": "./abilities/MyAbility.ts", + "skills": [{ + "actions": ["action.system.home"], + "entities": ["entity.system.home"], + "uris": [] + }], + "metadata": [{ + "name": "ohos.ability.shortcuts", + "resource": "$profile:shortcuts_config" + }] + }] } } ``` @@ -674,7 +692,7 @@ Specify the **commonEvent** information in the **metadata**, where: - **resource** indicates where the resources of the common event are stored. -Table 14 Internal structure of the commonEvents attribute +Table 15 Internal structure of the commonEvents attribute | Attribute | Description | Data Type | Initial Value Allowed | | ---------- | ------------------------------------------------------------ | ---------- | -------------------------- | @@ -687,24 +705,22 @@ Define the **common_event_config.json** file in **resources/base/profile** in th ```json { - "commonEvents": [ - { - "name": "abilityName", - "permission": "string", - "types": [ - "string", - "string" - ], - "events": [ - "string", - "string" - ] - } - ] + "commonEvents": [{ + "name": "abilityName", + "permission": "string", + "types": [ + "string", + "string" + ], + "events": [ + "string", + "string" + ] + }] } ``` -Define the **metadata** information under **extension** in the **module.json** file as follows: +Define the **metadata** information under **extension** in the **module.json5** file as follows: ```json "extensionAbilities": [ @@ -712,66 +728,64 @@ Define the **metadata** information under **extension** in the **module.json** f "name": "mySubscriber", "srcEntrance": "./extension/my_subscriber.js", "type": "staticSubscriber", - "metadata": [ - { - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:common_event_config", - } - ], + "metadata": [{ + "name": "ohos.extability.staticSubscriber", + "resource": "$profile:common_event_config", + }], } ] ``` #### Internal Structure of the distroFilter Attribute -Application distribution rules. +Distribution rules of the application. -This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when AppGallery distributes applications. Applications can be distributed by API version, screen shape, or screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. +This attribute defines the rules for distributing HAP files based on different device specifications, so that precise matching can be performed when AppGallery distributes applications. Distribution rules cover three factors: API version, screen shape, and screen resolution. During distribution, a unique HAP is determined based on the mapping between **deviceType** and these three factors. -Table 15 Internal structure of the distroFilter attribute +Table 16 Internal structure of the distroFilter attribute | Attribute | Description | Data Type| Initial Value Allowed | | ------------- | ------------------------------------------------------------ | -------- | -------------------------- | | apiVersion | Supported API versions. For details, see Table 16. | Object array| Yes (initial value: left empty)| | screenShape | Supported screen shapes. | Object array| Yes (initial value: left empty)| -| screenWindow | Supported window resolutions when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)| -| screenDensity | Dots per inch (DPI) of the screen. This attribute is optional. The value options are as follows:
**sdpi**: small-scale dots per inch. This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: medium-scale dots per inch. This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: large-scale dots per inch. This value is applicable for devices with a DPI in the (160, 240] range.
**xldpi**: extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (240, 320] range.
**xxldpi**: extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI in the (320, 480] range.
**xxxldpi**: extra-extra-extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (480, 640] range.| Object array| Yes (initial value: left empty)| -| countryCode | Code of the country or region to which an application is to be distributed. For details, see ISO-3166-1. Enumerated definitions of multiple countries and regions are supported. This attribute is optional. The substring of the value consists of two uppercase letters and indicates the supported countries or regions.| Object array| Yes (initial value: left empty)| +| screenWindow | Supported window resolutions for when the application is running. This attribute applies only to the lite wearables.| Object array| Yes (initial value: left empty)| +| screenDensity | Pixel density of the screen, in dots per inch (dpi). This attribute is optional. The value options are as follows:
**sdpi**: small-scale dots per inch. This value is applicable for devices with a DPI range of (0, 120].
**mdpi**: medium-scale dots per inch. This value is applicable for devices with a DPI range of (120, 160].
**ldpi**: large-scale dots per inch. This value is applicable for devices with a DPI in the (160, 240] range.
**xldpi**: extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (240, 320] range.
**xxldpi**: extra-extra-large-scale dots per inch (XXLDPI). This value is applicable for devices with a DPI in the (320, 480] range.
**xxxldpi**: extra-extra-extra-large-scale dots per inch. This value is applicable for devices with a DPI in the (480, 640] range.| Object array| Yes (initial value: left empty)| +| countryCode | Code of the country or region to which the application is to be distributed. For details, see ISO-3166-1. Enumerated definitions of multiple countries and regions are supported. This attribute is optional. The substring of the value consists of two uppercase letters and indicates the supported countries or regions.| Object array| Yes (initial value: left empty)| -Table 16 Internal structure of the apiVersion attribute +Table 17 Internal structure of the apiVersion attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released. | Array | Yes (initial value: left empty)| +| value | An integer of the existing API version, for example, 4, 5, or 6. If an application uses two software versions developed using API 5 and API 6 for the same device model, two installation packages of the entry type can be released.| Array | Yes (initial value: left empty)| -Table 17 Internal structure of the screenShape attribute +Table 18 Internal structure of the screenShape attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | The value can be **circle** or **rect**. Example: Different HAPs can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| +| value | The value can be **circle** or **rect**. Example: Different HAP files can be provided for a smart watch with a circular face and a smart watch with a rectangular face.| Array | Yes (initial value: left empty)| -Table 18 Internal structure of the screenWindow attribute +Table 19 Internal structure of the screenWindow attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| | value | Width and height of the screen. The value is in the "width * height" format, in pixels, for example, **454*454**.| Array | Yes (initial value: left empty)| -Table 19 Internal structure of the screenDensity attribute +Table 20 Internal structure of the screenDensity attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Dots per inch (DPI) of the screen. | Array | Yes (initial value: left empty)| +| value | Pixel density of the screen, in dots per inch (dpi). | Array | Yes (initial value: left empty)| -Table 20 Internal structure of the countryCode attribute +Table 21 Internal structure of the countryCode attribute | Attribute| Description | Data Type| Initial Value Allowed | | -------- | ------------------------------------------------------------ | -------- | -------------------- | | policy | Blocklist and trustlist rule of the sub-attribute value. Set this attribute to **exclude** or **include**. **include** indicates that the sub-attribute value is in the trustlist. If the value matches any of the **value** enums, it matches this attribute.| String | Yes (initial value: left empty)| -| value | Code of the country or region to which an application is to be distributed. | Array | Yes (initial value: left empty)| +| value | Code of the country or region to which the application is to be distributed. | Array | Yes (initial value: left empty)| Example of the **distroFilter** attribute structure: @@ -780,37 +794,50 @@ Define the **distroFilter_config.json** file in **resources/base/profile** of th ```json "distroFilter": [ { - "apiVersion": { + "apiVersion": { "policy": "include", - "value": [4,5] + "value": [4, 5] }, "screenShape": { "policy": "include", - "value": ["circle","rect"] + "value": ["circle", "rect"] }, "screenWindow": { "policy": "include", - "value": ["454*454","466*466"] + "value": ["454*454", "466*466"] } } ] ``` -Define the **metadata** information under **extensionAbilities** in the **module.json** file as follows: +Define the **metadata** information under **extensionAbilities** in the **module.json5** file as follows: ```json "extensionAbilities": [ { "name": "mySubscriber", "srcEntrance": "./extension/my_subscriber.js", - "type": "staticSubscriber", - "metadata": [ - { - "name": "ohos.extability.staticSubscriber", - "resource": "$profile:distroFilter_config", - } - ], + "type": "staticSubscriber", + "metadata": [{ + "name": "ohos.extability.staticSubscriber", + "resource": "$profile:distroFilter_config", + }], } ] +``` + +#### Internal Structure of the testRunner Attribute +Table 22 Internal structure of the testRunner attribute + +| Attribute| Description | Data Type| Initial Value Allowed| +| -------- | ---------------------- | -------- | ---------- | +| name | Name of the test runner object.| String | No| +| srcPath | Path of the test runner code.| String | No| + +``` +"testRunner": { + "name": "myTestRUnnerName", + "srcPath": "etc/test/TestRunner.ts" +} ``` diff --git a/en/application-dev/reference/apis/js-apis-Bundle.md b/en/application-dev/reference/apis/js-apis-Bundle.md index e487baedfd496a9ac0a6e90332aa99f3323a4fc2..ca3b0873ab187379e62b7640c55bb650f84d4850 100644 --- a/en/application-dev/reference/apis/js-apis-Bundle.md +++ b/en/application-dev/reference/apis/js-apis-Bundle.md @@ -139,6 +139,80 @@ bundle.getApplicationInfo(bundleName, bundleFlags, (err, data) => { }) ``` +## bundle.getApplicationInfoSync9+ + +getApplicationInfoSync(bundleName: string, bundleFlags: number, userId: number): ApplicationInfo; + +Obtains the application information of the specified user based on a given bundle name. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| +| userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------- | +| [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | **ApplicationInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 0; +let userId = 100; +var applicationInfo = bundle.getApplicationInfoSync(bundleName, bundleFlags, userId); +console.info('Operation successful. Name:' + applicationInfo.name); +``` + +## bundle.getApplicationInfoSync9+ + +getApplicationInfoSync(bundleName: string, bundleFlags: number) : ApplicationInfo; + +Obtains the application information based on a given bundle name. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the application information flags in [BundleFlag](#bundleflag).| + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ------------------- | +| [ApplicationInfo](js-apis-bundle-ApplicationInfo.md) | **ApplicationInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 0; +var applicationInfo = bundle.getApplicationInfoSync(bundleName, bundleFlags); +console.info('Operation successful. Name:' + applicationInfo.name); +``` + ## bundle.getAllBundleInfo getAllBundleInfo(bundleFlag: BundleFlag, userId?: number): Promise> @@ -370,6 +444,82 @@ bundle.getBundleInfo(bundleName, bundleFlags, options, (err, data) => { }) ``` +## bundle.getBundleInfoSync9+ + +getBundleInfoSync(bundleName: string, bundleFlags: number, options: BundleOptions): BundleInfo; + +Obtains the bundle information based on a given bundle name and bundle options. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------------------------------- | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| +| options | [BundleOptions](#bundleoptions) | Yes | Options of the bundle. | + +**Return value** + +| Type | Description | +| ------------------------------------------ | -------------- | +| [BundleInfo](js-apis-bundle-BundleInfo.md) | **BundleInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 1; +let options = { + "userId" : 100 +}; +var bundleInfo = bundle.getBundleInfoSync(bundleName, bundleFlags, options); +console.info('Operation successful. Name:' + bundleInfo.name); +``` + +## bundle.getBundleInfoSync9+ + +getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo; + +Obtains the bundle information based on a given bundle name. This API returns the result synchronously. + +**Required permissions** + +ohos.permission.GET_BUNDLE_INFO_PRIVILEGED or ohos.permission.GET_BUNDLE_INFO + +**System capability** + +SystemCapability.BundleManager.BundleFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | ------ | ---- | ------------------------------------------------------------ | +| bundleName | string | Yes | Bundle name of an application. | +| bundleFlags | number | Yes | Type of information that will be returned. The default value is **0**. For details on the available enumerated values, see the bundle information flags in [BundleFlag](#bundleflag).| + +**Return value** + +| Type | Description | +| ------------------------------------------ | -------------- | +| [BundleInfo](js-apis-bundle-BundleInfo.md) | **BundleInfo** object.| + +**Example** + +```js +let bundleName = "com.example.myapplication"; +let bundleFlags = 1; +var bundleInfo = bundle.getBundleInfoSync(bundleName, bundleFlags); +console.info('Operation successful. Name:' + bundleInfo.name); +``` + ## bundle.getBundleInstaller getBundleInstaller(): Promise<BundleInstaller>; @@ -685,7 +835,7 @@ This is a system API and cannot be called by third-party applications. | ----------- | --------------------------- | ---- | ---------------------- | | bundleName | string | Yes | Bundle name of an application. | | moduleName | string | Yes | Module name of the application. | -| upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| +| upgradeFlag | [UpgradeFlag](#upgradeflag) | Yes | Upgrade flag, which is for internal use only.| **Return value** @@ -758,10 +908,10 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ---------------------------------- | ---- | ---------------------------------------------------- | -| bundleName | string | Yes | Bundle name of an application. | -| bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------- | +| bundleName | string | Yes | Bundle name of an application. | +| bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package. | | callback | AsyncCallback | Yes | Callback used to return the bundle package information.| ## bundle.getBundlePackInfo9+ @@ -780,16 +930,16 @@ This is a system API and cannot be called by third-party applications. **Parameters** -| Name | Type | Mandatory| Description | -| -------------- | ------------------- | ---- | ---------------------- | -| bundleName | string | Yes | Bundle name of an application. | +| Name | Type | Mandatory| Description | +| -------------- | ------------------------------------------------- | ---- | ---------------------- | +| bundleName | string | Yes | Bundle name of an application. | | bundlePackFlag | pack.BundlePackFlag | Yes | Flags of the bundle package.| **Return value** -| Type | Description | -| ---------------------------- | ----------------------------------- | -| Promise | Promise used to return the bundle package information.| +| Type | Description | +| ---------------------------- | ------------------------------------------------------ | +| Promise | Promise used to return the bundle package information. | ## bundle.getDispatcherVersion9+ @@ -1894,7 +2044,7 @@ SystemCapability.BundleManager.BundleFramework | -------------- | ------ | ---- | ---------------------------------------- | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | | extensionType | number | Yes | Type of the Extension ability information to obtain. The default value is **0**. For details on the available enumerated values, see [ExtensionAbilityType](#extensionabilitytype9).| -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| +| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| | userId | number | No | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | **Return value** @@ -1943,7 +2093,7 @@ SystemCapability.BundleManager.BundleFramework | -------------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | | extensionType | number | Yes | Type of the Extension ability information to obtain. The default value is **0**. For details on the available enumerated values, see [ExtensionAbilityType](#extensionabilitytype9).| -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| +| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| | userId | number | Yes | User ID. The default value is the user ID of the caller. The value must be greater than or equal to 0. | | callback | AsyncCallback> | Yes | Callback used to return the Extension ability information. | @@ -1986,7 +2136,7 @@ SystemCapability.BundleManager.BundleFramework | -------------- | ---------------------------------------- | ---- | ---------------------------------------- | | want | [Want](js-apis-application-Want.md) | Yes | Want that contains the bundle name. | | extensionType | number | Yes | Type of the Extension ability information to obtain. The default value is **0**. For details on the available enumerated values, see [ExtensionAbilityType](#extensionabilitytype9).| -| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| +| extensionFlags | number | Yes | Extension ability information to be returned. The default value is **0**. For details on the available enumerated values, see [ExtensionFlags](#extensionflag9).| | callback | AsyncCallback> | Yes | Callback used to return the Extension ability information. | **Example** diff --git a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md index 06cac3878b46d62fdc09e6a342bdcc9340714c4f..7732457b6f32608db4c51f55e1cfa5ff0ee28ae8 100644 --- a/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md +++ b/en/application-dev/reference/apis/js-apis-EnterpriseAdminExtensionAbility.md @@ -49,3 +49,51 @@ export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbil } }; ``` + +## EnterpriseAdminExtensionAbility.onBundleAdded + +onBundleAdded(bundleName: string): void + +Called when a bundle is added. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| bundleName | string | Yes | Name of the bundle added.| + +**Example** + +```ts +export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { + onBundleAdded(bundleName: string) { + console.log("added bundle name: " + bundleName); + } +}; +``` + +## EnterpriseAdminExtensionAbility.onBundleRemoved + +onBundleRemoved(bundleName: string): void + +Called when a bundle is removed. + +**System capability**: SystemCapability.Customization.EnterpriseDeviceManager + +**Parameters** + +| Parameter | Type | Mandatory | Description | +| ----- | ----------------------------------- | ---- | ------- | +| bundleName | string | Yes | Name of the bundle removed.| + +**Example** + +```ts +export default class EnterpriseAdminAbility extends EnterpriseAdminExtensionAbility { + onBundleAdded(bundleName: string) { + console.log("removed bundle name: " + bundleName); + } +}; +``` diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index 003a5efd92057dc7127b74aa35553f3220bd890e..733fee0c5671f9e100191f8b23a54fd7b5edec67 100644 --- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -25,7 +25,7 @@ Creates an **AtManager** instance, which is used for ability access control. | Type| Description| | -------- | -------- | -| [AtManager](#atmanager) | **AtManager** instance obtained.| +| [AtManager](#atmanager) | **AtManager** instance created.| **Example** @@ -37,9 +37,9 @@ var AtManager = abilityAccessCtrl.createAtManager(); Implements ability access control. -### verifyAccessToken +### checkAccessToken9+ -verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> +checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> Checks whether an application has been granted the specified permission. This API uses a promise to return the result. @@ -49,24 +49,31 @@ Checks whether an application has been granted the specified permission. This AP | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to verify.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<GrantStatus> | Promise instance used to return the result.| +| Promise<GrantStatus> | Promise used to return the permission grant state.| **Example** ```js -var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; -let promise = AtManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + AtManager.checkAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + console.log(`checkAccessToken success, data->${JSON.stringify(data)}`); + }).catch((err) => { + console.log(`checkAccessToken fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### verifyAccessTokenSync9+ @@ -81,7 +88,7 @@ Checks whether an application has been granted the specified permission. This AP | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. | | permissionName | string | Yes | Name of the permission to verify.| **Return value** @@ -95,13 +102,13 @@ Checks whether an application has been granted the specified permission. This AP ```js var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; -let data = verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let data = AtManager.verifyAccessTokenSync(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); console.log(`data->${JSON.stringify(data)}`); ``` ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> +grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> Grants a user granted permission to an application. This API uses a promise to return the result. @@ -115,31 +122,38 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to grant.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise instance used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** ```js -var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -let promise = AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + console.log('grantUserGrantedPermission success'); + }).catch((err) => { + console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### grantUserGrantedPermission -grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void +grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void Grants a user granted permission to an application. This API uses an asynchronous callback to return the result. @@ -153,29 +167,35 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to grant.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<number> | Yes| Callback used to return the result.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js +import privacyManager from '@ohos.abilityAccessCtrl'; + var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { - if (err) { - console.log(`callback: err->${JSON.stringify(err)}`); - } else { - console.log(`callback: data->${JSON.stringify(data)}`); - } -}); +try { + AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (data, err) => { + if (err) { + console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('grantUserGrantedPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<number> +revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> Revokes a user granted permission given to an application. This API uses a promise to return the result. @@ -189,31 +209,38 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to revoke.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise instance used to return the result.| +| Promise<void> | Promise that returns no value.| **Example** ```js -var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -let promise = AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag); -promise.then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag).then(() => { + console.log('revokeUserGrantedPermission success'); + }).catch((err) => { + console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### revokeUserGrantedPermission -revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<number>): void +revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void Revokes a user granted permission given to an application. This API uses an asynchronous callback to return the result. @@ -227,24 +254,30 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to revoke.| -| permissionFlag | number | Yes | Permission flag. The value **1** means that a dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | -| callback | AsyncCallback<number> | Yes| Callback used to return the result.| +| permissionFlag | number | Yes | Permission flag. The value **1** means that the permission request dialog box will still be displayed after the user grants or denies the permission. The value **2** means that no dialog box will be displayed after the user grants or denies the permission. The value **3** means a system permission that cannot be changed. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result.| **Example** ```js +import privacyManager from '@ohos.abilityAccessCtrl'; + var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. let permissionFlag = 1; -AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { - if (err) { - console.log(`callback: err->${JSON.stringify(err)}`); - } else { - console.log(`callback: data->${JSON.stringify(data)}`); - } -}); +try { + AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (data, err) => { + if (err) { + console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('revokeUserGrantedPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ### getPermissionFlags @@ -263,21 +296,167 @@ This is a system API. | Name | Type | Mandatory| Description | | --------- | ------------------- | ---- | ------------------------------------------------------------ | -| tokenID | number | Yes | ID of the application. | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission to query.| **Return value** | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise instance used to return the result.| +| Promise<number> | Promise used to return the result.| + +**Example** + +```js +import privacyManager from '@ohos.abilityAccessCtrl'; + +let AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let permissionFlag = 1; +try { + AtManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS").then((data) => { + console.log(`getPermissionFlags success, data->${JSON.stringify(data)}`); + }).catch((err) = > { + console.log(`getPermissionFlags fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +### getVersion9+ + +getVersion(): Promise<number> + +Obtains the data version of the current permission management. This API uses a promise to return the result. + +This is a system API. + +**System capability**: SystemCapability.Security.AccessToken + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<number> | Promise used to return the version.| **Example** ```js var AtManager = abilityAccessCtrl.createAtManager(); -let tokenID = 0; -let promise = AtManager.getPermissionFlags(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +let promise = AtManager.getVersion(); +promise.then(data => { + console.log(`promise: data->${JSON.stringify(data)}`); +}); +``` + +### on9+ + +on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<string>, callback: Callback<PermissionStateChangeInfo>): void; + +Subscribes to permission grant state change events of a specified token ID list and permission list. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'permissionStateChange'**, indicating the permission grant state change event. | +| tokenIDList | Array<number> | No | List of token IDs. If this parameter is left empty, the permission grant state changes of all applications are subscribed to. | +| permissionNameList | Array<string> | No | List of permission names. If this parameter is left empty, the permission grant state changes of all permissions are subscribed to. | +| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | Yes| Callback used to return the permission grant state change information.| + +**Example** + +```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager = abilityAccessCtrl.createAtManager(); +let tokenIDList: Array = []; +let permissionNameList: Array = []; +try { + atManager.on('permissionStateChange', tokenIDList, permissionNameList, (data) => { + console.debug("receive permission state change, data:" + JSON.stringify(data)); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +### off9+ + +off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<string>, callback?: Callback<PermissionStateChangeInfo>): void; + +Unsubscribes from permission grant state change events of a specified token ID list and permission list. This API uses an asynchronous callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.GET_SENSITIVE_PERMISSIONS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value is fixed at **'permissionStateChange'**, indicating the permission grant state change event. | +| tokenIDList | Array<number> | No | List of token IDs. If this parameter is left empty, the permission grant state changes of all applications are unsubscribed from. The value must be the same as that passed in **on()**.| +| permissionNameList | Array<string> | No | List of permission names. If this parameter is left empty, the permission grant state changes of all permissions are unsubscribed from. The value must be the same as that passed in **on()**.| +| callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | No| Callback used to return the permission grant state change information.| + +**Example** + +```js +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; + +let atManager = abilityAccessCtrl.createAtManager(); +let tokenIDList: Array = []; +let permissionNameList: Array = []; +try { + atManager.off('permissionStateChange', tokenIDList, permissionNameList); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +### verifyAccessToken(deprecated) + +verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> + +Checks whether an application has been granted the specified permission. This API uses a promise to return the result. + +> **NOTE** +> +> This API is deprecated since API version 9. You are advised to use [checkAccessToken](#checkaccesstoken9) instead. + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------- | ---- | ------------------------------------------ | +| tokenID | number | Yes | Token ID of the application. The value can be obtained from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | +| permissionName | string | Yes | Name of the permission to verify.| + +**Return value** + +| Type | Description | +| :------------ | :---------------------------------- | +| Promise<GrantStatus> | Promise used to return the permission grant state.| + +**Example** + +```js +import privacyManager from '@ohos.abilityAccessCtrl'; + +var AtManager = abilityAccessCtrl.createAtManager(); +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +let promise = AtManager.verifyAccessToken(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); promise.then(data => { console.log(`promise: data->${JSON.stringify(data)}`); }); @@ -289,7 +468,34 @@ Enumerates the permission grant states. **System capability**: SystemCapability.Security.AccessToken -| Name | Default Value | Description | -| ----------------------------- | ---------------------- | ----------------------- | -| PERMISSION_DENIED | -1 | Permission denied. | -| PERMISSION_GRANTED | 0 | Permission granted. | +| Name | Default Value| Description | +| ------------------ | ----- | ----------- | +| PERMISSION_DENIED | -1 | Permission denied.| +| PERMISSION_GRANTED | 0 | Permission granted.| + +### PermissionStateChangeType9+ + +Enumerates the operations that trigger permission grant state changes. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Default Value| Description | +| ----------------------- | ------ | ----------------- | +| PERMISSION_REVOKED_OPER | 0 | Operation to revoke the permission.| +| PERMISSION_GRANTED_OPER | 1 | Operation to grant the permission.| + +### PermissionStateChangeInfo9+ + +Defines the detailed permission grant state change information. + +**System API**: This is a system API. + + **System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Readable| Writable| Description | +| -------------- | ------------------------- | ---- | ---- | ------------------ | +| change | [PermissionStateChangeType](#permissionstatechangetype9) | Yes | No | Operation that triggers the permission grant state change. | +| tokenID | number | Yes | No | Token ID of the application whose permission grant state changes are subscribed.| +| permissionName | string | Yes | No | Name of the permission whose grant state is changed.| diff --git a/en/application-dev/reference/apis/js-apis-accessibility-config.md b/en/application-dev/reference/apis/js-apis-accessibility-config.md new file mode 100644 index 0000000000000000000000000000000000000000..71517bfb32ca3880637b565c85c02e53acbad8e6 --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-accessibility-config.md @@ -0,0 +1,364 @@ +# System Accessibility Configuration + +The **config** module allows you to configure system accessibility features, including accessibility extension, high-contrast text, mouse buttons, and captions. + +> **NOTE** +> +> The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. +> +> The APIs provided by this module are system APIs. + +## Modules to Import + +```typescript +import config from "@ohos.accessibility.config"; +``` + +## Attributes + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| highContrastText | [Config](#config)\| Yes| Yes| Whether to enable high-contrast text.| +| invertColor | [Config](#config)\| Yes| Yes| Whether to enable color inversion.| +| daltonizationColorFilter | [Config](#config)<[DaltonizationColorFilter](#daltonizationcolorfilter)>| Yes| Yes| 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.| +| brightnessDiscount | [Config](#config)\| Yes| Yes| Brightness discount. The value ranges from 0 to 1.0.| +| mouseKey | [Config](#config)\| Yes| Yes| Whether to enable the mouse button feature.| +| mouseAutoClick | [Config](#config)\| Yes| Yes| Interval for the automatic mouse clicks. The value ranges from 0 to 5000, in milliseconds.| +| shortkey | [Config](#config)\| Yes| Yes| Whether to enable the accessibility extension shortcut key.| +| shortkeyTarget | [Config](#config)\| Yes| Yes| Target application for the accessibility extension shortcut key. The value format is bundleName/abilityName.| +| captions | [Config](#config)\| Yes| Yes| Whether to enable captions.| +| captionsStyle | [Config](#config)\<[accessibility.CaptionsStyle](./js-apis-accessibility.md#captionsstyle8)>| Yes| Yes| Captions style.| + +## enableAbility + +enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>): Promise<void>; + +Enables an accessibility extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>) | Yes| Capability of the accessibility extension ability.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + +**Example** + + ```typescript + config.enableAbility("com.ohos.example/axExtension", ['retrieve']) + .then(() => { + console.info('enable succeed'); + }).catch((error) => { + console.error('enable failed'); + }); + ``` + +## enableAbility + +enableAbility(name: string, capability: Array<[accessibility.Capability](./js-apis-accessibility.md#capability)>, callback: AsyncCallback<void>): void; + +Enables an accessibility extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| capability | Array<[accessibility.Capability](./js-apis-accessibility.md#capability)> | Yes| Capability of the accessibility extension ability.| +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +**Example** + + ```typescript + config.enableAbility("com.ohos.example/axExtension", ['retrieve'], (err, data) => { + if (err) { + console.error('enable failed'); + return; + } + console.info('enable succeed'); + }) + ``` + +## disableAbility + +disableAbility(name: string): Promise<void>; + +Disables an accessibility extension ability. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + +**Example** + + ```typescript + config.disableAbility("com.ohos.example/axExtension") + .then(() => { + console.info('disable succeed'); + }).catch((error) => { + console.error('disable failed'); + }); + ``` + +## disableAbility + +disableAbility(name: string, callback: AsyncCallback<void>): void; + +Disables an accessibility extension ability. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| name | string | Yes| Name of the accessibility extension ability. The format is bundleName/abilityName.| +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +**Example** + + ```typescript + config.disableAbility("com.ohos.example/axExtension", (err, data) => { + if (err) { + console.error('disable failed'); + return; + } + console.info('disable succeed'); + }) + ``` + +## on('enableAbilityListsStateChanged') + +on(type: 'enableAbilityListsStateChanged', callback: Callback<void>): void; + +Adds a listener for changes in the list of enabled accessibility extension abilities. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | Yes| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating that the changes in the list of enabled accessibility extension abilities.| +| callback | Callback<void> | Yes| Callback invoked when the list of enabled accessibility extension abilities changes.| + +**Example** + + ```typescript + config.on('enableAbilityListsStateChanged',() => { + console.info('ax extension ability enable list changed'); + }); + ``` + +## off('enableAbilityListsStateChanged') + +off(type: 'enableAbilityListsStateChanged', callback?: Callback<void>): void; + +Cancels the listener for changes in the list of enabled accessibility extension abilities. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| type | string | No| Listening type. The value is fixed at **'enableAbilityListsStateChanged'**, indicating that the changes in the list of enabled accessibility extension abilities.| +| callback | Callback<void> | No| Callback invoked when the list of enabled accessibility extension abilities changes.| + +**Example** + + ```typescript + config.off('enableAbilityListsStateChanged'); + ``` + +## Config + +Implements configuration, acquisition, and listening for attributes. + +### set + +set(value: T): Promise<void>; + +Sets this attribute. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | T | Yes| Attribute value to set.| + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<void> | Promise used to return the execution result.| + +**Example** + + ```typescript + config.highContrastText.set(true) + .then(() => { + console.info('highContrastText set succeed'); + }).catch((error) => { + console.error('highContrastText set failed'); + }); + ``` + +### set + +set(value: T, callback: AsyncCallback<void>): void; + +Sets this attribute. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| value | T | Yes| Attribute value to set.| +| callback | AsyncCallback<void> | Yes| Callback used to return the execution result.| + +**Example** + + ```typescript + config.highContrastText.set(true, (err, data) => { + if (err) { + console.error('highContrastText set failed'); + return; + } + console.info('highContrastText set succeed'); + }) + ``` + +### get + +get(): Promise<T>; + +Obtains the value of this attribute. This API uses a promise to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Return value** + +| Type| Description| +| -------- | -------- | +| Promise<T> | Promise used to return the attribute value.| + +**Example** + + ```typescript + config.highContrastText.get() + .then((value) => { + console.info('highContrastText get succeed'); + }).catch((error) => { + console.error('highContrastText get failed'); + }); + ``` + +### get + +get(callback: AsyncCallback<T>): void; + +Obtains the value of this attribute. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | Yes| Callback used to return the attribute value.| + +**Example** + + ```typescript + config.highContrastText.get((err, data) => { + if (err) { + console.error('highContrastText get failed'); + return; + } + console.info('highContrastText get succeed'); + }) + ``` + +### on + +on(callback: Callback<T>): void; + +Adds a listener for attribute changes. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | Callback<T> | Yes| Callback invoked when the attribute changes.| + +**Example** + + ```typescript + config.highContrastText.on(() => { + console.info('highContrastText changed'); + }); + ``` + +### off + +off(callback?: Callback<T>): void; + +Cancels the listener for attribute changes. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| callback | Callback<T> | No| Callback invoked when the attribute changes.| + +**Example** + + ```typescript + config.highContrastText.off(); + ``` + +## DaltonizationColorFilter + +Enumerates the daltonization filters. + +**System capability**: SystemCapability.BarrierFree.Accessibility.Core + +| Name| Description| +| -------- | -------- | +| Normal | Filter for normal users.| +| Protanomaly | Filter for protanomaly.| +| Deuteranomaly | Filter for deuteranomaly.| +| Tritanomaly | Filter for tritanomaly.| diff --git a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md index c97515fa2bd988b91c4fd5c27a8e27ed285f141c..45024751e4460258a696e7f7e883e84fb93d73c2 100644 --- a/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md +++ b/en/application-dev/reference/apis/js-apis-application-MissionSnapshot.md @@ -14,19 +14,19 @@ The mission snapshot information can be obtained by using **getMissionSnapShot** ```js import ElementName from '@ohos.bundle'; import image from '@ohos.multimedia.image'; -import missionManager from '@ohos.application.missionManager' +import missionManager from '@ohos.application.missionManager'; - missionManager.getMissionInfos("", 10, (error, missions) => { - console.log("getMissionInfos is called, error.code = " + error.code); - console.log("size = " + missions.length); - console.log("missions = " + JSON.stringify(missions)); - var id = missions[0].missionId; +missionManager.getMissionInfos("", 10, (error, missions) => { + console.log("getMissionInfos is called, error.code = " + error.code); + console.log("size = " + missions.length); + console.log("missions = " + JSON.stringify(missions)); + var id = missions[0].missionId; - missionManager.getMissionSnapShot("", id, (error, snapshot) => { - console.log("getMissionSnapShot is called, error.code = " + error.code); - console.log("bundleName = " + snapshot.ability.bundleName); - }) + missionManager.getMissionSnapShot("", id, (error, snapshot) => { + console.log("getMissionSnapShot is called, error.code = " + error.code); + console.log("bundleName = " + snapshot.ability.bundleName); }) +}) ``` ## MissionSnapshot diff --git a/en/application-dev/reference/apis/js-apis-audio.md b/en/application-dev/reference/apis/js-apis-audio.md index 7fa4e76c7a448d1272d1a50b8da71e0303b27762..acd9ef20950cd35f4f25d0b63b5e33b4e4021e89 100644 --- a/en/application-dev/reference/apis/js-apis-audio.md +++ b/en/application-dev/reference/apis/js-apis-audio.md @@ -7,6 +7,7 @@ This module provides the following common audio-related functions: - [AudioManager](#audiomanager): audio management. - [AudioRenderer](#audiorenderer8): audio rendering, used to play Pulse Code Modulation (PCM) audio data. - [AudioCapturer](#audiocapturer8): audio capture, used to record PCM audio data. +- [TonePlayer](#toneplayer9): tone player, used to manage and play Dual Tone Multi Frequency (DTMF) tones, such as dial tones and ringback tones. > **NOTE** > @@ -55,65 +56,11 @@ Obtains an **AudioManager** instance. var audioManager = audio.getAudioManager(); ``` -## audio.getStreamManager9+ - -getStreamManager(callback: AsyncCallback\): void - -Obtains an **AudioStreamManager** instance. This API uses an asynchronous callback to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Core - -**Parameters** - -| Name | Type | Mandatory| Description | -| -------- | --------------------------------------------------------- | ---- | ---------------- | -| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | Yes | **AudioStreamManager** instance.| - -**Example** - -```js -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - let audioStreamManager = data; - } -}); -``` - -## audio.getStreamManager9+ - -getStreamManager(): Promise - -Obtains an **AudioStreamManager** instance. This API uses a promise to return the result. - -**System capability**: SystemCapability.Multimedia.Audio.Core - -**Return value** - -| Type | Description | -| ---------------------------------------------------- | ---------------- | -| Promise<[AudioStreamManager](#audiostreammanager9)> | **AudioStreamManager** instance.| - -**Example** - -```js -var audioStreamManager; -audio.getStreamManager().then((data) => { - audioStreamManager = data; - console.info('getStreamManager: Success!'); -}).catch((err) => { - console.error(`getStreamManager: ERROR : ${err}`); -}); - -``` - ## audio.createAudioRenderer8+ createAudioRenderer(options: AudioRendererOptions, callback: AsyncCallback\): void -Obtains an **AudioRenderer** instance. This API uses an asynchronous callback to return the result. +Creates an **AudioRenderer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer @@ -160,7 +107,7 @@ audio.createAudioRenderer(audioRendererOptions,(err, data) => { createAudioRenderer(options: AudioRendererOptions): Promise -Obtains an **AudioRenderer** instance. This API uses a promise to return the result. +Creates an **AudioRenderer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Renderer @@ -212,10 +159,12 @@ audio.createAudioRenderer(audioRendererOptions).then((data) => { createAudioCapturer(options: AudioCapturerOptions, callback: AsyncCallback): void -Obtains an **AudioCapturer** instance. This API uses an asynchronous callback to return the result. +Creates an **AudioCapturer** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.MICROPHONE + **Parameters** | Name | Type | Mandatory| Description | @@ -258,10 +207,12 @@ audio.createAudioCapturer(audioCapturerOptions, (err, data) => { createAudioCapturer(options: AudioCapturerOptions): Promise -Obtains an **AudioCapturer** instance. This API uses a promise to return the result. +Creates an **AudioCapturer** instance. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Capturer +**Required permissions**: ohos.permission.MICROPHONE + **Parameters** | Name | Type | Mandatory| Description | @@ -305,6 +256,78 @@ audio.createAudioCapturer(audioCapturerOptions).then((data) => { }); ``` +## audio.createTonePlayer9+ + +createTonePlayer(options: AudioRendererInfo, callback: AsyncCallback<TonePlayer>): void + +Creates a **TonePlayer** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ----------------------------------------------- | ---- | -------------- | +| options | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| +| callback | AsyncCallback<[TonePlayer](#toneplayer9)> | Yes | Callback used to return the **TonePlayer** instance.| + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; + +var audioRendererInfo = { + "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags": 0 +} +var tonePlayer; + +audio.createTonePlayer(audioRendererInfo, (err, data) => { + console.info(`callback call createTonePlayer: audioRendererInfo: ${audioRendererInfo}`); + if (err) { + console.error(`callback call createTonePlayer return error: ${err.message}`); + } else { + console.info(`callback call createTonePlayer return data: ${data}`); + tonePlayer = data; + } +}); +``` + +## audio.createTonePlayer9+ + +createTonePlayer(options: AudioRendererInfo): Promise<TonePlayer> + +Creates a **TonePlayer** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory| Description | +| :------ | :---------------------------------------------| :--- | :----------- | +| options | [AudioRendererInfo](#audiorendererinfo8) | Yes | Audio renderer information.| + +**Return value** + +| Type | Description | +| ----------------------------------------- | -------------------------------- | +| Promise<[TonePlayer](#toneplayer9)> | Promise used to return the **TonePlayer** instance. | + +**Example** + +```js +import audio from '@ohos.multimedia.audio'; +async function createTonePlayer(){ + var audioRendererInfo = { + "contentType": audio.ContentType.CONTENT_TYPE_MUSIC, + "streamUsage": audio.StreamUsage.STREAM_USAGE_MEDIA, + "rendererFlags": 0 + } + let tonePlayer = await audio.createTonePlayer(this.audioRendererInfo); +} +``` + ## AudioVolumeType Enumerates the audio stream types. @@ -338,13 +361,13 @@ Enumerates the audio device flags. | Name | Default Value | Description | | ------------------------------- | ------ | ------------------------------------------------- | -| NONE_DEVICES_FLAG9+ | 0 | No flag.
This is a system API and cannot be called by third-party applications. | +| NONE_DEVICES_FLAG9+ | 0 | No device.
This is a system API and cannot be called by third-party applications. | | OUTPUT_DEVICES_FLAG | 1 | Output device.| | INPUT_DEVICES_FLAG | 2 | Input device.| | ALL_DEVICES_FLAG | 3 | All devices.| | DISTRIBUTED_OUTPUT_DEVICES_FLAG9+ | 4 | Distributed output device.
This is a system API and cannot be called by third-party applications. | | DISTRIBUTED_INPUT_DEVICES_FLAG9+ | 8 | Distributed input device.
This is a system API and cannot be called by third-party applications. | -| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output devices.
This is a system API and cannot be called by third-party applications. | +| ALL_DISTRIBUTED_DEVICES_FLAG9+ | 12 | Distributed input and output device.
This is a system API and cannot be called by third-party applications. | ## DeviceRole @@ -479,12 +502,13 @@ Enumerates the audio stream usage. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | -| ---------------------------------- | ------ | ---------- | -| STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| -| STREAM_USAGE_MEDIA | 1 | Used for media. | -| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Used for voice communication.| -| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.| +| Name | Default Value| Description | +| ------------------------------------------| ------ | ---------- | +| STREAM_USAGE_UNKNOWN | 0 | Unknown usage.| +| STREAM_USAGE_MEDIA | 1 | Used for media. | +| STREAM_USAGE_VOICE_COMMUNICATION | 2 | Used for voice communication.| +| STREAM_USAGE_VOICE_ASSISTANT9+ | 3 | Used for voice assistant.| +| STREAM_USAGE_NOTIFICATION_RINGTONE | 6 | Used for notification.| ## FocusType9+ @@ -668,6 +692,8 @@ Describes the event received by the application when the volume is changed. Enumerates the types of connected devices. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Device | Name | Default Value| Description | @@ -689,7 +715,7 @@ Describes the volume group information. | groupId9+ | number | Yes | No | Group ID of the device.| | mappingId9+ | number | Yes | No | Group mapping ID.| | groupName9+ | number | Yes | No | Group name.| -| ConnectType9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| +| type9+ | [ConnectType](#connecttype9)| Yes | No | Type of the connected device.| ## VolumeGroupInfos9+ @@ -761,11 +787,12 @@ Enumerates the audio source types. **System capability**: SystemCapability.Multimedia.Audio.Core -| Name | Default Value| Description | -| :------------------------------ | :----- | :--------------------- | -| SOURCE_TYPE_INVALID | -1 | Invalid audio source. | -| SOURCE_TYPE_MIC | 0 | Mic source. | -| SOURCE_TYPE_VOICE_COMMUNICATION | 7 | Voice communication source.| +| Name | Default Value| Description | +| :------------------------------------------- | :----- | :--------------------- | +| SOURCE_TYPE_INVALID | -1 | Invalid audio source. | +| SOURCE_TYPE_MIC | 0 | Mic source. | +| SOURCE_TYPE_VOICE_RECOGNITION9+ | 1 | Voice recognition source. | +| SOURCE_TYPE_VOICE_COMMUNICATION | 7 | Voice communication source.| ## AudioScene8+ @@ -780,7 +807,6 @@ Enumerates the audio scenes. | AUDIO_SCENE_PHONE_CALL | 2 | Phone call audio scene.
This is a system API and cannot be called by third-party applications.| | AUDIO_SCENE_VOICE_CHAT | 3 | Voice chat audio scene. | - ## AudioManager Implements audio volume and audio device management. Before calling any API in **AudioManager**, you must use [getAudioManager](#audiogetaudiomanager) to create an **AudioManager** instance. @@ -801,7 +827,7 @@ Obtains an **AudioRoutingManager** instance. This API uses an asynchronous callb **Example** ```js -await audioManager.getRoutingManager((err, callback) => { +audioManager.getRoutingManager((err, callback) => { if (err) { console.error(`Result ERROR: ${err}`); } @@ -827,12 +853,15 @@ Obtains an **AudioRoutingManager** instance. This API uses a promise to return t **Example** ```js -await audioManager.getRoutingManager().then((value) => { - var routingManager = value; - console.info('getRoutingManager Promise SUCCESS.'); -}).catch((err) => { - console.error(`Result ERROR: ${err}`); -}); +var audioManager = audio.getAudioManager(); +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + var routingManager = value; + console.info('getRoutingManager Promise SUCCESS.'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); +} ``` ### setVolume @@ -1951,6 +1980,7 @@ Sets an audio scene. This API uses an asynchronous callback to return the result **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL, (err) => { if (err) { console.error(`Failed to set the audio scene mode.​ ${err}`); @@ -1985,6 +2015,7 @@ Sets an audio scene. This API uses a promise to return the result. **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.setAudioScene(audio.AudioScene.AUDIO_SCENE_PHONE_CALL).then(() => { console.info('Promise returned to indicate a successful setting of the audio scene mode.'); }).catch ((err) => { @@ -2009,6 +2040,7 @@ Obtains the audio scene. This API uses an asynchronous callback to return the re **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getAudioScene((err, value) => { if (err) { console.error(`Failed to obtain the audio scene mode.​ ${err}`); @@ -2036,6 +2068,7 @@ Obtains the audio scene. This API uses a promise to return the result. **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getAudioScene().then((value) => { console.info(`Promise returned to indicate that the audio scene mode is obtained ${value}.`); }).catch ((err) => { @@ -2062,6 +2095,7 @@ Obtains the volume groups. This API uses an asynchronous callback to return the **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID, (err, value) => { if (err) { console.error(`Failed to obtain the volume group infos list. ${err}`); @@ -2091,7 +2125,7 @@ Obtains the volume groups. This API uses a promise to return the result. | Type | Description | | ------------------- | ----------------------------- | -| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information list.| +| Promise<[VolumeGroupInfos](#volumegroupinfos9)> | Volume group information array.| **Example** @@ -2116,12 +2150,14 @@ Obtains the audio group manager. This API uses an asynchronous callback to retur | Name | Type | Mandatory| Description | | ---------- | ------------------------------------------------------------ | ---- | -------------------- | -| networkId | string | Yes | Network ID of the device. | +| groupId | number | Yes | Volume group ID. | | callback | AsyncCallback< [AudioGroupManager](#audiogroupmanager9) > | Yes | Callback used to return the audio group manager.| **Example** ```js +var audioManager = audio.getAudioManager(); +var audioGroupManager; async function getGroupManager(){ let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); if (value.length > 0) { @@ -2151,8 +2187,8 @@ Obtains the audio group manager. This API uses a promise to return the result. **Parameters** | Name | Type | Mandatory| Description | -| ---------- | ---------------------------------------- | ---- | -------------- -- | -| networkId | string | Yes | Network ID of the device. | +| ---------- | ---------------------------------------- | ---- | ---------------- | +| groupId | number | Yes | Volume group ID. | **Return value** @@ -2163,15 +2199,74 @@ Obtains the audio group manager. This API uses a promise to return the result. **Example** ```js +var audioManager = audio.getAudioManager(); async function getGroupManager(){ let value = await audioManager.getVolumeGroups(audio.LOCAL_NETWORK_ID); if (value.length > 0) { let groupid = value[0].groupId; - let audioGroupManager = await audioManager.getGroupManager(audio.LOCAL_NETWORK_ID) + let audioGroupManager = await audioManager.getGroupManager(groupid) console.info('Callback invoked to indicate that the volume group infos list is obtained.'); } } ``` + +### getStreamManager9+ + +getStreamManager(callback: AsyncCallback\): void + +Obtains an **AudioStreamManager** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Core + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------------------------------------- | ---- | ---------------- | +| callback | AsyncCallback<[AudioStreamManager](#audiostreammanager9)> | Yes | **AudioStreamManager** instance.| + +**Example** + +```js +var audioManager = audio.getAudioManager(); +let audioStreamManager; +audioManager.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); +``` + +### getStreamManager9+ + +getStreamManager(): Promise + +Obtains an **AudioStreamManager** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Core + +**Return value** + +| Type | Description | +| ---------------------------------------------------- | ---------------- | +| Promise<[AudioStreamManager](#audiostreammanager9)> | **AudioStreamManager** instance.| + +**Example** + +```js +var audioManager = audio.getAudioManager(); +var audioStreamManager; +audioManager.getStreamManager().then((data) => { + audioStreamManager = data; + console.info('getStreamManager: Success!'); +}).catch((err) => { + console.error(`getStreamManager: ERROR : ${err}`); +}); + +``` + ### requestIndependentInterrupt9+ requestIndependentInterrupt(focusType: FocusType, callback: AsyncCallback\): void @@ -2203,7 +2298,7 @@ async function requestIndependentInterrupt(){ ``` ### requestIndependentInterrupt9+ -requestIndependentInterrupt(focusType: FocusType: Promise +requestIndependentInterrupt(focusType: FocusType): Promise Requests independent interruption and obtains an interruption session ID. This API uses a promise to return the result. @@ -2265,7 +2360,7 @@ async function abandonIndependentInterrupt(){ ``` ### abandonIndependentInterrupt9+ -abandonIndependentInterrupt(focusType: FocusType]: Promise +abandonIndependentInterrupt(focusType: FocusType): Promise Abandons independent interruption. This API uses a promise to return the result. @@ -2313,6 +2408,8 @@ Sets the volume for a stream. This API uses an asynchronous callback to return t This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2345,6 +2442,8 @@ Sets the volume for a stream. This API uses a promise to return the result. This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2374,6 +2473,8 @@ getVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>): v Obtains the volume of a stream. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2401,6 +2502,8 @@ getVolume(volumeType: AudioVolumeType): Promise<number> Obtains the volume of a stream. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2429,6 +2532,8 @@ getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) Obtains the minimum volume allowed for a stream. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2456,6 +2561,8 @@ getMinVolume(volumeType: AudioVolumeType): Promise<number> Obtains the minimum volume allowed for a stream. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2484,6 +2591,8 @@ getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback<number>) Obtains the maximum volume allowed for a stream. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2511,6 +2620,8 @@ getMaxVolume(volumeType: AudioVolumeType): Promise<number> Obtains the maximum volume allowed for a stream. This API uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2543,6 +2654,8 @@ Mutes or unmutes a stream. This API uses an asynchronous callback to return the This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2575,6 +2688,8 @@ Mutes or unmutes a stream. This API uses a promise to return the result. This permission is required only for muting or unmuting the ringer when **volumeType** is set to **AudioVolumeType.RINGTONE**. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2604,6 +2719,8 @@ isMute(volumeType: AudioVolumeType, callback: AsyncCallback<boolean>): voi Checks whether a stream is muted. This API uses an asynchronous callback to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2631,6 +2748,8 @@ isMute(volumeType: AudioVolumeType): Promise<boolean> Checks whether a stream is muted. This method uses a promise to return the result. +**System API**: This is a system API. + **System capability**: SystemCapability.Multimedia.Audio.Volume **Parameters** @@ -2655,7 +2774,7 @@ audioGroupManager.isMute(audio.AudioVolumeType.MEDIA).then((value) => { ## AudioStreamManager9+ -Implements audio stream management. Before calling any API of **AudioStreamManager**, you must use **[getStreamManager](#audiogetstreammanager9)** to obtain an **AudioStreamManager** instance. +Implements audio stream management. Before calling any API in **AudioStreamManager**, you must use [getStreamManager](#getstreammanager9) to obtain an **AudioStreamManager** instance. ### getCurrentAudioRendererInfoArray9+ @@ -2674,16 +2793,6 @@ Obtains the information about the current audio renderers. This API uses an asyn **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.getCurrentAudioRendererInfoArray(async (err, AudioRendererChangeInfoArray) => { console.info('getCurrentAudioRendererInfoArray **** Get Callback Called ****'); if (err) { @@ -2731,42 +2840,34 @@ Obtains the information about the current audio renderers. This API uses a promi **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { - console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); - if (AudioRendererChangeInfoArray != null) { - for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { - let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; - console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); - console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); - console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); - console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); - console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); - console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); - for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); +async function getCurrentAudioRendererInfoArray(){ + await audioStreamManager.getCurrentAudioRendererInfoArray().then( function (AudioRendererChangeInfoArray) { + console.info(`getCurrentAudioRendererInfoArray ######### Get Promise is called ##########`); + if (AudioRendererChangeInfoArray != null) { + for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { + let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; + console.info(`StreamId for ${i} is: ${AudioRendererChangeInfo.streamId}`); + console.info(`ClientUid for ${i} is: ${AudioRendererChangeInfo.clientUid}`); + console.info(`Content ${i} is: ${AudioRendererChangeInfo.rendererInfo.content}`); + console.info(`Stream ${i} is: ${AudioRendererChangeInfo.rendererInfo.usage}`); + console.info(`Flag ${i} is: ${AudioRendererChangeInfo.rendererInfo.rendererFlags}`); + console.info(`State for ${i} is: ${AudioRendererChangeInfo.rendererState}`); + for (let j = 0;j < AudioRendererChangeInfo.deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCount ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioRendererChangeInfo.deviceDescriptors[j].channelMasks}`); + } } } - } -}).catch((err) => { - console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); -}); + }).catch((err) => { + console.error(`getCurrentAudioRendererInfoArray :ERROR: ${err}`); + }); +} ``` ### getCurrentAudioCapturerInfoArray9+ @@ -2786,16 +2887,6 @@ Obtains the information about the current audio capturers. This API uses an asyn **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.getCurrentAudioCapturerInfoArray(async (err, AudioCapturerChangeInfoArray) => { console.info('getCurrentAudioCapturerInfoArray **** Get Callback Called ****'); if (err) { @@ -2841,40 +2932,32 @@ Obtains the information about the current audio capturers. This API uses a promi **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - -await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { - console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); - if (AudioCapturerChangeInfoArray != null) { - for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); - console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); - console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); - console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); - console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); - for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { - console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); - console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); - console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); - console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); - console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); - console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); - console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); - console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); - } +async function getCurrentAudioCapturerInfoArray(){ + await audioStreamManager.getCurrentAudioCapturerInfoArray().then( function (AudioCapturerChangeInfoArray) { + console.info('getCurrentAudioCapturerInfoArray **** Get Promise Called ****'); + if (AudioCapturerChangeInfoArray != null) { + for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { + console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); + console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); + console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); + console.info(`Flag ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.capturerFlags}`); + console.info(`State for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerState}`); + for (let j = 0; j < AudioCapturerChangeInfoArray[i].deviceDescriptors.length; j++) { + console.info(`Id: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].id}`); + console.info(`Type: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceType}`); + console.info(`Role: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].deviceRole}`); + console.info(`Name: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].name}`); + console.info(`Address: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].address}`); + console.info(`SampleRates: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].sampleRates[0]}`); + console.info(`ChannelCounts ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelCounts[0]}`); + console.info(`ChannelMask: ${i} : ${AudioCapturerChangeInfoArray[i].deviceDescriptors[j].channelMasks}`); + } + } } - } -}).catch((err) => { - console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); -}); + }).catch((err) => { + console.error(`getCurrentAudioCapturerInfoArray :ERROR: ${err}`); + }); +} ``` ### on('audioRendererChange')9+ @@ -2895,16 +2978,6 @@ Subscribes to audio renderer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { let AudioRendererChangeInfo = AudioRendererChangeInfoArray[i]; @@ -2946,16 +3019,6 @@ Unsubscribes from audio renderer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.off('audioRendererChange'); console.info('######### RendererChange Off is called #########'); ``` @@ -2978,19 +3041,9 @@ Subscribes to audio capturer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { - console.info(`## CapChange on is called for element ${i} ##'); + console.info(`## CapChange on is called for element ${i} ##`); console.info(`StreamId for ${i} is: ${AudioCapturerChangeInfoArray[i].streamId}`); console.info(`ClientUid for ${i} is: ${AudioCapturerChangeInfoArray[i].clientUid}`); console.info(`Source for ${i} is: ${AudioCapturerChangeInfoArray[i].capturerInfo.source}`); @@ -3028,23 +3081,13 @@ Unsubscribes from audio capturer change events. **Example** ```js -let audioStreamManager; -audio.getStreamManager((err, data) => { - if (err) { - console.error(`getStreamManager : Error: ${err}`); - } else { - console.info('getStreamManager : Success : SUCCESS'); - audioStreamManager = data; - } -}); - audioStreamManager.off('audioCapturerChange'); console.info('######### CapturerChange Off is called #########'); ``` ## AudioRoutingManager9+ -Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to create an **AudioRoutingManager** instance. +Implements audio routing management. Before calling any API in **AudioRoutingManager**, you must use [getRoutingManager](#getroutingmanager9) to obtain an **AudioRoutingManager** instance. ### getDevices9+ @@ -3064,11 +3107,11 @@ Obtains the audio devices with a specific flag. This API uses an asynchronous ca **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } - else { + } else { AudioRoutingManager.getDevices(audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (err, value) => { if (err) { console.error(`Failed to obtain the device list. ${err}`); @@ -3103,6 +3146,7 @@ Obtains the audio devices with a specific flag. This API uses a promise to retur **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); @@ -3134,6 +3178,7 @@ Subscribes to device change events. When a device is connected or disconnected, **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); @@ -3162,29 +3207,113 @@ Unsubscribes from device change events. | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ------------------------------------------ | | type | string | Yes | Event type. The value **deviceChange** means the device change event, which is triggered when a device connection status change is detected.| -| deviceFlag | [DeviceFlag](#deviceflag) | Yes | Audio device flag. | | callback | Callback<[DeviceChangeAction](#devicechangeaction)> | No | Callback used to return the device update details. | **Example** ```js +var audioManager = audio.getAudioManager(); audioManager.getRoutingManager((err,AudioRoutingManager)=>{ if (err) { console.error(`AudioFrameworkTest:Callback:failed to get RoutingManager ${err}`); - } - else { - AudioRoutingManager.off('deviceChange', audio.DeviceFlag.OUTPUT_DEVICES_FLAG, (deviceChanged) => { + } else { + AudioRoutingManager.off('deviceChange', (deviceChanged) => { console.info('Should be no callback.'); }); } }); ``` +### selectInputDevice9+ + +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void + +Selects an audio input device. Currently, only one input device can be selected. This API uses an asynchronous callback to return the result. + +**System API**: This is a system API. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| + +**Example** +```js +var audioManager = audio.getAudioManager(); +let inputAudioDeviceDescriptor = [{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select input devices result callback: SUCCESS'); } + }); + }); +} +``` + +### selectInputDevice9+ + +selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> + +**System API**: This is a system API. + +Selects an audio input device. Currently, only one input device can be selected. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Device + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------------------------- | ------------------------------------------------------------ | ---- | ------------------------- | +| inputAudioDevices | [AudioDeviceDescriptors](#audiodevicedescriptors) | Yes | Input device. | + +**Return value** + +| Type | Description | +| --------------------- | --------------------------- | +| Promise<void> | Promise used to return the result.| + +**Example** + +```js +var audioManager = audio.getAudioManager(); +let inputAudioDeviceDescriptor =[{ + "deviceRole":audio.DeviceRole.INPUT_DEVICE, + "networkId":audio.LOCAL_NETWORK_ID, + "interruptGroupId":1, + "volumeGroupId":1 }]; +var audioRoutingManager; + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectInputDevice(inputAudioDeviceDescriptor).then(() => { + console.info('Select input devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); + }); +} +``` + ### selectOutputDevice9+ selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback<void>): void -Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. **System API**: This is a system API. @@ -3199,21 +3328,25 @@ Selects an audio output device. Currently, only one output device can be selecte **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioDeviceDescriptor = [{ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, "networkId":audio.LOCAL_NETWORK_ID, "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices result callback: SUCCESS'); } + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices result callback: SUCCESS'); } + }); }); -}); +} ``` ### selectOutputDevice9+ @@ -3222,7 +3355,7 @@ selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise<void& **System API**: This is a system API. -Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. +Selects an audio output device. Currently, only one output device can be selected. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Device @@ -3241,20 +3374,24 @@ Selects an audio output device. Currently, only one output device can be selecte **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioDeviceDescriptor =[{ "deviceRole":audio.DeviceRole.OUTPUT_DEVICE, "networkId":audio.LOCAL_NETWORK_ID, "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDevice(outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }); }); -}); +} ``` ### selectOutputDeviceByFilter9+ @@ -3263,7 +3400,7 @@ selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: Audi **System API**: This is a system API. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Multimedia.Audio.Device @@ -3277,6 +3414,7 @@ Selects an audio output device based on the filter criteria. Currently, only one **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioRendererFilter = { "uid":20010041, "rendererInfo": { @@ -3290,15 +3428,18 @@ let outputAudioDeviceDescriptor = [{ "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { - if (err) { - console.error(`Result ERROR: ${err}`); - } else { - console.info('Select output devices by filter result callback: SUCCESS'); } + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor, (err) => { + if (err) { + console.error(`Result ERROR: ${err}`); + } else { + console.info('Select output devices by filter result callback: SUCCESS'); } + }); }); -}); +} ``` ### selectOutputDeviceByFilter9+ @@ -3307,7 +3448,7 @@ selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: Audi **System API**: This is a system API. -Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. +Selects an audio output device based on the filter criteria. Currently, only one output device can be selected. This API uses a promise to return the result. **System capability**: SystemCapability.Multimedia.Audio.Device @@ -3327,6 +3468,7 @@ Selects an audio output device based on the filter criteria. Currently, only one **Example** ```js +var audioManager = audio.getAudioManager(); let outputAudioRendererFilter = { "uid":20010041, "rendererInfo": { @@ -3340,14 +3482,17 @@ let outputAudioDeviceDescriptor = [{ "interruptGroupId":1, "volumeGroupId":1 }]; var audioRoutingManager; -await audioManager.getRoutingManager().then((value) => { - audioRoutingManager = value; - audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { - console.info('Select output devices by filter result promise: SUCCESS'); - }).catch((err) => { - console.error(`Result ERROR: ${err}`); - }) -}); + +async function getRoutingManager(){ + await audioManager.getRoutingManager().then((value) => { + audioRoutingManager = value; + audioRoutingManager.selectOutputDeviceByFilter(outputAudioRendererFilter, outputAudioDeviceDescriptor).then(() => { + console.info('Select output devices by filter result promise: SUCCESS'); + }).catch((err) => { + console.error(`Result ERROR: ${err}`); + }) + }); +} ``` ## AudioRendererChangeInfo9+ @@ -3356,12 +3501,12 @@ Describes the audio renderer change event. **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable| Writable| Description | -| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API and cannot be called by third-party applications.| -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | -| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications.| +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio renderer client.
This is a system API and cannot be called by third-party applications. | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | Yes | No | Audio renderer information. | +| rendererState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. | ## AudioRendererChangeInfoArray9+ @@ -3375,26 +3520,19 @@ Describes the **AudioRenderChangeInfo** array, which is read-only. import audio from '@ohos.multimedia.audio'; var audioStreamManager; -var audioStreamManagerCB; var resultFlag = false; - -await audioManager.getStreamManager().then(async function (data) { - audioStreamManager = data; - console.info('Get AudioStream Manager : Success'); -}).catch((err) => { - console.error(`Get AudioStream Manager : ERROR : ${err}`); -}); +var audioManager = audio.getAudioManager(); audioManager.getStreamManager((err, data) => { if (err) { console.error(`Get AudioStream Manager : ERROR : ${err}`); } else { - audioStreamManagerCB = data; + audioStreamManager = data; console.info('Get AudioStream Manager : Success'); } }); -audioStreamManagerCB.on('audioRendererChange', (AudioRendererChangeInfoArray) => { +audioStreamManager.on('audioRendererChange', (AudioRendererChangeInfoArray) => { for (let i = 0; i < AudioRendererChangeInfoArray.length; i++) { console.info(`## RendererChange on is called for ${i} ##`); console.info(`StreamId for ${i} is: ${AudioRendererChangeInfoArray[i].streamId}`); @@ -3428,12 +3566,12 @@ Describes the audio capturer change event. **System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Readable| Writable| Description | -| -------------------| ----------------------------------------- | ---- | ---- | ---------------------------- | -| streamId | number | Yes | No | Unique ID of an audio stream. | -| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API and cannot be called by third-party applications.| -| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | -| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications.| +| Name | Type | Readable | Writable | Description | +| ------------- | ---------------------------------------- | -------- | -------- | ------------------------------------------------------------ | +| streamId | number | Yes | No | Unique ID of an audio stream. | +| clientUid | number | Yes | No | UID of the audio capturer client.
This is a system API and cannot be called by third-party applications. | +| capturerInfo | [AudioCapturerInfo](#audiocapturerinfo8) | Yes | No | Audio capturer information. | +| capturerState | [AudioState](#audiostate) | Yes | No | Audio state.
This is a system API and cannot be called by third-party applications. | ## AudioCapturerChangeInfoArray9+ @@ -3447,6 +3585,16 @@ Describes the **AudioCapturerChangeInfo** array, which is read-only. import audio from '@ohos.multimedia.audio'; const audioManager = audio.getAudioManager(); +let audioStreamManager; +audioManager.getStreamManager((err, data) => { + if (err) { + console.error(`getStreamManager : Error: ${err}`); + } else { + console.info('getStreamManager : Success : SUCCESS'); + audioStreamManager = data; + } +}); + var resultFlag = false; audioStreamManager.on('audioCapturerChange', (AudioCapturerChangeInfoArray) => { for (let i = 0; i < AudioCapturerChangeInfoArray.length; i++) { @@ -3481,19 +3629,19 @@ Describes an audio device. **System capability**: SystemCapability.Multimedia.Audio.Device -| Name | Type | Readable| Writable| Description | -| ----------------------------- | -------------------------- | ---- | ---- | ---------- | -| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role.| -| deviceType | [DeviceType](#devicetype) | Yes | No | Device type.| -| id9+ | number | Yes | No | Device ID. | -| name9+ | string | Yes | No | Device name.| -| address9+ | string | Yes | No | Device address.| -| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates.| -| channelCounts9+ | Array<number> | Yes | No | Number of channels supported.| -| channelMasks9+ | Array<number> | Yes | No | Supported channel masks.| -| networkId9+ | string | Yes | No | ID of the device network.
This is a system API and cannot be called by third-party applications.| -| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API and cannot be called by third-party applications.| -| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API and cannot be called by third-party applications.| +| Name | Type | Readable | Writable | Description | +| ----------------------------- | ------------------------- | -------- | -------- | ------------------------------------------------------------ | +| deviceRole | [DeviceRole](#devicerole) | Yes | No | Device role. | +| deviceType | [DeviceType](#devicetype) | Yes | No | Device type. | +| id9+ | number | Yes | No | Device ID. | +| name9+ | string | Yes | No | Device name. | +| address9+ | string | Yes | No | Device address. | +| sampleRates9+ | Array<number> | Yes | No | Supported sampling rates. | +| channelCounts9+ | Array<number> | Yes | No | Number of channels supported. | +| channelMasks9+ | Array<number> | Yes | No | Supported channel masks. | +| networkId9+ | string | Yes | No | ID of the device network.
This is a system API and cannot be called by third-party applications. | +| interruptGroupId9+ | number | Yes | No | ID of the interruption group to which the device belongs.
This is a system API and cannot be called by third-party applications. | +| volumeGroupId9+ | number | Yes | No | ID of the volume group to which the device belongs.
This is a system API and cannot be called by third-party applications. | ## AudioDeviceDescriptors @@ -3529,13 +3677,11 @@ Implements filter criteria. Before calling **selectOutputDeviceByFilter**, you m **System API**: This is a system API. -**System capability**: SystemCapability.Multimedia.Audio.Device - -| Name | Type | Mandatory | Description | -| -------------| ---------------------------------------- | ---- | -------------- | -| uid | number | Yes | Application ID.
System capability: SystemCapability.Multimedia.Audio.Core| -| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
System capability: SystemCapability.Multimedia.Audio.Renderer| -| rendererId | number | No | Unique ID of an audio stream.
System capability: SystemCapability.Multimedia.Audio.Renderer| +| Name | Type | Mandatory | Description | +| ------------ | ---------------------------------------- | --------- | ------------------------------------------------------------ | +| uid | number | Yes | Application ID.
**System capability**: SystemCapability.Multimedia.Audio.Core | +| rendererInfo | [AudioRendererInfo](#audiorendererinfo8) | No | Audio renderer information.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | +| rendererId | number | No | Unique ID of an audio stream.
**System capability**: SystemCapability.Multimedia.Audio.Renderer | **Example** @@ -3557,9 +3703,9 @@ Provides APIs for audio rendering. Before calling any API in **AudioRenderer**, **System capability**: SystemCapability.Multimedia.Audio.Renderer -| Name | Type | Readable| Writable| Description | -| ----- | -------------------------- | ---- | ---- | ------------------ | -| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state.| +| Name | Type | Readable | Writable | Description | +| ------------------ | -------------------------- | -------- | -------- | --------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio renderer state. | **Example** @@ -3577,9 +3723,9 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------------------------------------- | :--- | :--------------------- | -| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information.| +| Name | Type | Mandatory | Description | +| :------- | :------------------------------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback<[AudioRendererInfo](#audiorendererinfo8)\> | Yes | Callback used to return the renderer information. | **Example** @@ -3602,9 +3748,9 @@ Obtains the renderer information of this **AudioRenderer** instance. This API us **Return value** -| Type | Description | -| -------------------------------------------------- | ------------------------------- | -| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information.| +| Type | Description | +| -------------------------------------------------- | ------------------------------------------------ | +| Promise<[AudioRendererInfo](#audiorendererinfo8)\> | Promise used to return the renderer information. | **Example** @@ -3629,9 +3775,9 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------------------------- | :--- | :------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** @@ -3655,9 +3801,9 @@ Obtains the stream information of this **AudioRenderer** instance. This API uses **Return value** -| Type | Description | -| :--------------------------------------------- | :--------------------- | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** @@ -3671,6 +3817,7 @@ audioRenderer.getStreamInfo().then((streamInfo) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### start8+ @@ -3683,9 +3830,9 @@ Starts the renderer. This API uses an asynchronous callback to return the result **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -3697,6 +3844,7 @@ audioRenderer.start((err) => { console.info('Renderer start success.'); } }); + ``` ### start8+ @@ -3709,9 +3857,9 @@ Starts the renderer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3721,6 +3869,7 @@ audioRenderer.start().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### pause8+ @@ -3733,9 +3882,9 @@ Pauses rendering. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -3747,6 +3896,7 @@ audioRenderer.pause((err) => { console.info('Renderer paused.'); } }); + ``` ### pause8+ @@ -3759,9 +3909,9 @@ Pauses rendering. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3771,6 +3921,7 @@ audioRenderer.pause().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### drain8+ @@ -3783,9 +3934,9 @@ Drains the playback buffer. This API uses an asynchronous callback to return the **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -3797,6 +3948,7 @@ audioRenderer.drain((err) => { console.info('Renderer drained.'); } }); + ``` ### drain8+ @@ -3809,9 +3961,9 @@ Drains the playback buffer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3821,6 +3973,7 @@ audioRenderer.drain().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### stop8+ @@ -3833,9 +3986,9 @@ Stops rendering. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -3847,6 +4000,7 @@ audioRenderer.stop((err) => { console.info('Renderer stopped.'); } }); + ``` ### stop8+ @@ -3859,9 +4013,9 @@ Stops rendering. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3871,6 +4025,7 @@ audioRenderer.stop().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### release8+ @@ -3883,9 +4038,9 @@ Releases the renderer. This API uses an asynchronous callback to return the resu **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------- | --------- | ----------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -3897,6 +4052,7 @@ audioRenderer.release((err) => { console.info('Renderer released.'); } }); + ``` ### release8+ @@ -3909,9 +4065,9 @@ Releases the renderer. This API uses a promise to return the result. **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -3921,6 +4077,7 @@ audioRenderer.release().then(() => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### write8+ @@ -3933,52 +4090,27 @@ Writes the buffer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | --------------------------------------------------- | -| buffer | ArrayBuffer | Yes | Buffer to be written. | -| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ------------------------------------------------------------ | +| buffer | ArrayBuffer | Yes | Buffer to be written. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; -import featureAbility from '@ohos.ability.featureAbility' - -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_2, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION - rendererFlags: 0 -} - -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -var audioRenderer; -audio.createAudioRenderer(audioRendererOptions).then((data)=> { - audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); - }); var bufferSize; audioRenderer.getBufferSize().then((data)=> { console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); bufferSize = data; }).catch((err) => { - console.error.(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); + console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); console.info(`Buffer size: ${bufferSize}`); var context = featureAbility.getContext(); -var path = await context.getCacheDir(); +var path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} var filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); @@ -3990,6 +4122,7 @@ audioRenderer.write(buf, (err, writtenbytes) => { console.info(`Actual written bytes: ${writtenbytes}`); } }); + ``` ### write8+ @@ -4002,41 +4135,13 @@ Writes the buffer. This API uses a promise to return the result. **Return value** -| Type | Description | +| Type | Description | | ---------------- | ------------------------------------------------------------ | -| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned.| +| Promise\ | Promise used to return the result. If the operation is successful, the number of bytes written is returned; otherwise, an error code is returned. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; -import featureAbility from '@ohos.ability.featureAbility' - -var audioStreamInfo = { - samplingRate:audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels:audio.AudioChannel.CHANNEL_2, - sampleFormat:audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType:audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 0 -} - -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -var audioRenderer; -audio.createAudioRenderer(audioRendererOptions).then((data) => { - audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); - }).catch((err) => { - console.error(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); - }); var bufferSize; audioRenderer.getBufferSize().then((data) => { console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); @@ -4046,8 +4151,11 @@ audioRenderer.getBufferSize().then((data) => { }); console.info(`BufferSize: ${bufferSize}`); var context = featureAbility.getContext(); -var path = await context.getCacheDir(); -var filePath = 'data/StarWars10s-2C-48000-4SW.wav'; +var path; +async function getCacheDir(){ + path = await context.getCacheDir(); +} +var filePath = path + '/StarWars10s-2C-48000-4SW.wav'; let ss = fileio.createStreamSync(filePath, 'r'); let buf = new ArrayBuffer(bufferSize); ss.readSync(buf); @@ -4060,6 +4168,7 @@ audioRenderer.write(buf).then((writtenbytes) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### getAudioTime8+ @@ -4072,9 +4181,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | ---------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the timestamp.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | -------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the timestamp. | **Example** @@ -4082,6 +4191,7 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioRenderer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); + ``` ### getAudioTime8+ @@ -4094,9 +4204,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Return value** -| Type | Description | -| ---------------- | ----------------------- | -| Promise\ | Promise used to return the timestamp.| +| Type | Description | +| ---------------- | ------------------------------------- | +| Promise\ | Promise used to return the timestamp. | **Example** @@ -4106,6 +4216,7 @@ audioRenderer.getAudioTime().then((timestamp) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### getBufferSize8+ @@ -4118,9 +4229,9 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------- | ---- | -------------------- | -| callback | AsyncCallback\ | Yes | Callback used to return the buffer size.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | --------- | ---------------------------------------- | +| callback | AsyncCallback\ | Yes | Callback used to return the buffer size. | **Example** @@ -4130,6 +4241,7 @@ var bufferSize = audioRenderer.getBufferSize(async(err, bufferSize) => { console.error('getBufferSize error'); } }); + ``` ### getBufferSize8+ @@ -4142,40 +4254,13 @@ Obtains a reasonable minimum buffer size in bytes for rendering. This API uses a **Return value** -| Type | Description | -| ---------------- | --------------------------- | -| Promise\ | Promise used to return the buffer size.| +| Type | Description | +| ---------------- | --------------------------------------- | +| Promise\ | Promise used to return the buffer size. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; - -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_2, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S32LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 0 -} - -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -var audioRenderer; -audio.createAudioRenderer(audioRendererOptions).then((data) => { - audioRenderer = data; - console.info('AudioFrameworkRenderLog: AudioRenderer Created: SUCCESS'); - }).catch((err) => { - console.info(`AudioFrameworkRenderLog: AudioRenderer Created: ERROR: ${err}`); - }); var bufferSize; audioRenderer.getBufferSize().then((data) => { console.info(`AudioFrameworkRenderLog: getBufferSize: SUCCESS ${data}`); @@ -4183,6 +4268,7 @@ audioRenderer.getBufferSize().then((data) => { }).catch((err) => { console.error(`AudioFrameworkRenderLog: getBufferSize: ERROR: ${err}`); }); + ``` ### setRenderRate8+ @@ -4195,10 +4281,10 @@ Sets the render rate. This API uses an asynchronous callback to return the resul **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ---------------------------------------- | ---- | ------------------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | -| callback | AsyncCallback\ | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | --------- | ----------------------------------- | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** @@ -4210,6 +4296,7 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL, (err) => console.info('Callback invoked to indicate a successful render rate setting.'); } }); + ``` ### setRenderRate8+ @@ -4222,15 +4309,15 @@ Sets the render rate. This API uses a promise to return the result. **Parameters** -| Name| Type | Mandatory| Description | -| ------ | ---------------------------------------- | ---- | ------------ | -| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate.| +| Name | Type | Mandatory | Description | +| ---- | ---------------------------------------- | --------- | ------------------ | +| rate | [AudioRendererRate](#audiorendererrate8) | Yes | Audio render rate. | **Return value** -| Type | Description | -| -------------- | ------------------------- | -| Promise\ | Promise used to return the result.| +| Type | Description | +| -------------- | ---------------------------------- | +| Promise\ | Promise used to return the result. | **Example** @@ -4240,6 +4327,7 @@ audioRenderer.setRenderRate(audio.AudioRendererRate.RENDER_RATE_NORMAL).then(() }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` ### getRenderRate8+ @@ -4252,9 +4340,9 @@ Obtains the current render rate. This API uses an asynchronous callback to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------------------------- | ---- | ------------------ | -| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate.| +| Name | Type | Mandatory | Description | +| -------- | ------------------------------------------------------- | --------- | ---------------------------------------------- | +| callback | AsyncCallback<[AudioRendererRate](#audiorendererrate8)> | Yes | Callback used to return the audio render rate. | **Example** @@ -4262,6 +4350,7 @@ Obtains the current render rate. This API uses an asynchronous callback to retur audioRenderer.getRenderRate((err, renderrate) => { console.info(`getRenderRate: ${renderrate}`); }); + ``` ### getRenderRate8+ @@ -4274,9 +4363,9 @@ Obtains the current render rate. This API uses a promise to return the result. **Return value** -| Type | Description | -| ------------------------------------------------- | ------------------------- | -| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate.| +| Type | Description | +| ------------------------------------------------- | --------------------------------------------- | +| Promise<[AudioRendererRate](#audiorendererrate8)> | Promise used to return the audio render rate. | **Example** @@ -4286,7 +4375,9 @@ audioRenderer.getRenderRate().then((renderRate) => { }).catch((err) => { console.error(`ERROR: ${err}`); }); + ``` + ### setInterruptMode9+ setInterruptMode(mode: InterruptMode): Promise<void> @@ -4297,42 +4388,28 @@ Sets the audio interruption mode for the application. This API uses a promise to **Parameters** -| Name | Type | Mandatory | Description | -| ---------- | ---------------------------------- | ------ | ---------- | -| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| Name | Type | Mandatory | Description | +| ---- | -------------------------------- | --------- | ------------------------ | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | **Return value** -| Type | Description | -| ------------------- | ----------------------------- | -| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned.| +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to return the result. If the operation is successful, **undefined** is returned. Otherwise, **error** is returned. | **Example** ```js -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_MUSIC, - usage: audio.StreamUsage.STREAM_USAGE_MEDIA, - rendererFlags: 0 -} -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 0; audioRenderer.setInterruptMode(mode).then(data=>{ console.info('setInterruptMode Success!'); }).catch((err) => { console.error(`setInterruptMode Fail: ${err}`); }); + ``` + ### setInterruptMode9+ setInterruptMode(mode: InterruptMode, callback: AsyncCallback\): void @@ -4343,30 +4420,14 @@ Sets the audio interruption mode for the application. This API uses a callback t **Parameters** -| Name | Type | Mandatory | Description | -| ------- | ----------------------------------- | ------ | -------------- | -|mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode.| -|callback | AsyncCallback\ | Yes |Callback used to return the result.| +| Name | Type | Mandatory | Description | +| -------- | -------------------------------- | --------- | ----------------------------------- | +| mode | [InterruptMode](#interruptmode9) | Yes | Audio interruption mode. | +| callback | AsyncCallback\ | Yes | Callback used to return the result. | **Example** ```js -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_48000, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} -var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_MUSIC, - usage: audio.StreamUsage.STREAM_USAGE_MEDIA, - rendererFlags: 0 -} -var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo -} -let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); let mode = 1; audioRenderer.setInterruptMode(mode, (err, data)=>{ if(err){ @@ -4374,7 +4435,9 @@ audioRenderer.setInterruptMode(mode, (err, data)=>{ } console.info('setInterruptMode Success!'); }); + ``` + ### on('interrupt')9+ on(type: 'interrupt', callback: Callback\): void @@ -4385,10 +4448,10 @@ Subscribes to audio interruption events. This API uses a callback to get interru **Parameters** -| Name | Type | Mandatory| Description | -| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted.| -| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | +| Name | Type | Mandatory | Description | +| -------- | -------------------------------------------- | --------- | ------------------------------------------------------------ | +| type | string | Yes | Event type. The value **interrupt** means the audio interruption event, which is triggered when audio playback is interrupted. | +| callback | Callback<[InterruptEvent](#interruptevent9)> | Yes | Callback used to return the audio interruption event. | **Example** @@ -4438,11 +4501,12 @@ audioRenderer.on('interrupt', async(interruptEvent) => { } } }); + ``` ### on('markReach')8+ -on(type: "markReach", frame: number, callback: Callback): void +on(type: "markReach", frame: number, callback: Callback<number>): void Subscribes to mark reached events. When the number of frames rendered reaches the value of the **frame** parameter, the callback is invoked. @@ -4450,11 +4514,11 @@ Subscribes to mark reached events. When the number of frames rendered reaches th **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------- | :--- | :---------------------------------------- | -| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -4464,6 +4528,7 @@ audioRenderer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` @@ -4477,19 +4542,20 @@ Unsubscribes from mark reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :------------------------------------------------ | -| type | string | Yes | Event type. The value is fixed at **markReach**.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :----------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **markReach**. | **Example** ```js audioRenderer.off('markReach'); + ``` ### on('periodReach') 8+ -on(type: "periodReach", frame: number, callback: Callback): void +on(type: "periodReach", frame: number, callback: Callback<number>): void Subscribes to period reached events. When the period of frame rendering reaches the value of the **frame** parameter, the callback is invoked. @@ -4497,11 +4563,11 @@ Subscribes to period reached events. When the period of frame rendering reaches **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -4511,6 +4577,7 @@ audioRenderer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` ### off('periodReach') 8+ @@ -4523,14 +4590,15 @@ Unsubscribes from period reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :-------------------------------------------------- | -| type | string | Yes | Event type. The value is fixed at **periodReach**.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :------------------------------------------------- | +| type | string | Yes | Event type. The value is fixed at **periodReach**. | **Example** ```js audioRenderer.off('periodReach') + ``` ### on('stateChange')8+ @@ -4543,10 +4611,10 @@ Subscribes to state change events. **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **stateChange** means the state change event.| -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** @@ -4559,6 +4627,7 @@ audioRenderer.on('stateChange', (state) => { console.info('audio renderer state is: STATE_RUNNING'); } }); + ``` ## AudioCapturer8+ @@ -4569,14 +4638,15 @@ Provides APIs for audio capture. Before calling any API in **AudioCapturer**, yo **System capability**: SystemCapability.Multimedia.Audio.Capturer -| Name | Type | Readable| Writable| Description | -| :---- | :------------------------- | :--- | :--- | :--------------- | -| state8+ | [AudioState](#audiostate8) | Yes| No | Audio capturer state.| +| Name | Type | Readable | Writable | Description | +| :----------------- | :------------------------- | :------- | :------- | :-------------------- | +| state8+ | [AudioState](#audiostate8) | Yes | No | Audio capturer state. | **Example** ```js var state = audioCapturer.state; + ``` ### getCapturerInfo8+ @@ -4589,9 +4659,9 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :-------------------------------- | :--- | :----------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the capturer information.| +| Name | Type | Mandatory | Description | +| :------- | :-------------------------------- | :-------- | :------------------------------------------------ | +| callback | AsyncCallback | Yes | Callback used to return the capturer information. | **Example** @@ -4605,6 +4675,7 @@ audioCapturer.getCapturerInfo((err, capturerInfo) => { console.info(`Capturer flags: ${capturerInfo.capturerFlags}`); } }); + ``` @@ -4618,9 +4689,9 @@ Obtains the capturer information of this **AudioCapturer** instance. This API us **Return value** -| Type | Description | -| :------------------------------------------------ | :---------------------------------- | -| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information.| +| Type | Description | +| :------------------------------------------------ | :----------------------------------------------- | +| Promise<[AudioCapturerInfo](#audiocapturerinfo)\> | Promise used to return the capturer information. | **Example** @@ -4637,6 +4708,7 @@ audioCapturer.getCapturerInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`AudioFrameworkRecLog: CapturerInfo :ERROR: ${err}`); }); + ``` ### getStreamInfo8+ @@ -4649,9 +4721,9 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------------------------------------- | :--- | :------------------------------- | -| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------------------------------------- | :-------- | :---------------------------------------------- | +| callback | AsyncCallback<[AudioStreamInfo](#audiostreaminfo8)\> | Yes | Callback used to return the stream information. | **Example** @@ -4667,6 +4739,7 @@ audioCapturer.getStreamInfo((err, streamInfo) => { console.info(`Capturer encoding type: ${streamInfo.encodingType}`); } }); + ``` ### getStreamInfo8+ @@ -4679,9 +4752,9 @@ Obtains the stream information of this **AudioCapturer** instance. This API uses **Return value** -| Type | Description | -| :--------------------------------------------- | :------------------------------ | -| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information.| +| Type | Description | +| :--------------------------------------------- | :--------------------------------------------- | +| Promise<[AudioStreamInfo](#audiostreaminfo8)\> | Promise used to return the stream information. | **Example** @@ -4695,6 +4768,7 @@ audioCapturer.getStreamInfo().then((audioParamsGet) => { }).catch((err) => { console.error(`getStreamInfo :ERROR: ${err}`); }); + ``` ### start8+ @@ -4707,9 +4781,9 @@ Starts capturing. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -4721,6 +4795,7 @@ audioCapturer.start((err) => { console.info('Capturer start success.'); } }); + ``` @@ -4734,35 +4809,13 @@ Starts capturing. This API uses a promise to return the result. **Return value** -| Type | Description | -| :------------- | :---------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** ```js -import audio from '@ohos.multimedia.audio'; -import fileio from '@ohos.fileio'; - -var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_2, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW -} - -var audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 0 -} - -var audioCapturer; -audio.createAudioCapturer(audioCapturerOptions).then((data) => { - audioCapturer = data; - console.info('AudioFrameworkRecLog: AudioCapturer Created: SUCCESS'); - }).catch((err) => { - console.info(`AudioFrameworkRecLog: AudioCapturer Created: ERROR: ${err}`); - }); audioCapturer.start().then(() => { console.info('AudioFrameworkRecLog: ---------START---------'); console.info('AudioFrameworkRecLog: Capturer started: SUCCESS'); @@ -4774,6 +4827,7 @@ audioCapturer.start().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer start :ERROR : ${err}`); }); + ``` ### stop8+ @@ -4786,9 +4840,9 @@ Stops capturing. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -4800,6 +4854,7 @@ audioCapturer.stop((err) => { console.info('Capturer stopped.'); } }); + ``` @@ -4813,9 +4868,9 @@ Stops capturing. This API uses a promise to return the result. **Return value** -| Type | Description | -| :------------- | :---------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** @@ -4829,6 +4884,7 @@ audioCapturer.stop().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); + ``` ### release8+ @@ -4841,9 +4897,9 @@ Releases this **AudioCapturer** instance. This API uses an asynchronous callback **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------- | :--- | :---------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result. | +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -4855,6 +4911,7 @@ audioCapturer.release((err) => { console.info('capturer released.'); } }); + ``` @@ -4868,9 +4925,9 @@ Releases this **AudioCapturer** instance. This API uses a promise to return the **Return value** -| Type | Description | -| :------------- | :---------------------------- | -| Promise | Promise used to return the result.| +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | **Example** @@ -4884,6 +4941,7 @@ audioCapturer.release().then(() => { }).catch((err) => { console.info(`AudioFrameworkRecLog: Capturer stop: ERROR: ${err}`); }); + ``` @@ -4897,11 +4955,11 @@ Reads the buffer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| :------------- | :-------------------------- | :--- | :------------------------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation. | -| callback | AsyncCallback | Yes | Callback used to return the buffer.| +| Name | Type | Mandatory | Description | +| :------------- | :-------------------------- | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | +| callback | AsyncCallback | Yes | Callback used to return the buffer. | **Example** @@ -4918,6 +4976,7 @@ audioCapturer.read(bufferSize, true, async(err, buffer) => { console.info('Success in reading the buffer data'); } }); + ``` @@ -4931,16 +4990,16 @@ Reads the buffer. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| :------------- | :------ | :--- | :--------------- | -| size | number | Yes | Number of bytes to read. | -| isBlockingRead | boolean | Yes | Whether to block the read operation.| +| Name | Type | Mandatory | Description | +| :------------- | :------ | :-------- | :----------------------------------- | +| size | number | Yes | Number of bytes to read. | +| isBlockingRead | boolean | Yes | Whether to block the read operation. | **Return value** -| Type | Description | -| :-------------------- | :----------------------------------------------------- | -| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned.| +| Type | Description | +| :-------------------- | :----------------------------------------------------------- | +| Promise | Promise used to return the result. If the operation is successful, the buffer data read is returned; otherwise, an error code is returned. | **Example** @@ -4958,6 +5017,7 @@ audioCapturer.read(bufferSize, true).then((buffer) => { }).catch((err) => { console.info(`ERROR : ${err}`); }); + ``` @@ -4971,9 +5031,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------- | :--- | :----------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the result.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | **Example** @@ -4981,6 +5041,7 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). audioCapturer.getAudioTime((err, timestamp) => { console.info(`Current timestamp: ${timestamp}`); }); + ``` @@ -4994,9 +5055,9 @@ Obtains the number of nanoseconds elapsed from the Unix epoch (January 1, 1970). **Return value** -| Type | Description | -| :--------------- | :---------------------------- | -| Promise | Promise used to return the timestamp.| +| Type | Description | +| :--------------- | :------------------------------------ | +| Promise | Promise used to return the timestamp. | **Example** @@ -5006,6 +5067,7 @@ audioCapturer.getAudioTime().then((audioTime) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: AudioCapturer Created : ERROR : ${err}`); }); + ``` @@ -5019,9 +5081,9 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :--------------------- | :--- | :----------------------------------- | -| callback | AsyncCallback | Yes | Callback used to return the buffer size.| +| Name | Type | Mandatory | Description | +| :------- | :--------------------- | :-------- | :--------------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the buffer size. | **Example** @@ -5036,6 +5098,7 @@ audioCapturer.getBufferSize((err, bufferSize) => { }); } }); + ``` @@ -5049,9 +5112,9 @@ Obtains a reasonable minimum buffer size in bytes for capturing. This API uses a **Return value** -| Type | Description | -| :--------------- | :---------------------------------- | -| Promise | Promise used to return the buffer size.| +| Type | Description | +| :--------------- | :-------------------------------------- | +| Promise | Promise used to return the buffer size. | **Example** @@ -5063,12 +5126,13 @@ audioCapturer.getBufferSize().then((data) => { }).catch((err) => { console.info(`AudioFrameworkRecLog: getBufferSize :ERROR : ${err}`); }); + ``` ### on('markReach')8+ -on(type: "markReach", frame: number, callback: Callback): void +on(type: "markReach", frame: number, callback: Callback<number>): void Subscribes to mark reached events. When the number of frames captured reaches the value of the **frame** parameter, the callback is invoked. @@ -5076,11 +5140,11 @@ Subscribes to mark reached events. When the number of frames captured reaches th **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :---------------------- | :--- | :----------------------------------------- | -| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered.| +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -5090,6 +5154,7 @@ audioCapturer.on('markReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` ### off('markReach')8+ @@ -5102,19 +5167,20 @@ Unsubscribes from mark reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :-------------------------------------------- | -| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **markReach** means the mark reached event, which is triggered when the number of frames captured reaches the value of the **frame** parameter. | **Example** ```js audioCapturer.off('markReach'); + ``` ### on('periodReach')8+ -on(type: "periodReach", frame: number, callback: Callback): void +on(type: "periodReach", frame: number, callback: Callback<number>): void Subscribes to mark reached events. When the period of frame capturing reaches the value of the **frame** parameter, the callback is invoked. @@ -5122,11 +5188,11 @@ Subscribes to mark reached events. When the period of frame capturing reaches th **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :----------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter.| -| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | -| callback | Callback | Yes | Callback invoked when the event is triggered. | +| Name | Type | Mandatory | Description | +| :------- | :--------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame rendering reaches the value of the **frame** parameter. | +| frame | number | Yes | Number of frames to trigger the event. The value must be greater than **0**. | +| callback | Callback | Yes | Callback invoked when the event is triggered. | **Example** @@ -5136,6 +5202,7 @@ audioCapturer.on('periodReach', 1000, (position) => { console.info('ON Triggered successfully'); } }); + ``` ### off('periodReach')8+ @@ -5148,14 +5215,15 @@ Unsubscribes from period reached events. **Parameters** -| Name| Type | Mandatory| Description | -| :----- | :----- | :--- | :---------------------------------------------- | -| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter.| +| Name | Type | Mandatory | Description | +| :--- | :----- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **periodReach** means the period reached event, which is triggered when the period of frame capturing reaches the value of the **frame** parameter. | **Example** ```js audioCapturer.off('periodReach') + ``` ### on('stateChange')8+ @@ -5168,10 +5236,10 @@ Subscribes to state change events. **Parameters** -| Name | Type | Mandatory| Description | -| :------- | :------------------------- | :--- | :------------------------------------------ | -| type | string | Yes | Event type. The value **stateChange** means the state change event.| -| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | +| Name | Type | Mandatory | Description | +| :------- | :------------------------- | :-------- | :----------------------------------------------------------- | +| type | string | Yes | Event type. The value **stateChange** means the state change event. | +| callback | [AudioState](#audiostate8) | Yes | Callback used to return the state change. | **Example** @@ -5184,4 +5252,262 @@ audioCapturer.on('stateChange', (state) => { console.info('audio capturer state is: STATE_RUNNING'); } }); + ``` + +## ToneType 9+ + +Enumerates the tone types of the player. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +| Name | Default Value | Description | +| :----------------------------------------------- | :------------ | :------------------------------------------- | +| TONE_TYPE_DIAL_0 | 0 | DTMF tone of key 0. | +| TONE_TYPE_DIAL_1 | 1 | DTMF tone of key 1. | +| TONE_TYPE_DIAL_2 | 2 | DTMF tone of key 2. | +| TONE_TYPE_DIAL_3 | 3 | DTMF tone of key 3. | +| TONE_TYPE_DIAL_4 | 4 | DTMF tone of key 4. | +| TONE_TYPE_DIAL_5 | 5 | DTMF tone of key 5. | +| TONE_TYPE_DIAL_6 | 6 | DTMF tone of key 6. | +| TONE_TYPE_DIAL_7 | 7 | DTMF tone of key 7. | +| TONE_TYPE_DIAL_8 | 8 | DTMF tone of key 8. | +| TONE_TYPE_DIAL_9 | 9 | DTMF tone of key 9. | +| TONE_TYPE_DIAL_S | 10 | DTMF tone of the star key (*). | +| TONE_TYPE_DIAL_P | 11 | DTMF tone of the pound key (#). | +| TONE_TYPE_DIAL_A | 12 | DTMF tone of key A. | +| TONE_TYPE_DIAL_B | 13 | DTMF tone of key B. | +| TONE_TYPE_DIAL_C | 14 | DTMF tone of key C. | +| TONE_TYPE_DIAL_D | 15 | DTMF tone of key D. | +| TONE_TYPE_COMMON_SUPERVISORY_DIAL | 100 | Supervisory tone - dial tone. | +| TONE_TYPE_COMMON_SUPERVISORY_BUSY | 101 | Supervisory tone - busy. | +| TONE_TYPE_COMMON_SUPERVISORY_CONGESTION | 102 | Supervisory tone - congestion. | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_ACK | 103 | Supervisory tone - radio path acknowledgment | +| TONE_TYPE_COMMON_SUPERVISORY_RADIO_NOT_AVAILABLE | 104 | Supervisory tone - radio path not available | +| TONE_TYPE_COMMON_SUPERVISORY_CALL_WAITING | 106 | Supervisory tone - call waiting tone | +| TONE_TYPE_COMMON_SUPERVISORY_RINGTONE | 107 | Supervisory tone - ringing tone | +| TONE_TYPE_COMMON_PROPRIETARY_BEEP | 200 | Proprietary tone - beep tone. | +| TONE_TYPE_COMMON_PROPRIETARY_ACK | 201 | Proprietary tone - ACK. | +| TONE_TYPE_COMMON_PROPRIETARY_PROMPT | 203 | Proprietary tone - PROMPT. | +| TONE_TYPE_COMMON_PROPRIETARY_DOUBLE_BEEP | 204 | Proprietary tone - double beep tone. | + +## TonePlayer9+ + +Provides APIs for playing and managing DTMF tones, such as dial tones, ringback tones, supervisory tones, and proprietary tones. + +### load9+ + +load(type: ToneType, callback: AsyncCallback<void>): void + +Loads the DTMF tone configuration. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| type | ToneType(#tonetype9) | Yes | Tone type. | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_5, (err) => { + if (err) { + console.error(`callback call load failed error: ${err.message}`); + return; + } else { + console.info('callback call load success'); + } +}); + +``` + +### load9+ + +load(type: ToneType): Promise<void> + +Loads the DTMF tone configuration. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :--- | :------------------- | :-------- | ----------- | +| type | ToneType(#tonetype9) | Yes | Tone type. | + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.load(audio.ToneType.TONE_TYPE_DIAL_1).then(() => { + console.info('promise call load '); +}).catch(() => { + console.error('promise call load fail'); +}); + +``` + +### start9+ + +start(callback: AsyncCallback<void>): void + +Starts DTMF tone playing. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.start((err) => { + if (err) { + console.error(`callback call start failed error: ${err.message}`); + return; + } else { + console.info('callback call start success'); + } +}); + +``` + +### start9+ + +start(): Promise<void> + +Starts DTMF tone playing. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.start().then(() => { + console.info('promise call start'); +}).catch(() => { + console.error('promise call start fail'); +}); + +``` + +### stop9+ + +stop(callback: AsyncCallback<void>): void + +Stops the tone that is being played. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.stop((err) => { + if (err) { + console.error(`callback call stop error: ${err.message}`); + return; + } else { + console.error('callback call stop success '); + } +}); + +``` + +### stop9+ + +stop(): Promise<void> + +Stops the tone that is being played. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.stop().then(() => { + console.info('promise call stop finish'); +}).catch(() => { + console.error('promise call stop fail'); +}); + +``` + +### release9+ + +release(callback: AsyncCallback<void>): void + +Releases the resources associated with the **TonePlay** instance. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Parameters** + +| Name | Type | Mandatory | Description | +| :------- | :------------------- | :-------- | :---------------------------------- | +| callback | AsyncCallback | Yes | Callback used to return the result. | + +**Example** + +```js +tonePlayer.release((err) => { + if (err) { + console.error(`callback call release failed error: ${err.message}`); + return; + } else { + console.info('callback call release success '); + } +}); +``` + +### release9+ + +release(): Promise<void> + +Releases the resources associated with the **TonePlay** instance. This API uses a promise to return the result. + +**System capability**: SystemCapability.Multimedia.Audio.Tone + +**Return value** + +| Type | Description | +| :------------- | :--------------------------------- | +| Promise | Promise used to return the result. | + +**Example** + +```js +tonePlayer.release().then(() => { + console.info('promise call release'); +}).catch(() => { + console.error('promise call release fail'); +}); +``` \ No newline at end of file diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md index b1c81e2eecd00b5043bb703b574bcc0c06533373..c055385384fc9c1a28818fc0a1bd23a355e83076 100644 --- a/en/application-dev/reference/apis/js-apis-buffer.md +++ b/en/application-dev/reference/apis/js-apis-buffer.md @@ -16,6 +16,16 @@ import buffer from '@ohos.buffer'; ## Buffer +### Attributes + +**System capability**: SystemCapability.Utils.Lang + +| Name| Type| Readable| Writable| Description| +| -------- | -------- | -------- | -------- | -------- | +| length | number | Yes| No| Length of the buffer, in bytes.| +| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.| +| byteOffset | number | Yes| No| Offset of the buffer in the memory pool.| + ### alloc alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer @@ -2422,7 +2432,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc let blob3 = blob.slice(0, 2, "MIME"); ``` - ### text +### text text(): Promise<string> diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md index f6702d14d391a025bf9a16f2d8bf79a97772ed0a..5fedece20aac3dc30e68020964be1fbca1cefdfa 100644 --- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md +++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md @@ -195,7 +195,7 @@ Moves to the specified row in the result set. **Example** ```ts -let goToRowNum = 2 +let goToRowNum = 2; let isGoToRow = resultSet.goToRow(goToRowNum); console.info('resultSet.goToRow: ' + isGoToRow); ``` @@ -223,7 +223,7 @@ Obtains the value in the form of a byte array based on the specified column and **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getBlob = resultSet.getBlob(columnIndex); console.info('resultSet.getBlob: ' + getBlob); @@ -231,7 +231,7 @@ console.info('resultSet.getBlob: ' + getBlob); ### getString -getString(columnIndex: number): *string* +getString(columnIndex: number): string Obtains the value in the form of a string based on the specified column and the current row. @@ -252,7 +252,7 @@ Obtains the value in the form of a string based on the specified column and the **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getString = resultSet.getString(columnIndex); console.info('resultSet.getString: ' + getString); @@ -281,7 +281,7 @@ Obtains the value in the form of a long integer based on the specified column an **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getLong = resultSet.getLong(columnIndex); console.info('resultSet.getLong: ' + getLong); @@ -310,7 +310,7 @@ Obtains the value in the form of a double-precision floating-point number based **Example** ```ts -let columnIndex = 1 +let columnIndex = 1; let goToFirstRow = resultSet.goToFirstRow(); let getDouble = resultSet.getDouble(columnIndex); console.info('resultSet.getDouble: ' + getDouble); @@ -353,14 +353,14 @@ Obtains the column index based on the column name. **Example** ```ts -let ColumnName = "name" -let getColumnIndex = resultSet.getColumnIndex(ColumnName) +let ColumnName = "name"; +let getColumnIndex = resultSet.getColumnIndex(ColumnName); console.info('resultSet.getColumnIndex: ' + getColumnIndex); ``` ### getColumnName -getColumnName(columnIndex: number): *string* +getColumnName(columnIndex: number): string Obtains the column name based on the column index. @@ -381,8 +381,8 @@ Obtains the column name based on the column index. **Example** ```ts -let columnIndex = 1 -let getColumnName = resultSet.getColumnName(columnIndex) +let columnIndex = 1; +let getColumnName = resultSet.getColumnName(columnIndex); console.info('resultSet.getColumnName: ' + getColumnName); ``` diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md index 2f54d7d7c47b10403fbc96edf92ce1d55cdcb41b..4d2df994d96b7b0986782774e9d531a12750cac7 100644 --- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md +++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md @@ -2,6 +2,8 @@ You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data. +The APIs provided by **DataSharePredicates** correspond to the filter criteria of the database. Before using the APIs, you need to have basic database knowledge. + > **NOTE** > > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -22,7 +24,7 @@ Provides methods for setting different **DataSharePredicates** objects. equalTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is equal to the specified value. Currently, only the relational database (RDB) and key-value database (KVDB, schema) support this **DataSharePredicates** object. @@ -52,7 +54,7 @@ predicates.equalTo("NAME", "Rose") notEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is not equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is not equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -188,7 +190,7 @@ predicates.equalTo("NAME", "lisi") contains(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that contains the specified value. +Sets a **DataSharePredicates** object to search for the data that contains the specified value. Currently, only the RDB supports this **DataSharePredicates** object. @@ -218,7 +220,7 @@ predicates.contains("NAME", "os") beginsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that begins with the specified value. +Sets a **DataSharePredicates** object to search for the data that begins with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. @@ -248,7 +250,7 @@ predicates.beginsWith("NAME", "os") endsWith(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that ends with the specified value. +Sets a **DataSharePredicates** object to search for the data that ends with the specified value. Currently, only the RDB supports this **DataSharePredicates** object. @@ -278,7 +280,7 @@ predicates.endsWith("NAME", "os") isNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data whose value is null. +Sets a **DataSharePredicates** object to search for the data whose value is null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -307,7 +309,7 @@ predicates.isNull("NAME") isNotNull(field: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data whose value is not null. +Sets a **DataSharePredicates** object to search for the data whose value is not null. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -336,7 +338,7 @@ predicates.isNotNull("NAME") like(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is similar to the specified value. +Sets a **DataSharePredicates** object to search for the data that matches the specified wildcard expression. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -347,7 +349,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match.| +| value | string | Yes | Wildcard expression to match.
In the expression, '%' represents zero, one, or more digits or characters, and '_' represents a single digit or character. It is case insensitive.| **Return value** @@ -366,7 +368,7 @@ predicates.like("NAME", "%os%") unlike(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is not not similar to the specified value. +Sets a **DataSharePredicates** object to search for the data that does not match the specified wildcard expression. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -377,7 +379,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match.| +| value | string | Yes | Wildcard expression to match.
In the expression, '%' represents zero, one, or more digits or characters, and '_' represents a single digit or character. It is case insensitive.| **Return value** @@ -396,7 +398,7 @@ predicates.unlike("NAME", "%os%") glob(field: string, value: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the specified string. +Sets a **DataSharePredicates** object to search for the data that matches the specified wildcard expression. Currently, only the RDB supports this **DataSharePredicates** object. @@ -407,7 +409,7 @@ Currently, only the RDB supports this **DataSharePredicates** object. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ---------------------- | | field | string | Yes | Column name in the database table. | -| value | string | Yes | Value to match.| +| value | string | Yes | Wildcard expression to match.
In the expression, '*' represents zero, one, or more digits or characters, and '?' represents a single digit or character. It is case sensitive.| **Return value** @@ -426,7 +428,7 @@ predicates.glob("NAME", "?h*g") between(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is within the specified range. +Sets a **DataSharePredicates** object to search for the data that is within the specified range, including the start and end values. Currently, only the RDB supports this **DataSharePredicates** object. @@ -457,7 +459,7 @@ predicates.between("AGE", 10, 50) notBetween(field: string, low: ValueType, high: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is out of the specified range. +Sets a **DataSharePredicates** object to search for the data that is out of the specified range, excluding the start and end values. Currently, only the RDB supports this **DataSharePredicates** object. @@ -488,7 +490,7 @@ predicates.notBetween("AGE", 10, 50) greaterThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is greater than the specified value. +Sets a **DataSharePredicates** object to search for the data that is greater than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -518,7 +520,7 @@ predicates.greaterThan("AGE", 10) lessThan(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is less than the specified value. +Sets a **DataSharePredicates** object to search for the data that is less than the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -548,7 +550,7 @@ predicates.lessThan("AGE", 50) greaterThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is greater than or equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is greater than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -578,7 +580,7 @@ predicates.greaterThanOrEqualTo("AGE", 10) lessThanOrEqualTo(field: string, value: ValueType): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is less than or equal to the specified value. +Sets a **DataSharePredicates** object to search for the data that is less than or equal to the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -777,7 +779,7 @@ predicates.indexedBy("SALARY_INDEX") in(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is within the specified value. +Sets a **DataSharePredicates** object to search for the data that is within the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -807,7 +809,7 @@ predicates.in("AGE", [18, 20]) notIn(field: string, value: Array<ValueType>): DataSharePredicates -Sets a **DataSharePredicates** object to match the data that is not in the specified value. +Sets a **DataSharePredicates** object to search for the data that is not in the specified value. Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** object. @@ -837,7 +839,7 @@ predicates.notIn("NAME", ["Lisa", "Rose"]) prefixKey(prefix: string): DataSharePredicates -Sets a **DataSharePredicates** object to match the data with the specified key prefix. +Sets a **DataSharePredicates** object to search for the data with the specified key prefix. Currently, only the KVDB supports this **DataSharePredicates** object. @@ -866,7 +868,7 @@ predicates.prefixKey("NAME") inKeys(keys: Array<string>): DataSharePredicates -Sets a **DataSharePredicates** object to match the data whose keys are within the given range. +Sets a **DataSharePredicates** object to search for the data whose keys are within the given range. Currently, only the KVDB supports this **DataSharePredicates** object. diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 6803d4edf50fc219bc37c4be79fc71687dd91457..153397a41d715c1814a143a4ff051e6964ba29eb 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -38,15 +38,21 @@ Obtains a **Preferences** instance. This API uses an asynchronous callback to re | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | -| name | string | Yes | Name of the **Preferences** instance. | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | +| name | string | Yes | Name of the **Preferences** instance.| | callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| **Example** +FA model: + ```js -var preferences = null; -data_preferences.getPreferences(this.context, 'mystore', function (err, object) { +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let preferences = null; +data_preferences.getPreferences(context, 'mystore', function (err, object) { if (err) { console.info("Failed to get the preferences. Cause: " + err); return; @@ -56,6 +62,28 @@ data_preferences.getPreferences(this.context, 'mystore', function (err, object) }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let preferences = null; +data_preferences.getPreferences(context, 'mystore', function (err, object) { + if (err) { + console.info("Failed to get the preferences. Cause: " + err); + return; + } + preferences = object; + console.info("Got the preferences successfully."); +}) +``` ## data_preferences.getPreferences @@ -66,21 +94,29 @@ Obtains a **Preferences** instance. This API uses a promise to return the result **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance.| **Return value** + | Type | Description | | ------------------------------------------ | ---------------------------------- | | Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| **Example** +FA model: + ```js -var preferences = null; -let promise = data_preferences.getPreferences(this.context, 'mystore') +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let preferences = null; +let promise = data_preferences.getPreferences(context, 'mystore'); promise.then((object) => { preferences = object; console.info("Got the preferences successfully."); @@ -89,6 +125,27 @@ promise.then((object) => { }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let preferences = null; +let promise = data_preferences.getPreferences(context, 'mystore'); +promise.then((object) => { + preferences = object; + console.info("Got the preferences successfully."); +}).catch((err) => { + console.info("Failed to get the preferences. Cause: " + err); +}) +``` ## data_preferences.deletePreferences @@ -103,23 +160,51 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + +FA model: + ```js -data_preferences.deletePreferences(this.context, 'mystore', function (err) { +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +data_preferences.deletePreferences(context, 'mystore', function (err) { if (err) { console.info("Failed to delete the preferences. Cause: " + err); - return + return; } console.info("Deleted the preferences successfully." ); }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +data_preferences.deletePreferences(context, 'mystore', function (err) { + if (err) { + console.info("Failed to delete the preferences. Cause: " + err); + return; + } + console.info("Deleted the preferences successfully." ); +}) +``` ## data_preferences.deletePreferences @@ -134,19 +219,28 @@ The deleted **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + +FA model: + ```js -let promise = data_preferences.deletePreferences(this.context, 'mystore') +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let promise = data_preferences.deletePreferences(context, 'mystore'); promise.then(() => { console.info("Deleted the preferences successfully."); }).catch((err) => { @@ -154,6 +248,25 @@ promise.then(() => { }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let promise = data_preferences.deletePreferences(context, 'mystore'); +promise.then(() => { + console.info("Deleted the preferences successfully."); +}).catch((err) => { + console.info("Failed to delete the preferences. Cause: " + err); +}) +``` ## data_preferences.removePreferencesFromCache @@ -166,15 +279,23 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ---------------------------------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + +FA model: + ```js -data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { if (err) { console.info("Failed to remove the preferences. Cause: " + err); return; @@ -183,6 +304,26 @@ data_preferences.removePreferencesFromCache(this.context, 'mystore', function (e }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +data_preferences.removePreferencesFromCache(context, 'mystore', function (err) { + if (err) { + console.info("Failed to remove the preferences. Cause: " + err); + return; + } + console.info("Removed the preferences successfully."); +}) +``` ## data_preferences.removePreferencesFromCache @@ -195,19 +336,28 @@ The removed **Preferences** instance cannot be used for data operations. Otherwi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name | Type | Mandatory| Description | -| ------- | ------------------------------------- | ---- | -------------------------- | -| context | [Context](js-apis-ability-context.md) | Yes | Application context. | + +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | ----------------------- | +| context | Context | Yes | Application context.
For the application context of the FA model, see [Context](js-apis-Context.md).
For the application context of the stage model, see [Context](js-apis-ability-context.md). | | name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + +FA model: + ```js -let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore') +// Obtain the context. +import featureAbility from '@ohos.ability.featureAbility'; +let context = featureAbility.getContext(); + +let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); promise.then(() => { console.info("Removed the preferences successfully."); }).catch((err) => { @@ -215,6 +365,25 @@ promise.then(() => { }) ``` +Stage model: + +```ts +// Obtain the context. +import Ability from '@ohos.application.Ability'; +let context = null; +class MainAbility extends Ability{ + onWindowStageCreate(windowStage){ + context = this.context; + } +} + +let promise = data_preferences.removePreferencesFromCache(context, 'mystore'); +promise.then(() => { + console.info("Removed the preferences successfully."); +}).catch((err) => { + console.info("Failed to remove the preferences. Cause: " + err); +}) +``` ## Preferences @@ -232,6 +401,7 @@ Obtains the value of a key. This API uses an asynchronous callback to return the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -260,6 +430,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to obtain. It cannot be empty. | @@ -272,6 +443,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the | Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| **Example** + ```js let promise = preferences.get('startup', 'default'); promise.then((data) => { @@ -290,6 +462,7 @@ Obtains an **Object** instance that contains all KV pairs. This API uses an asyn **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | callback | AsyncCallback<Object> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** is the **Object** instance obtained. Otherwise, **err** is an error code.| @@ -318,11 +491,13 @@ Obtains an **Object** instance that contains all KV pairs. This API uses a promi **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | --------------------- | ------------------------------------------- | | Promise<Object> | Promise used to return the **Object** instance obtained.| **Example** + ```js let promise = preferences.getAll(); promise.then((value) => { @@ -343,6 +518,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | @@ -350,6 +526,7 @@ Writes data to this **Preferences** instance. This API uses an asynchronous call | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. | **Example** + ```js preferences.put('startup', 'auto', function (err) { if (err) { @@ -370,17 +547,20 @@ Writes data to this **Preferences** instance. This API uses a promise to return **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ----------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data. It cannot be empty. | | value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.put('startup', 'auto'); promise.then(() => { @@ -395,17 +575,19 @@ promise.then(() => { has(key: string, callback: AsyncCallback<boolean>): void -Checks whether this **Preferences** instance contains a KV pair of the given key. This API uses an asynchronous callback to return the result.. +Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses an asynchronous callback to return the result.. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ------------------------------------------------------------ | | key | string | Yes | Key of the data to check. It cannot be empty. | | callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** + ```js preferences.has('startup', function (err, isExist) { if (err) { @@ -425,16 +607,18 @@ preferences.has('startup', function (err, isExist) { has(key: string): Promise<boolean> -Checks whether this **Preferences** instance contains data with the given key. This API uses a promise to return the result. +Checks whether this **Preferences** instance contains a KV pair with the given key. This API uses a promise to return the result.. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the data to check. It cannot be empty.| **Return value** + | Type | Description | | ---------------------- | ------------------------------------------------------------ | | Promise<boolean> | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| @@ -464,12 +648,14 @@ Deletes a KV pair from this **Preferences** instance. This API uses an asynchron **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty. | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.delete('startup', function (err) { if (err) { @@ -490,16 +676,19 @@ Deletes a KV pair from this **Preferences** instance. This API uses a promise to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------------------- | | key | string | Yes | Key of the KV pair to delete. It cannot be empty.| **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.delete('startup'); promise.then(() => { @@ -514,16 +703,18 @@ promise.then(() => { flush(callback: AsyncCallback<void>): void -Saves the data of the **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. +Saves the data of this **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.flush(function (err) { if (err) { @@ -539,16 +730,18 @@ preferences.flush(function (err) { flush(): Promise<void> -Saves the data of the **Preferences** instance to a file asynchronously. This API uses a promise to return the result. +Saves the data of this **Preferences** instance to a file asynchronously. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.flush(); promise.then(() => { @@ -568,11 +761,13 @@ Clears this **Preferences** instance. This API uses an asynchronous callback to **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | ---------------------------------------------------- | | callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** + ```js preferences.clear(function (err) { if (err) { @@ -593,11 +788,13 @@ Clears this **Preferences** instance. This API uses a promise to return the resu **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** + | Type | Description | | ------------------- | ------------------------- | | Promise<void> | Promise that returns no value.| **Example** + ```js let promise = preferences.clear() promise.then(() => { @@ -617,23 +814,25 @@ Subscribes to data changes. A callback will be triggered to return the new value **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------- | ---- | ---------------------------------------- | | type | string | Yes | Event type to subscribe to. The value **change** indicates data change events.| | callback | Callback<{ key : string }> | Yes | Callback invoked to return data changes. | **Example** + ```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { console.info("Failed to get the preferences."); return; } - var observer = function (key) { + let observer = function (key) { console.info("The key " + key + " changed."); } preferences.on('change', observer); - preferences.put('startup', 'auto', function (err) { + preferences.put('startup', 'manual', function (err) { if (err) { console.info("Failed to put the value of 'startup'. Cause: " + err); return; @@ -661,19 +860,21 @@ Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** + | Name | Type | Mandatory| Description | | -------- | -------------------------------- | ---- | ------------------------------------------ | | type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | | callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| **Example** + ```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to get preferences."); + console.info("Failed to get the preferences."); return; } - var observer = function (key) { + let observer = function (key) { console.info("The key " + key + " changed."); } preferences.on('change', observer); diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md index 3098499d48ca52b0251cfb9648cc032fc26e2652..28cde770498760d5eac09dc79c5b495f91d05c4a 100644 --- a/en/application-dev/reference/apis/js-apis-data-resultset.md +++ b/en/application-dev/reference/apis/js-apis-data-resultset.md @@ -6,26 +6,25 @@ A result set is a set of results returned after the relational database (RDB) qu > > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Usage You need to use [RdbStore.query()](js-apis-data-rdb.md#query) to obtain a **resultSet** object. ```js import dataRdb from '@ohos.data.rdb'; -let predicates = new dataRdb.RdbPredicates("EMPLOYEE") -predicates.equalTo("AGE", 18) -let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]) +let predicates = new dataRdb.RdbPredicates("EMPLOYEE"); +predicates.equalTo("AGE", 18); +let promise = rdbStore.query(predicates, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promise.then((resultSet) => { console.log(TAG + "resultSet columnNames:" + resultSet.columnNames); - console.log(TAG + "resultSet columnCount:" + resultSet.columnCount);}) + console.log(TAG + "resultSet columnCount:" + resultSet.columnCount); +}); ``` ## ResultSet Provides methods to access the result set, which is obtained by querying the RDB store. - ### Attributes **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core @@ -42,7 +41,6 @@ Provides methods to access the result set, which is obtained by querying the RDB | isStarted | boolean | Yes| Whether the cursor has been moved.| | isClosed | boolean | Yes| Whether the result set is closed.| - ### getColumnIndex getColumnIndex(columnName: string): number @@ -52,25 +50,27 @@ Obtains the column index based on the column name. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | columnName | string | Yes| Column name specified.| **Return value** + | Type| Description| | -------- | -------- | | number | Index of the column obtained.| **Example** + ```js - resultSet.goToFirstRow() - const id = resultSet.getLong(resultSet.getColumnIndex("ID")) - const name = resultSet.getString(resultSet.getColumnIndex("NAME")) - const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) - const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + resultSet.goToFirstRow(); + const id = resultSet.getLong(resultSet.getColumnIndex("ID")); + const name = resultSet.getString(resultSet.getColumnIndex("NAME")); + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` - ### getColumnName getColumnName(columnIndex: number): string @@ -80,23 +80,25 @@ Obtains the column name based on the column index. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | columnIndex | number | Yes| Column index specified.| **Return value** + | Type| Description| | -------- | -------- | | string | Column name obtained.| **Example** + ```js - const id = resultSet.getColumnName(0) - const name = resultSet.getColumnName(1) - const age = resultSet.getColumnName(2) + const id = resultSet.getColumnName(0); + const name = resultSet.getColumnName(1); + const age = resultSet.getColumnName(2); ``` - ### goTo goTo(offset:number): boolean @@ -106,28 +108,30 @@ Moves the cursor to the row based on the specified offset. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | offset | number | Yes| Offset relative to the current position.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js - let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoto = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoto = rdbStore.query(predicatesgoto, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoto.then((resultSet) { - resultSet.goTo(1) - resultSet.close() + resultSet.goTo(1); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToRow goToRow(position: number): boolean @@ -137,28 +141,30 @@ Moves the cursor to the specified row in the result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | position | number | Yes| Position to which the cursor is to be moved.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js - let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgotorow = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygotorow = rdbStore.query(predicatesgotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygotorow.then((resultSet) { - resultSet.goToRow(5) - resultSet.close() + resultSet.goToRow(5); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToFirstRow goToFirstRow(): boolean @@ -169,23 +175,24 @@ Moves the cursor to the first row of the result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js - let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoFirst = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoFirst = rdbStore.query(predicatesgoFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoFirst.then((resultSet) { - resultSet.goToFirstRow() - resultSet.close() + resultSet.goToFirstRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToLastRow goToLastRow(): boolean @@ -195,23 +202,24 @@ Moves the cursor to the last row of the result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js - let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoLast = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoLast = rdbStore.query(predicatesgoLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoLast.then((resultSet) { - resultSet.goToLastRow() - resultSet.close() + resultSet.goToLastRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToNextRow goToNextRow(): boolean @@ -221,23 +229,24 @@ Moves the cursor to the next row in the result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js - let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoNext = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoNext = rdbStore.query(predicatesgoNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoNext.then((resultSet) { - resultSet.goToNextRow() - resultSet.close() + resultSet.goToNextRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### goToPreviousRow goToPreviousRow(): boolean @@ -247,23 +256,24 @@ Moves the cursor to the previous row in the result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** + ```js - let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE") - let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesgoPrev = new dataRdb.RdbPredicates("EMPLOYEE"); + let promisequerygoPrev = rdbStore.query(predicatesgoPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promisequerygoPrev.then((resultSet) { - resultSet.goToPreviousRow() - resultSet.close() + resultSet.goToPreviousRow(); + resultSet.close(); }).catch((err) => { - console.log('query failed') - }) + console.log('query failed'); + }); ``` - ### getBlob getBlob(columnIndex: number): Uint8Array @@ -273,21 +283,23 @@ Obtains the value in the specified column in the current row as a byte array. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** + | Type| Description| | -------- | -------- | | Uint8Array | Value in the specified column as a byte array.| **Example** + ```js - const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")) + const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES")); ``` - ### getString getString(columnIndex: number): string @@ -297,21 +309,23 @@ Obtains the value in the specified column in the current row as a string. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** + | Type| Description| | -------- | -------- | | string | Value in the specified column as a string.| **Example** + ```js - const name = resultSet.getString(resultSet.getColumnIndex("NAME")) + const name = resultSet.getString(resultSet.getColumnIndex("NAME")); ``` - ### getLong getLong(columnIndex: number): number @@ -321,21 +335,23 @@ Obtains the value in the specified column in the current row as a Long. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** + | Type| Description| | -------- | -------- | | number | Value in the specified column as a Long.| **Example** + ```js - const age = resultSet.getLong(resultSet.getColumnIndex("AGE")) + const age = resultSet.getLong(resultSet.getColumnIndex("AGE")); ``` - ### getDouble getDouble(columnIndex: number): number @@ -345,21 +361,23 @@ Obtains the value in the specified column in the current row as a double. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** + | Type| Description| | -------- | -------- | | number | Value in the specified column as a double.| **Example** + ```js - const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")) + const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY")); ``` - ### isColumnNull isColumnNull(columnIndex: number): boolean @@ -369,21 +387,23 @@ Checks whether the value in the specified column of the current row is null. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | columnIndex | number | Yes| Index of the specified column, starting from 0.| **Return value** + | Type| Description| | -------- | -------- | | boolean | Returns **true** if the value is null; returns **false** otherwise.| **Example** + ```js - const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")) + const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES")); ``` - ### close close(): void @@ -393,12 +413,13 @@ Closes this result set. **System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core **Example** + ```js - let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE") - let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]) + let predicatesClose = new dataRdb.RdbPredicates("EMPLOYEE"); + let promiseClose = rdbStore.query(predicatesClose, ["ID", "NAME", "AGE", "SALARY", "CODES"]); promiseClose.then((resultSet) { - resultSet.close() + resultSet.close(); }).catch((err) => { - console.log('Failed to close resultset') - }) + console.log('Failed to close resultset'); + }); ``` diff --git a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 81ee6f74b796de60b190f06b3f2a8a719f8569c3..382806418cb94f0e7be4a7c31a3feded938fee38 100644 --- a/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/en/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -41,7 +41,7 @@ Checks whether the application specified by **bundleName** is in the idle state. | Name | Type | Mandatory | Description | | ---------- | ---------------------------- | ---- | ---------------------------------------- | | bundleName | string | Yes | Bundle name of an application. | -| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. If the value of bundleName is valid, null will be returned.| +| callback | AsyncCallback<boolean> | Yes | Callback used to return the result. Returns the idle state of the application if the specified **bundleName** is valid; returns **null** otherwise.| **Example** @@ -73,7 +73,7 @@ Checks whether the application specified by **bundleName** is in the idle state. | Type | Description | | ---------------------- | ---------------------------------------- | -| Promise<boolean> | Promise used to return the result. If the value of **bundleName** is valid, **null** will be returned.| +| Promise<boolean> | Promise used to return the result. Returns the idle state of the application if the specified **bundleName** is valid; returns **null** otherwise.| **Example** @@ -275,7 +275,7 @@ Queries the application usage duration statistics in the specified time frame at | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| Promise<Array<[BundleStateInfo](#bundlestateinfo)>> | Promise used to return the result.| +| Promise<Array<[BundleStateInfo](#bundlestateinfo)>> | Promise used to return the result. | **Example** @@ -309,7 +309,7 @@ Queries events of all applications based on the specified start time and end tim | -------- | ---------------------------------------- | ---- | --------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result. | **Example** @@ -350,7 +350,7 @@ Queries events of all applications based on the specified start time and end tim | Type | Description | | ---------------------------------------- | -------------------------------------- | -| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result. | **Example** @@ -380,7 +380,7 @@ Queries events of this application based on the specified start time and end tim | -------- | ---------------------------------------- | ---- | --------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | Yes | Callback used to return the result. | **Example** @@ -417,7 +417,7 @@ Queries events of this application based on the specified start time and end tim | Type | Description | | ---------------------------------------- | -------------------------------------- | -| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveState](#bundleactivestate)>> | Promise used to return the result. | **Example** @@ -455,7 +455,7 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses a | Type | Description | | ---------------------------------------- | ---------------------------------- | -| Promise<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Promise used to return the result. | **Example** @@ -486,7 +486,7 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses a getRecentlyUsedModules(callback: AsyncCallback<Array<BundleActiveModuleInfo>>): void -This API uses an asynchronous callback to return at most 1000 records sorted by time (most recent first). +Obtains FA usage records. This API uses an asynchronous callback to return a maximum of 1000 FA usage records sorted by time in descending order. **Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO @@ -498,7 +498,7 @@ This API uses an asynchronous callback to return at most 1000 records sorted by | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result. | **Example** @@ -532,8 +532,8 @@ Obtains the number of FA usage records specified by **maxNum**. This API uses an | Name | Type | Mandatory | Description | | -------- | ---------------------------------------- | ---- | ----------------------------------- | -| maxNum | number | Yes | Maximum number of returned records. The maximum and default value is **1000**.| -| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result.| +| maxNum | number | Yes | Maximum number of returned records. The maximum value is **1000**.| +| callback | AsyncCallback<Array<[BundleActiveModuleInfo](#bundleactivemoduleinfo9)>> | Yes | Callback used to return the result. | **Example** @@ -578,14 +578,14 @@ Queries the priority group of the application specified by **bundleName**. If ** **Example** ```javascript -// Promise with bundleName +// Promise mode when bundleName is specified let bundleName = "com.ohos.camera"; bundleState.queryAppUsagePriorityGroup(bundleName).then( res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( err => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise failed. because: ' + err.code); }); -// Promise without bundleName +// Promise mode when bundleName is not specified bundleState.queryAppUsagePriorityGroup().then( res => { console.log('BUNDLE_ACTIVE QueryPackageGroup promise succeeded. result: ' + JSON.stringify(res)); }).catch( err => { @@ -597,7 +597,7 @@ bundleState.queryAppUsagePriorityGroup().then( res => { queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void -Queries the priority group of the current application . This API uses an asynchronous callback to return the result. +Queries the priority group of this application. This API uses an asynchronous callback to return the result. **Required permissions**: ohos.permission.BUNDLE_ACTIVE_INFO @@ -609,7 +609,7 @@ Queries the priority group of the current application . This API uses an asynchr | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------------------------------------- | -| callback | AsyncCallback<number> | Yes | Callback used to return the result. | +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | **Example** @@ -639,8 +639,8 @@ Queries the priority group of the application specified by **bundleName**. This | Name | Type | Mandatory | Description | | ---------- | --------------------- | ---- | ---------------------------------------- | -| bundleName | string | Yes | Bundle name of the target application.| -| callback | AsyncCallback<number> | Yes | Callback used to return the result. | +| bundleName | string | Yes | Bundle name of the target application.| +| callback | AsyncCallback<number> | Yes | Callback used to return the result. | **Example** @@ -678,7 +678,7 @@ Sets the group for the application specified by **bundleName**. This API uses a | Type | Description | | ------------- | ------------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result. | **Example** @@ -711,7 +711,7 @@ Sets the group for the application specified by **bundleName**. This API uses an | ---------- | ------------------- | ---- | ------------------------- | | bundleName | string | Yes | Bundle name of an application. | | newGroup | [GroupType](#grouptype) | Yes | Application group. | -| callback | AsyncCallback<void> | Yes | Callback used to return the result.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | **Example** @@ -750,7 +750,7 @@ Registers a callback for application group changes. When an application group of | Type | Description | | ------------- | ----------------------- | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result. | **Example** @@ -827,7 +827,7 @@ Deregisters the callback for application group changes. This API uses a promise | Type | Description | | ------------- | ------------------------ | -| Promise<void> | Promise used to return the result.| +| Promise<void> | Promise used to return the result. | **Example** @@ -892,7 +892,7 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result. | **Example** @@ -923,7 +923,7 @@ Queries statistics about system events (hibernation, wakeup, unlocking, and scre | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result. | **Example** @@ -961,7 +961,7 @@ Queries the number of notifications from all applications based on the specified | Type | Description | | ---------------------------------------- | ---------------------------------------- | -| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result.| +| Promise<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Promise used to return the result. | **Example** @@ -992,7 +992,7 @@ Queries the number of notifications from all applications based on the specified | -------- | ---------------------------------------- | ---- | ---------------------------------------- | | begin | number | Yes | Start time. | | end | number | Yes | End time. | -| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result.| +| callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | Yes | Callback used to return the result. | **Example** @@ -1012,6 +1012,8 @@ Provides the information about the FA usage. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Mandatory | Description | | -------------------- | ---------------------------------------- | ---- | ----------------------------- | | deviceId | string | No | ID of the device to which the FA belongs. | @@ -1033,6 +1035,8 @@ Provides the FA widget usage information. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.App +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Mandatory | Description | | ---------------- | ------ | ---- | ----------- | | formName | string | Yes | Widget name. | @@ -1047,6 +1051,8 @@ Provides the application group changes returned through a callback. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Type | Mandatory| Description | | ---------------- | ------ | ---- | ---------------- | | appUsageOldGroup | number | Yes | Application group before the change.| @@ -1135,6 +1141,8 @@ Enumerates the application group types. **System capability**: SystemCapability.ResourceSchedule.UsageStatistics.AppGroup +**System API**: This is a system API and cannot be called by third-party applications. + | Name | Default Value | Description | | ------------------ | ---- | ----------------- | | ACTIVE_GROUP_ALIVE | 10 | Group of active applications. | diff --git a/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md b/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md index 3158ba2e321cc4c609c70d4ec8ba402c7290b4a4..ce89c3498f39deffd41ccb5ffd318b7cecef8c6f 100644 --- a/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md +++ b/en/application-dev/reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md @@ -24,7 +24,7 @@ enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { ## DeviceSettingsManager.setDateTime -setDateTime(admin: Want, time: number, callback: AsyncCallback): void +setDateTime(admin: Want, time: number, callback: AsyncCallback\): void Sets the system time. This API uses an asynchronous callback to return the result. @@ -38,7 +38,7 @@ Sets the system time. This API uses an asynchronous callback to return the resul | ----- | ----------------------------------- | ---- | ------- | | admin | [Want](js-apis-application-Want.md) | Yes | Device administrator application.| | time | number | Yes| Timestamp (ms).| -| callback | AsyncCallback | Yes| Callback used to the result. If the system time is set successfully, **err** is **null**; otherwise, **err** is an error object.| +| callback | AsyncCallback\ | Yes| Callback used to the result. If the system time is set successfully, **err** is **null**; otherwise, **err** is an error object.| **Example** @@ -64,7 +64,7 @@ enterpriseDeviceManager.getDeviceSettingsManager((error, mgr) => { ## DeviceSettingsManager.setDateTime -setDateTime(admin: Want, time: number): Promise +setDateTime(admin: Want, time: number): Promise\ Sets the system time. This API uses a promise to return the result. @@ -83,8 +83,7 @@ Sets the system time. This API uses a promise to return the result. | Type | Description | | ----- | ----------------------------------- | -| Promise | Promise that returns no value.| - +| Promise\ | Promise that returns no value.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-fileio.md b/en/application-dev/reference/apis/js-apis-fileio.md index 4d3791fd26788b92c136c32df7f298787f887f3d..8a55647849f7b2633a7b69e6fc5ff49f4a20f1e6 100644 --- a/en/application-dev/reference/apis/js-apis-fileio.md +++ b/en/application-dev/reference/apis/js-apis-fileio.md @@ -1,6 +1,6 @@ # File Management -The fileio module provides APIs for file storage and management, including basic file management, directory management, file information statistics, and stream read and write. +The **fileio** module provides APIs for file storage and management, including basic file management, directory management, file information statistics, and stream read and write. > **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -24,7 +24,7 @@ import Ability from '@ohos.application.Ability'; class MainAbility extends Ability { onWindowStageCreate(windowStage) { let context = this.context; - let path = context.filesDir; + let pathDir = context.filesDir; } } ``` @@ -37,7 +37,7 @@ FA Model import featureAbility from '@ohos.ability.featureAbility'; let context = featureAbility.getContext(); context.getFilesDir().then((data) => { - let path = data; + let pathDir = data; }) ``` @@ -66,7 +66,8 @@ Obtains file information. This API uses a promise to return the result. **Example** ```js - fileio.stat(path).then(function(stat){ + let filePath = pathDir + "test.txt"; + fileio.stat(filePath).then(function(stat){ console.info("Got file info:"+ JSON.stringify(stat)); }).catch(function(err){ console.info("Failed to get file info. Error:"+ err); @@ -76,7 +77,7 @@ Obtains file information. This API uses a promise to return the result. ## fileio.stat -stat(path:string, callback:AsyncCallback<Stat>): void +stat(path: string, callback: AsyncCallback<Stat>): void Obtains file information. This API uses an asynchronous callback to return the result. @@ -92,7 +93,7 @@ Obtains file information. This API uses an asynchronous callback to return the r **Example** ```js - fileio.stat(path, function (err, stat) { + fileio.stat(pathDir, function (err, stat) { // Example code in Stat }); ``` @@ -100,7 +101,7 @@ Obtains file information. This API uses an asynchronous callback to return the r ## fileio.statSync -statSync(path:string): Stat +statSync(path: string): Stat Synchronously obtains file information. @@ -122,7 +123,7 @@ Synchronously obtains file information. **Example** ```js - let stat = fileio.statSync(path); + let stat = fileio.statSync(pathDir); // Example code in Stat ``` @@ -150,7 +151,8 @@ Opens a file directory. This API uses a promise to return the result. **Example** ```js - fileio.opendir(path).then(function(dir){ + let dirPath = pathDir + "/testDir"; + fileio.opendir(dirPath).then(function(dir){ console.info("Directory opened:"+ JSON.stringify(dir)); }).catch(function(err){ console.info("Failed to open the directory. Error:"+ err); @@ -176,7 +178,7 @@ Opens a file directory. This API uses an asynchronous callback to return the res **Example** ```js - fileio.opendir(path, function (err, dir) { + fileio.opendir(pathDir, function (err, dir) { // Example code in Dir struct // Use read/readSync/close. }); @@ -207,7 +209,7 @@ Synchronously opens a directory. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); // Example code in Dir struct // Use read/readSync/close. ``` @@ -237,7 +239,8 @@ Checks whether the current process can access a file. This API uses a promise to **Example** ```js - fileio.access(path).then(function() { + let filePath = pathDir + "/test.txt"; + fileio.access(filePath).then(function() { console.info("Access successful"); }).catch(function(err){ console.info("Access failed. Error:"+ err); @@ -264,7 +267,8 @@ Checks whether the current process can access a file. This API uses an asynchron **Example** ```js - fileio.access(path, function (err) { + let filePath = pathDir + "/test.txt"; + fileio.access(filePath, function (err) { // Do something. }); ``` @@ -288,17 +292,18 @@ Synchronously checks whether the current process can access the specified file. **Example** ```js + let filePath = pathDir + "/test.txt"; try { - fileio.accessSync(path); + fileio.accessSync(filePath); } catch(err) { - console.info("accessSync failed. Error:"+ err); + console.info("accessSync failed with error:"+ err); } ``` ## fileio.close7+ -close(fd: number):Promise<void> +close(fd: number): Promise<void> Closes a file. This API uses a promise to return the result. @@ -319,7 +324,8 @@ Closes a file. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.close(fd).then(function(){ console.info("File closed"); }).catch(function(err){ @@ -330,7 +336,7 @@ Closes a file. This API uses a promise to return the result. ## fileio.close7+ -close(fd: number, callback:AsyncCallback<void>): void +close(fd: number, callback: AsyncCallback<void>): void Closes a file. This API uses an asynchronous callback to return the result. @@ -346,7 +352,8 @@ Closes a file. This API uses an asynchronous callback to return the result. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.close(fd, function (err) { // Do something. }); @@ -370,14 +377,15 @@ Synchronously closes a file. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.closeSync(fd); ``` ## fileio.copyFile -copyFile(src:string | number, dest:string | number, mode?:number):Promise<void> +copyFile(src: string | number, dest: string | number, mode?: number): Promise<void> Copies a file. This API uses a promise to return the result. @@ -400,9 +408,9 @@ Copies a file. This API uses a promise to return the result. **Example** ```js - let src = path; - let dest = src + 'tgt'; - fileio.copyFile(src, dest).then(function(){ + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fileio.copyFile(srcPath, dstPath).then(function(){ console.info("File copied"); }).catch(function(err){ console.info("Failed to copy the file. Error:"+ err); @@ -430,9 +438,9 @@ Copies a file. This API uses an asynchronous callback to return the result. **Example** ```js - let src = path; - let dest = src + 'tgt'; - fileio.copyFile(src, dest, function (err) { + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fileio.copyFile(srcPath, dstPath, function (err) { // Do something. }); ``` @@ -457,15 +465,15 @@ Synchronously copies a file. **Example** ```js - let src = path; - let dest = src + 'tgt'; - fileio.copyFileSync(src, dest); + let srcPath = pathDir + "srcDir/test.txt"; + let dstPath = pathDir + "dstDir/test.txt"; + fileio.copyFileSync(srcPath, dstPath); ``` ## fileio.mkdir -mkdir(path:string, mode?: number): Promise<void> +mkdir(path: string, mode?: number): Promise<void> Creates a directory. This API uses a promise to return the result. @@ -487,7 +495,8 @@ Creates a directory. This API uses a promise to return the result. **Example** ```js - fileio.mkdir(path).then(function() { + let dirPath = pathDir + '/testDir'; + fileio.mkdir(dirPath).then(function() { console.info("Directory created"); }).catch(function (error){ console.info("Failed to create the directory. Error:"+ error); @@ -514,7 +523,8 @@ Creates a directory. This API uses an asynchronous callback to return the result **Example** ```js - fileio.mkdir(path, function(err) { + let dirPath = pathDir + '/testDir'; + fileio.mkdir(dirPath, function(err) { console.info("Directory created"); }); ``` @@ -538,7 +548,8 @@ Synchronously creates a directory. **Example** ```js - fileio.mkdirSync(path); + let dirPath = path + '/testDir'; + fileio.mkdirSync(dirPath); ``` @@ -567,7 +578,8 @@ Opens a file. This API uses a promise to return the result. **Example** ```js - fileio.open(path, 0o1, 0o0200).then(function(number){ + let filePath = pathDir + "/test.txt"; + fileio.open(filePath, 0o1, 0o0200).then(function(number){ console.info("File opened"); }).catch(function(err){ console.info("Failed to open the file. Error:"+ err); @@ -588,14 +600,15 @@ Opens a file. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | | path | string | Yes | Application sandbox path of the file. | -| flags | number | Yes | Option for opening the file. You must specify one of the following options. By default, the file is open in read-only mode.
- **0o0**: Open the file in read-only mode.
- **0o1**: Open the file in write-only mode.
- **0o2**: Open the file in read/write mode.
In addition, you can specify the following options, separated using a bitwise OR operator (|). By default, no additional option is specified.
- **0o100**: If the file does not exist, create it. If you use this option, you must also specify **mode**.
- **0o200**: If **0o100** is added and the file already exists, throw an exception.
- **0o1000**: If the file exists and is open in write-only or read/write mode, truncate the file length to 0.
- **0o2000**: Open the file in append mode. New data will be appended to the file (added to the end of the file).
- **0o4000**: If **path** points to a named pipe (also known as a FIFO), block special file, or character special file, perform non-blocking operations on the open file and in subsequent I/Os.
- **0o200000**: If **path** does not point to a directory, throw an exception.

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

- **0o400000**: If **path** points to a symbolic link, throw an exception.
- **0o4010000**: Open the file in synchronous I/O mode.| +| mode | number | No | Permissions on the file. You can specify multiple permissions, separated using a bitwise OR operator (|). The default value is **0o666**.
- **0o666**: The owner, user group, and other users have the read and write permissions on the file.
- **0o700**: The owner has the read, write, and execute permissions.
-  **0o400**: The owner has the read permission.
- **0o200**: The owner has the write permission.
- **0o100**: The owner has the execute permission.
- **0o070**: The user group has the read, write, and execute permissions.
- **0o040**: The user group has the read permission.
- **0o020**: The user group has the write permission.
- **0o010**: The user group has the execute permission.
- **0o007**: Other users have the read, write, and execute permissions.
- **0o004**: Other users have the read permission.
- **0o002**: Other users have the write permission.
- **0o001**: Other users have the execute permission.| | callback | AsyncCallback <void> | Yes | Callback invoked when the file is open asynchronously. | **Example** ```js - fileio.open(path, 0, function(err, fd) { + let filePath = pathDir + "/test.txt"; + fileio.open(filePath, 0, function(err, fd) { // Do something. }); ``` @@ -603,7 +616,7 @@ Opens a file. This API uses an asynchronous callback to return the result. ## fileio.openSync -openSync(path:string, flags?:number, mode?:number): number +openSync(path: string, flags?: number, mode?: number): number Synchronously opens a file. @@ -626,12 +639,14 @@ Synchronously opens a file. **Example** ```js - let fd = fileio.openSync(path, 0o102, 0o640); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o102, 0o640); ``` ```js - let fd = fileio.openSync(path, 0o102, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o102, 0o666); fileio.writeSync(fd, 'hello world'); - let fd1 = fileio.openSync(path, 0o2002); + let fd1 = fileio.openSync(filePath, 0o2002); fileio.writeSync(fd1, 'hello world'); let num = fileio.readSync(fd1, new ArrayBuffer(4096), {position: 0}); console.info("num == " + num); @@ -667,7 +682,8 @@ Reads data from a file. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path, 0o2); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o2); let buf = new ArrayBuffer(4096); fileio.read(fd, buf).then(function(readOut){ console.info("Read file data successfully"); @@ -702,7 +718,8 @@ Reads data from a file. This API uses an asynchronous callback to return the res **Example** ```js - let fd = fileio.openSync(path, 0o2); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o2); let buf = new ArrayBuffer(4096); fileio.read(fd, buf, function (err, readOut) { if (readOut) { @@ -742,7 +759,8 @@ Synchronously reads data from a file. **Example** ```js - let fd = fileio.openSync(path, 0o2); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o2); let buf = new ArrayBuffer(4096); let num = fileio.readSync(fd, buf); ``` @@ -771,7 +789,8 @@ Deletes a directory. This API uses a promise to return the result. **Example** ```js - fileio.rmdir(path).then(function() { + let dirPath = pathDir + '/testDir'; + fileio.rmdir(dirPath).then(function() { console.info("Directory deleted"); }).catch(function(err){ console.info("Failed to delete the directory. Error:"+ err); @@ -781,7 +800,7 @@ Deletes a directory. This API uses a promise to return the result. ## fileio.rmdir7+ -rmdir(path: string, callback:AsyncCallback<void>): void +rmdir(path: string, callback: AsyncCallback<void>): void Deletes a directory. This API uses an asynchronous callback to return the result. @@ -797,7 +816,8 @@ Deletes a directory. This API uses an asynchronous callback to return the result **Example** ```js - fileio.rmdir(path, function(err){ + let dirPath = pathDir + '/testDir'; + fileio.rmdir(dirPath, function(err){ // Do something. console.info("Directory deleted"); }); @@ -821,13 +841,14 @@ Synchronously deletes a directory. **Example** ```js - fileio.rmdirSync(path); + let dirPath = pathDir + '/testDir'; + fileio.rmdirSync(dirPath); ``` ## fileio.unlink -unlink(path:string): Promise<void> +unlink(path: string): Promise<void> Deletes a file. This API uses a promise to return the result. @@ -848,7 +869,8 @@ Deletes a file. This API uses a promise to return the result. **Example** ```js - fileio.unlink(path).then(function(){ + let filePath = pathDir + "/test.txt"; + fileio.unlink(filePath).then(function(){ console.info("File deleted"); }).catch(function(error){ console.info("Failed to delete the file. Error:"+ error); @@ -858,7 +880,7 @@ Deletes a file. This API uses a promise to return the result. ## fileio.unlink -unlink(path:string, callback:AsyncCallback<void>): void +unlink(path: string, callback: AsyncCallback<void>): void Deletes a file. This API uses an asynchronous callback to return the result. @@ -874,7 +896,8 @@ Deletes a file. This API uses an asynchronous callback to return the result. **Example** ```js - fileio.unlink(path, function(err) { + let filePath = pathDir + "/test.txt"; + fileio.unlink(filePath, function(err) { console.info("File deleted"); }); ``` @@ -897,7 +920,8 @@ Synchronously deletes a file. **Example** ```js - fileio.unlinkSync(path); + let filePath = pathDir + "/test.txt"; + fileio.unlinkSync(filePath); ``` @@ -931,7 +955,8 @@ Writes data into a file. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world").then(function(number){ console.info("Data written to the file. Size is:"+ number); }).catch(function(err){ @@ -965,7 +990,8 @@ Writes data into a file. This API uses an asynchronous callback to return the re **Example** ```js - let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); fileio.write(fd, "hello, world", function (err, bytesWritten) { if (bytesWritten) { console.info("Data written to the file. Size is:"+ bytesWritten); @@ -1004,7 +1030,8 @@ Synchronously writes data into a file. **Example** ```js - let fd = fileio.openSync(path, 0o100 | 0o2, 0o666); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath, 0o100 | 0o2, 0o666); let num = fileio.writeSync(fd, "hello, world"); ``` @@ -1033,7 +1060,8 @@ Calculates the hash value of a file. This API uses a promise to return the resul **Example** ```js - fileio.hash(path, "sha256").then(function(str){ + let filePath = pathDir + "/test.txt"; + fileio.hash(filePath, "sha256").then(function(str){ console.info("Calculated file hash:"+ str); }).catch(function(err){ console.info("Failed to calculate the file hash. Error:"+ err); @@ -1060,7 +1088,8 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r **Example** ```js - fileio.hash(path, "sha256", function(err, hashStr) { + let filePath = pathDir + "/test.txt"; + fileio.hash(filePath, "sha256", function(err, hashStr) { if (hashStr) { console.info("Calculated file hash:"+ hashStr); } @@ -1070,7 +1099,7 @@ Calculates the hash value of a file. This API uses an asynchronous callback to r ## fileio.chmod7+ -chmod(path: string, mode: number):Promise<void> +chmod(path: string, mode: number): Promise<void> Changes file permissions. This API uses a promise to return the result. @@ -1092,7 +1121,8 @@ Changes file permissions. This API uses a promise to return the result. **Example** ```js - fileio.chmod(path, 0o700).then(function() { + let filePath = pathDir + "/test.txt"; + fileio.chmod(filePath, 0o700).then(function() { console.info("File permissions changed"); }).catch(function(err){ console.info("Failed to change file permissions. Error:"+ err); @@ -1119,7 +1149,8 @@ Changes file permissions. This API uses an asynchronous callback to return the r **Example** ```js - fileio.chmod(path, 0o700, function (err) { + let filePath = pathDir + "/test.txt"; + fileio.chmod(filePath, 0o700, function (err) { // Do something. }); ``` @@ -1143,7 +1174,8 @@ Synchronously changes file permissions. **Example** ```js - fileio.chmodSync(path, 0o700); + let filePath = pathDir + "/test.txt"; + fileio.chmodSync(filePath, 0o700); ``` @@ -1170,7 +1202,8 @@ Obtains file information based on the file descriptor. This API uses a promise t **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fstat(fd).then(function(stat){ console.info("Obtained file info:"+ JSON.stringify(stat)); }).catch(function(err){ @@ -1197,7 +1230,8 @@ Obtains file information based on the file descriptor. This API uses an asynchro **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fstat(fd, function (err) { // Do something. }); @@ -1227,7 +1261,8 @@ Synchronously obtains file information based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let stat = fileio.fstatSync(fd); ``` @@ -1256,7 +1291,8 @@ Truncates a file based on the file descriptor. This API uses a promise to return **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.ftruncate(fd, 5).then(function(err) { console.info("File truncated"); }).catch(function(err){ @@ -1267,7 +1303,7 @@ Truncates a file based on the file descriptor. This API uses a promise to return ## fileio.ftruncate7+ -ftruncate(fd: number, len: number, callback:AsyncCallback<void>): void +ftruncate(fd: number, len: number, callback: AsyncCallback<void>): void Truncates a file based on the file descriptor. This API uses an asynchronous callback to return the result. @@ -1278,13 +1314,14 @@ Truncates a file based on the file descriptor. This API uses an asynchronous cal | Name | Type | Mandatory | Description | | -------- | ------------------------- | ---- | ---------------- | | fd | number | Yes | File descriptor of the file to truncate. | - | len | number | Yes | File length, in bytes, after truncation.| - | callback | AsyncCallback<void> | Yes | Callback that returns no value.| + | len | number | No | File length, in bytes, after truncation.| + | callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let len = 5; fileio.ftruncate(fd, 5, function(err){ // Do something. @@ -1310,7 +1347,8 @@ Synchronously truncates a file based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let len = 5; fileio.ftruncateSync(fd, len); ``` @@ -1340,8 +1378,9 @@ Truncates a file based on the file path. This API uses a promise to return the r **Example** ```js + let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncate(path, len).then(function(){ + fileio.truncate(filePath, len).then(function(){ console.info("File truncated"); }).catch(function(err){ console.info("Failed to truncate the file. Error:"+ err); @@ -1351,7 +1390,7 @@ Truncates a file based on the file path. This API uses a promise to return the r ## fileio.truncate7+ -truncate(path: string, len: number, callback:AsyncCallback<void>): void +truncate(path: string, len: number, callback: AsyncCallback<void>): void Truncates a file based on the file path. This API uses an asynchronous callback to return the result. @@ -1362,14 +1401,15 @@ Truncates a file based on the file path. This API uses an asynchronous callback | Name | Type | Mandatory| Description | | -------- | ------------------------- | ---- | -------------------------------- | | path | string | Yes | Application sandbox path of the file to truncate.| -| len | number | Yes | File length, in bytes, after truncation.| -| callback | AsyncCallback<void> | Yes | Callback that returns no value.| +| len | number | No | File length, in bytes, after truncation.| +| callback | AsyncCallback<void> | Yes | Callback that returns no value. | **Example** ```js + let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncate(path, len, function(err){ + fileio.truncate(filePath, len, function(err){ // Do something. }); ``` @@ -1393,8 +1433,9 @@ Synchronously truncates a file based on the file path. **Example** ```js + let filePath = pathDir + "/test.txt"; let len = 5; - fileio.truncateSync(path, len); + fileio.truncateSync(filePath, len); ``` @@ -1426,7 +1467,8 @@ Reads the text content of a file. This API uses a promise to return the result. **Example** ```js - fileio.readText(path).then(function(str) { + let filePath = pathDir + "/test.txt"; + fileio.readText(filePath).then(function(str) { console.info("Read text successfully:"+ str); }).catch(function(err){ console.info("Failed to read the text. Error:"+ err); @@ -1451,13 +1493,14 @@ Reads the text content of a file. This API uses an asynchronous callback to retu | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | | filePath | string | Yes | Application sandbox path of the file to read. | -| options | Object | Yes | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
-  **encoding**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| +| options | Object | No | The options are as follows:
- **position** (number): position of the data to read in the file. By default, data is read from the current position.
- **length** (number): length of the data to read. The default value is the buffer length minus the offset.
-  **encoding**: format of the string to be encoded. The default value is  **utf-8**, which is the only value supported.| | callback | AsyncCallback<string> | Yes | Callback used to return the content read. | **Example** ```js - fileio.readText(path, { position: 1, encoding: 'UTF-8' }, function(err, str){ + let filePath = pathDir + "/test.txt"; + fileio.readText(filePath, { position: 1, encoding: 'UTF-8' }, function(err, str){ // Do something. }); ``` @@ -1491,7 +1534,8 @@ Synchronously reads the text of a file. **Example** ```js - let str = fileio.readTextSync(path, {position: 1, length: 3}); + let filePath = pathDir + "/test.txt"; + let str = fileio.readTextSync(filePath, {position: 1, length: 3}); ``` @@ -1518,8 +1562,9 @@ Obtains link information. This API uses a promise to return the result. **Example** ```js - fileio.lstat(path).then(function(stat){ - console.info("Got link info:"+ JSON.stringify(stat)); + let filePath = pathDir + "/test.txt"; + fileio.lstat(filePath).then(function(stat){ + console.info("Get link info:"+ JSON.stringify(stat)); }).catch(function(err){ console.info("Failed to obtain link info. Error:"+ err); }); @@ -1528,7 +1573,7 @@ Obtains link information. This API uses a promise to return the result. ## fileio.lstat7+ -lstat(path:string, callback:AsyncCallback<Stat>): void +lstat(path: string, callback: AsyncCallback<Stat>): void Obtains link information. This API uses an asynchronous callback to return the result. @@ -1544,7 +1589,8 @@ Obtains link information. This API uses an asynchronous callback to return the r **Example** ```js - fileio.lstat(path, function (err, stat) { + let filePath = pathDir + "/test.txt"; + fileio.lstat(filePath, function (err, stat) { // Do something. }); ``` @@ -1552,7 +1598,7 @@ Obtains link information. This API uses an asynchronous callback to return the r ## fileio.lstatSync7+ -lstatSync(path:string): Stat +lstatSync(path: string): Stat Synchronously obtains the link information. @@ -1573,7 +1619,8 @@ Synchronously obtains the link information. **Example** ```js - let stat = fileio.lstatSync(path); + let filePath = pathDir + "/test.txt"; + let stat = fileio.lstatSync(filePath); ``` @@ -1601,9 +1648,9 @@ Renames a file. This API uses a promise to return the result. **Example** ```js - let oldPath = path; - let newPath = oldPath + '123'; - fileio.rename(oldPath, newPath).then(function() { + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fileio.rename(srcFile, dstFile).then(function() { console.info("File renamed"); }).catch(function(err){ console.info("Failed to rename the file. Error:"+ err); @@ -1630,9 +1677,9 @@ Renames a file. This API uses an asynchronous callback to return the result. **Example** ```js - let oldPath = path; - let newPath = oldPath + '123'; - fileio.rename(oldPath, newPath, function(err){ + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fileio.rename(srcFile, dstFile, function(err){ }); ``` @@ -1655,9 +1702,9 @@ Synchronously renames a file. **Example** ```js - let oldPath = path; - let newPath = oldPath + '123'; - fileio.renameSync(oldPath, newPath); + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/new.txt'; + fileio.renameSync(srcFile, dstFile); ``` @@ -1684,7 +1731,8 @@ Flushes data of a file to disk. This API uses a promise to return the result. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fsync(fd).then(function(){ console.info("Data flushed"); }).catch(function(err){ @@ -1711,7 +1759,8 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fsync(fd, function(err){ // Do something. }); @@ -1735,7 +1784,8 @@ Flushes data of a file to disk in synchronous mode. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fsyncSync(fd); ``` @@ -1763,7 +1813,8 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdatasync(fd).then(function(err) { console.info("Data flushed"); }).catch(function(err){ @@ -1774,7 +1825,7 @@ Flushes data of a file to disk. This API uses a promise to return the result. ** ## fileio.fdatasync7+ -fdatasync(fd: number, callback:AsyncCallback<void>): void +fdatasync(fd: number, callback: AsyncCallback<void>): void Flushes data of a file to disk. This API uses an asynchronous callback to return the result. @@ -1790,7 +1841,8 @@ Flushes data of a file to disk. This API uses an asynchronous callback to return **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdatasync (fd, function (err) { // Do something. }); @@ -1814,7 +1866,8 @@ Synchronizes data in a file in synchronous mode. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let stat = fileio.fdatasyncSync(fd); ``` @@ -1843,9 +1896,9 @@ Creates a symbolic link based on the file path. This API uses a promise to retur **Example** ```js - let target = path; - let srcPath = target + 'aaa'; - fileio.symlink(target, srcPath).then(function() { + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fileio.symlink(srcFile, dstFile).then(function() { console.info("Symbolic link created"); }).catch(function(err){ console.info("Failed to create the symbolic link. Error:"+ err); @@ -1872,9 +1925,9 @@ Creates a symbolic link based on the file path. This API uses an asynchronous ca **Example** ```js - let target = path; - let srcPath = target + 'aaa'; - fileio.symlink(target, srcPath, function (err) { + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fileio.symlink(srcFile, dstFile, function (err) { // Do something. }); ``` @@ -1898,9 +1951,9 @@ Synchronously creates a symbolic link based on a specified path. **Example** ```js - let target = path; - let srcPath = target + 'aaa'; - fileio.symlinkSync(target, srcPath); + let srcFile = pathDir + "/test.txt"; + let dstFile = pathDir + '/test'; + fileio.symlinkSync(srcFile, dstFile); ``` @@ -1929,8 +1982,9 @@ Changes the file owner based on the file path. This API uses a promise to return **Example** ```js - let stat = fileio.statSync(path); - fileio.chown(path, stat.uid, stat.gid).then(function(){ + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.chown(filePath, stat.uid, stat.gid).then(function(){ console.info("File owner changed"); }).catch(function(err){ console.info("Failed to change the file owner. Error:"+ err); @@ -1958,8 +2012,9 @@ Changes the file owner based on the file path. This API uses an asynchronous cal **Example** ```js - let stat = fileio.statSync(path) - fileio.chown(path, stat.uid, stat.gid, function (err){ + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath) + fileio.chown(filePath, stat.uid, stat.gid, function (err){ // Do something. }); ``` @@ -1984,8 +2039,9 @@ Synchronously changes the file owner based on its path. **Example** ```js - let stat = fileio.statSync(path) - fileio.chownSync(path, stat.uid, stat.gid); + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath) + fileio.chownSync(filePath, stat.uid, stat.gid); ``` @@ -2012,8 +2068,8 @@ Creates a temporary directory. This API uses a promise to return the result. **Example** ```js - fileio.mkdtemp(path + "XXXX").then(function(path){ - console.info("Temporary directory created:"+ path); + fileio.mkdtemp(pathDir + "/XXXXXX").then(function(pathDir){ + console.info("mkdtemp succeed:"+ pathDir); }).catch(function(err){ console.info("Failed to create the temporary directory. Error:"+ err); }); @@ -2038,7 +2094,7 @@ Creates a temporary directory. This API uses an asynchronous callback to return **Example** ```js - fileio.mkdtemp(path + "XXXX", function (err, res) { + fileio.mkdtemp(pathDir + "/XXXXXX", function (err, res) { // Do something. }); ``` @@ -2067,7 +2123,7 @@ Synchronously creates a temporary directory. **Example** ```js - let res = fileio.mkdtempSync(path + "XXXX"); + let res = fileio.mkdtempSync(pathDir + "/XXXXXX"); ``` @@ -2095,7 +2151,8 @@ Changes file permissions based on the file descriptor. This API uses a promise t **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let mode = 0o700; fileio.fchmod(fd, mode).then(function() { console.info("File permissions changed"); @@ -2124,7 +2181,8 @@ Changes file permissions based on the file descriptor. This API uses an asynchro **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let mode = 0o700; fileio.fchmod(fd, mode, function (err) { // Do something. @@ -2150,7 +2208,8 @@ Synchronously changes the file permissions based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let mode = 0o700; fileio.fchmodSync(fd, mode); ``` @@ -2180,8 +2239,9 @@ Opens a file stream based on the file path. This API uses a promise to return th **Example** ```js - fileio.createStream(path, "r+").then(function(stream){ - console.info("Stream opened"); + let filePath = pathDir + "/test.txt"; + fileio.createStream(filePath, "r+").then(function(stream){ + console.info("Stream created"); }).catch(function(err){ console.info("Failed to create the stream. Error:"+ err); }); @@ -2207,7 +2267,8 @@ Opens a file stream based on the file path. This API uses an asynchronous callba **Example** ```js - fileio.createStream(path, "r+", function(err, stream){ + let filePath = pathDir + "/test.txt"; + fileio.createStream(filePath, "r+", function(err, stream){ // Do something. }); ``` @@ -2237,7 +2298,8 @@ Synchronously opens a stream based on the file path. **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); ``` @@ -2265,7 +2327,8 @@ Opens a file stream based on the file descriptor. This API uses a promise to ret **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdopenStream(fd, "r+").then(function(stream){ console.info("Stream opened"); }).catch(function(err){ @@ -2293,7 +2356,8 @@ Opens a file stream based on the file descriptor. This API uses an asynchronous **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); fileio.fdopenStream(fd, "r+", function (err, stream) { // Do something. }); @@ -2324,7 +2388,8 @@ Synchronously opens a stream based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); let ss = fileio.fdopenStreamSync(fd, "r+"); ``` @@ -2354,8 +2419,9 @@ Changes the file owner based on the file descriptor. This API uses a promise to **Example** ```js - let fd = fileio.openSync(path); - let stat = fileio.statSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); + let stat = fileio.statSync(filePath); fileio.fchown(fd, stat.uid, stat.gid).then(function() { console.info("File owner changed"); }).catch(function(err){ @@ -2384,8 +2450,9 @@ Changes the file owner based on the file descriptor. This API uses an asynchrono **Example** ```js - let fd = fileio.openSync(path); - let stat = fileio.statSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); + let stat = fileio.statSync(filePath); fileio.fchown(fd, stat.uid, stat.gid, function (err){ // Do something. }); @@ -2411,8 +2478,9 @@ Synchronously changes the file owner based on the file descriptor. **Example** ```js - let fd = fileio.openSync(path); - let stat = fileio.statSync(path); + let filePath = pathDir + "/test.txt"; + let fd = fileio.openSync(filePath); + let stat = fileio.statSync(filePath); fileio.fchownSync(fd, stat.uid, stat.gid); ``` @@ -2442,8 +2510,9 @@ Changes the file owner (owner of the symbolic link, not the file referred to by **Example** ```js - let stat = fileio.statSync(path); - fileio.lchown(path, stat.uid, stat.gid).then(function() { + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.lchown(filePath, stat.uid, stat.gid).then(function() { console.info("File owner changed"); }).catch(function(err){ console.info("Failed to change the file owner. Error:"+ err); @@ -2471,8 +2540,9 @@ Changes the file owner (owner of the symbolic link, not the file referred to by **Example** ```js - let stat = fileio.statSync(path); - fileio.lchown(path, stat.uid, stat.gid, function (err){ + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.lchown(filePath, stat.uid, stat.gid, function (err){ // Do something. }); ``` @@ -2497,8 +2567,9 @@ Synchronously changes the file owner based on the file path and changes the owne **Example** ```js - let stat = fileio.statSync(path); - fileio.lchownSync(path, stat.uid, stat.gid); + let filePath = pathDir + "/test.txt"; + let stat = fileio.statSync(filePath); + fileio.lchownSync(filePath, stat.uid, stat.gid); ``` @@ -2514,7 +2585,7 @@ Listens for file or directory changes. This API uses an asynchronous callback to | Name | Type | Mandatory| Description | | -------- | --------------------------------- | ---- | ------------------------------------------------------------ | -| filename | string | Yes | Application sandbox path of the file. | +| filePath | string | Yes | Application sandbox path of the file. | | events | Number | Yes | - **1**: The file or directory is renamed.
- **2**: The file or directory is modified.
- **3**: The file or directory is modified and renamed.| | callback | AsyncCallback<number > | Yes | Called each time a change is detected. | @@ -2527,8 +2598,8 @@ Listens for file or directory changes. This API uses an asynchronous callback to **Example** ```js - let filename = path +"/test.txt"; - fileio.createWatcher(filename, 1, function(number){ + let filePath = pathDir +"/test.txt"; + fileio.createWatcher(filePath, 1, function(number){ console.info("Monitoring times: "+number); }); @@ -2589,7 +2660,8 @@ Checks whether this file is a block special file. A block special file supports **Example** ```js - let isBLockDevice = fileio.statSync(path).isBlockDevice(); + let filePath = pathDir + "/test.txt"; + let isBLockDevice = fileio.statSync(filePath).isBlockDevice(); ``` @@ -2610,7 +2682,8 @@ Checks whether this file is a character special file. A character special file s **Example** ```js - let isCharacterDevice = fileio.statSync(path).isCharacterDevice(); + let filePath = pathDir + "/test.txt"; + let isCharacterDevice = fileio.statSync(filePath).isCharacterDevice(); ``` @@ -2631,7 +2704,8 @@ Checks whether this file is a directory. **Example** ```js - let isDirectory = fileio.statSync(path).isDirectory(); + let dirPath = pathDir + "/test"; + let isDirectory = fileio.statSync(dirPath).isDirectory(); ``` @@ -2652,7 +2726,8 @@ Checks whether this file is a named pipe (or FIFO). Named pipes are used for int **Example** ```js - let isFIFO = fileio.statSync(path).isFIFO(); + let filePath = pathDir + "/test.txt"; + let isFIFO = fileio.statSync(filePath).isFIFO(); ``` @@ -2673,7 +2748,8 @@ Checks whether this file is a regular file. **Example** ```js - let isFile = fileio.statSync(path).isFile(); + let filePath = pathDir + "/test.txt"; + let isFile = fileio.statSync(filePath).isFile(); ``` @@ -2694,7 +2770,8 @@ Checks whether this file is a socket. **Example** ```js - let isSocket = fileio.statSync(path).isSocket(); + let filePath = pathDir + "/test.txt"; + let isSocket = fileio.statSync(filePath).isSocket(); ``` @@ -2715,7 +2792,8 @@ Checks whether this file is a symbolic link. **Example** ```js - let isSymbolicLink = fileio.statSync(path).isSymbolicLink(); + let filePath = pathDir + "/test"; + let isSymbolicLink = fileio.statSync(filePath).isSymbolicLink(); ``` @@ -2735,8 +2813,8 @@ Stops the **watcher** instance. This API uses a promise to return the result. **Example** ```js - let filename = path +"/test.txt"; - let watcher = fileio.createWatcher(filename, 1, function(number){ + let filePath = path + "/test.txt"; + let watcher = fileio.createWatcher(filePath, 1, function(number){ console.info("Monitoring times: "+number); }); watcher.stop().then(function(){ @@ -2762,8 +2840,8 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return **Example** ```js - let filename = path +"/test.txt"; - let watcher = fileio.createWatcher(filename, 1, function(number){ + let filePath = path +"/test.txt"; + let watcher = fileio.createWatcher(filePath, 1, function(number){ console.info("Monitoring times: "+number); }); watcher.stop(function(){ @@ -2771,6 +2849,7 @@ Stops the **watcher** instance. This API uses an asynchronous callback to return }) ``` + ## Stream Provides file stream management. Before calling a method of the **Stream** class, use the **createStream()** method synchronously or asynchronously to create a **Stream** instance. @@ -2793,7 +2872,8 @@ Closes the stream. This API uses a promise to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.close().then(function(){ console.info("File stream closed"); }).catch(function(err){ @@ -2819,9 +2899,10 @@ Closes the stream. This API uses an asynchronous callback to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.close(function (err) { - // Do something + // Do something. }); ``` @@ -2837,7 +2918,8 @@ Synchronously closes the stream. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.closeSync(); ``` @@ -2859,7 +2941,8 @@ Flushes the stream. This API uses a promise to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.flush().then(function (){ console.info("Stream flushed"); }).catch(function(err){ @@ -2885,9 +2968,10 @@ Flushes the stream. This API uses an asynchronous callback to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.flush(function (err) { - // Do something + // Do something. }); ``` @@ -2903,7 +2987,8 @@ Synchronously flushes the stream. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.flushSync(); ``` @@ -2937,7 +3022,8 @@ Writes data into the stream. This API uses a promise to return the result. **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.write("hello, world",{offset: 1,length: 5,position: 5,encoding :'utf-8'}).then(function (number){ console.info("Data written to the stream. Size is:"+ number); }).catch(function(err){ @@ -2970,10 +3056,11 @@ Writes data into the stream. This API uses an asynchronous callback to return th **Example** ```js - let ss= fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath, "r+"); ss.write("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}, function (err, bytesWritten) { if (bytesWritten) { - // Do something + // Do something. console.info("Data written to the stream. Size is:"+ bytesWritten); } }); @@ -3009,7 +3096,8 @@ Synchronously writes data into the stream. **Example** ```js - let ss= fileio.createStreamSync(path,"r+"); + let filePath = pathDir + "/test.txt"; + let ss= fileio.createStreamSync(filePath,"r+"); let num = ss.writeSync("hello, world", {offset: 1, length: 5, position: 5, encoding :'utf-8'}); ``` @@ -3042,7 +3130,8 @@ Reads data from the stream. This API uses a promise to return the result. **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); ss.read(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}).then(function (readOut){ console.info("Read data successfully"); console.log(String.fromCharCode.apply(null, new Uint8Array(readOut.buffer))); @@ -3075,7 +3164,8 @@ Reads data from the stream. This API uses an asynchronous callback to return the **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); ss.read(new ArrayBuffer(4096),{offset: 1, length: 5, position: 5},function (err, readOut) { if (readOut) { console.info("Read data successfully"); @@ -3113,7 +3203,8 @@ Synchronously reads data from the stream. **Example** ```js - let ss = fileio.createStreamSync(path, "r+"); + let filePath = pathDir + "/test.txt"; + let ss = fileio.createStreamSync(filePath, "r+"); let num = ss.readSync(new ArrayBuffer(4096), {offset: 1, length: 5, position: 5}); ``` @@ -3167,7 +3258,7 @@ Reads the next directory entry. This API uses an asynchronous callback to return ```js dir.read(function (err, dirent) { if (dirent) { - // Do something + // Do something. console.log("Read the next directory entry:"+JSON.stringify(dirent)); } }); @@ -3274,7 +3365,7 @@ Checks whether this directory entry is a block special file. A block special fil **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isBLockDevice = dir.readSync().isBlockDevice(); ``` @@ -3296,7 +3387,7 @@ Checks whether a directory entry is a character special file. A character specia **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isCharacterDevice = dir.readSync().isCharacterDevice(); ``` @@ -3318,7 +3409,7 @@ Checks whether a directory entry is a directory. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isDirectory = dir.readSync().isDirectory(); ``` @@ -3340,7 +3431,7 @@ Checks whether this directory entry is a named pipe (or FIFO). Named pipes are u **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isFIFO = dir.readSync().isFIFO(); ``` @@ -3362,7 +3453,7 @@ Checks whether a directory entry is a regular file. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isFile = dir.readSync().isFile(); ``` @@ -3384,7 +3475,7 @@ Checks whether a directory entry is a socket. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isSocket = dir.readSync().isSocket(); ``` @@ -3406,6 +3497,24 @@ Checks whether a directory entry is a symbolic link. **Example** ```js - let dir = fileio.opendirSync(path); + let dir = fileio.opendirSync(pathDir); let isSymbolicLink = dir.readSync().isSymbolicLink(); ``` + +## Filter9+ + +Defines the file filter configuration. + +**System API**: This is a system API. + +**System capability**: SystemCapability.FileManagement.File.FileIO + + +| Name | Type | Description | +| ----------- | --------------- | ------------------ | +| suffix | Array<string> | File name extensions. The keywords in the array are of the OR relationship. | +| displayName | Array<string> | File name for fuzzy match. The keywords in the array are of the OR relationship.| +| mimeType | Array<string> | MIME types to match. The keywords in the array are of the OR relationship. | +| fileSizeOver | number | File size to match. The files which are of the same or a lager size are matched. | +| lastModifiedAfter | Date | File modification time to match. The files modified after the specified time are matched. | +| excludeMedia | Boolean | Whether to exclude the files already in Media. | diff --git a/en/application-dev/reference/apis/js-apis-inputmethod.md b/en/application-dev/reference/apis/js-apis-inputmethod.md index f29975c5b4459acfd3d22e1a0f40b0579969ba24..924a6306618087d4589f5e33cf1c770e8c75c61f 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethod.md +++ b/en/application-dev/reference/apis/js-apis-inputmethod.md @@ -47,7 +47,7 @@ Obtains an **[InputMethodController](#inputmethodcontroller)** instance. | Type | Description | | ----------------------------------------------- | ------------------------ | -| [InputMethodController](#inputmethodcontroller) | Returns the current **InputMethodController** instance.| +| [InputMethodController](#inputmethodcontroller) | Current **InputMethodController** instance.| **Example** @@ -67,7 +67,7 @@ Obtains an **[InputMethodSetting](#inputmethodsetting8)** instance. | Type | Description | | ----------------------------------------- | ---------------------------- | -| [InputMethodSetting](#inputmethodsetting8) | Returns the current **InputMethodSetting** instance.| +| [InputMethodSetting](#inputmethodsetting8) | Current **InputMethodSetting** instance.| **Example** @@ -94,15 +94,15 @@ Switches to another input method. This API can be used only in the stage model. **Example** ```js -inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"} ,(err,result) => { +inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'} ,(err,result) => { if (err) { - console.error("switchInputMethod err: " + JSON.stringify(err)); + console.error('switchInputMethod err: ' + JSON.stringify(err)); return; } if (result) { - console.info("Success to switchInputMethod.(callback)"); + console.info('Success to switchInputMethod.(callback)'); } else { - console.error("Failed to switchInputMethod.(callback)"); + console.error('Failed to switchInputMethod.(callback)'); } }); ``` @@ -129,14 +129,14 @@ Switches to another input method. This API can be used only in the stage model. ```js -inputMethod.switchInputMethod({packageName:"com.example.kikakeyboard", methodId:"com.example.kikakeyboard"}).then((result) => { +inputMethod.switchInputMethod({packageName:'com.example.kikakeyboard', methodId:'com.example.kikakeyboard'}).then((result) => { if (result) { - console.info("Success to switchInputMethod.(promise)"); + console.info('Success to switchInputMethod.(promise)'); } else { - console.error("Failed to switchInputMethod.(promise)"); + console.error('Failed to switchInputMethod.(promise)'); } }).catch((err) => { - console.error("switchInputMethod promise err: " + err); + console.error('switchInputMethod promise err: ' + err); }) ``` ## inputMethod.getCurrentInputMethod9+ @@ -151,7 +151,7 @@ Obtains the current input method. This API synchronously returns the **Inputmeth | Type | Description | | -------------------------------------------- | ------------------------ | -| [InputmethodProperty](#inputmethodproperty8) | **InputmethodProperty** instance of the current input method. | +| [InputmethodProperty](#inputmethodproperty8) | **InputmethodProperty** instance of the current input method.| **Example** @@ -183,13 +183,13 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ```js InputMethodController.stopInput((error, result) => { if (error) { - console.error("failed to stopInput because: " + JSON.stringify(error)); + console.error('failed to stopInput because: ' + JSON.stringify(error)); return; } if (result) { - console.info("Success to stopInput.(callback)"); + console.info('Success to stopInput.(callback)'); } else { - console.error("Failed to stopInput.(callback)"); + console.error('Failed to stopInput.(callback)'); } }); ``` @@ -214,12 +214,12 @@ Hides the keyboard. This API uses a promise to return the result. If any paramet ```js InputMethodController.stopInput().then((result) => { if (result) { - console.info("Success to stopInput.(promise)"); + console.info('Success to stopInput.(promise)'); } else { - console.error("Failed to stopInput.(promise)"); + console.error('Failed to stopInput.(promise)'); } }).catch((err) => { - console.error("stopInput promise err: " + err); + console.error('stopInput promise err: ' + err); }) ``` @@ -241,7 +241,7 @@ Shows this soft keyboard. This API uses an asynchronous callback to return the r ```js InputMethodController.showSoftKeyboard((err) => { - if (err == undefined) { + if (err === undefined) { console.info('showSoftKeyboard success'); } else { console.error('showSoftKeyboard failed because : ' + JSON.stringify(err)); @@ -292,7 +292,7 @@ Hides this soft keyboard. This API uses an asynchronous callback to return the r ```js InputMethodController.hideSoftKeyboard((err) => { - if (err == undefined) { + if (err === undefined) { console.info('hideSoftKeyboard success'); } else { console.error('hideSoftKeyboard failed because : ' + JSON.stringify(err)); @@ -342,19 +342,17 @@ Obtains a list of activated or deactivated input methods. This API uses an async | Name | Type | Mandatory| Description | | -------- | --------------------------------------------------- | ---- | ----------------------------- | | enable | boolean | Yes | Whether to return a list of activated input methods. The value **true** means to return a list of activated input methods, and **false** means to return a list of deactivated input methods. | -| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return a list of activated or deactivated input methods. | +| callback | Array<[InputMethodProperty](#inputmethodproperty8)> | Yes | Callback used to return a list of activated or deactivated input methods.| **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod(true, (err,data) => { if (err) { - console.error("listInputMethod failed because: " + JSON.stringify(err)); + console.error('listInputMethod failed because: ' + JSON.stringify(err)); return; } - console.log("listInputMethod success"); - this.imeList = data; + console.log('listInputMethod success'); }); ``` @@ -376,17 +374,15 @@ Obtains a list of activated or deactivated input methods. This API uses a promis | Type | Description | | ------------------------------------------------------------ | ----------------------------- | -| Promise> | Promise used to return a list of activated or deactivated input methods. | +| Promise> | Promise used to return a list of activated or deactivated input methods.| **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod(true).then((data) => { - console.info("listInputMethod success"); - this.imeList = data; + console.info('listInputMethod success'); }).catch((err) => { - console.error("listInputMethod promise err: " + err); + console.error('listInputMethod promise err: ' + err); }) ``` @@ -407,14 +403,12 @@ Obtains a list of installed input methods. This API uses an asynchronous callbac **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod((err,data) => { if (err) { - console.error("listInputMethod failed because: " + JSON.stringify(err)); + console.error('listInputMethod failed because: ' + JSON.stringify(err)); return; } - console.log("listInputMethod success"); - this.imeList = data; + console.log('listInputMethod success'); }); ``` @@ -435,12 +429,10 @@ Obtains a list of installed input methods. This API uses a promise to return the **Example** ```js -imeList: Array = null InputMethodSetting.listInputMethod().then((data) => { - console.info("listInputMethod success"); - this.imeList = data; + console.info('listInputMethod success'); }).catch((err) => { - console.error("listInputMethod promise err: " + err); + console.error('listInputMethod promise err: ' + err); }) ``` @@ -463,20 +455,20 @@ Displays a dialog box for selecting an input method. This API uses an asynchrono ```js InputMethodSetting.displayOptionalInputMethod((err) => { if (err) { - console.error("displayOptionalInputMethod failed because: " + JSON.stringify(err)); + console.error('displayOptionalInputMethod failed because: ' + JSON.stringify(err)); return; } - console.info("displayOptionalInputMethod success"); + console.info('displayOptionalInputMethod success'); }); ``` ### displayOptionalInputMethod -displayOptionalInputMethod(): Promise<void> + displayOptionalInputMethod(): Promise<void> -Displays a dialog box for selecting an input method. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. + Displays a dialog box for selecting an input method. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. -**System capability**: SystemCapability.MiscServices.InputMethodFramework + **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** @@ -488,8 +480,8 @@ Displays a dialog box for selecting an input method. This API uses a promise to ```js InputMethodSetting.displayOptionalInputMethod().then(() => { - console.info("displayOptionalInputMethod success.(promise)"); + console.info('displayOptionalInputMethod success.(promise)'); }).catch((err) => { - console.error("displayOptionalInputMethod promise err: " + err); + console.error('displayOptionalInputMethod promise err: ' + err); }) ``` diff --git a/en/application-dev/reference/apis/js-apis-inputmethodengine.md b/en/application-dev/reference/apis/js-apis-inputmethodengine.md index 55e702cd0501af092bbc7e0420f410ff81ed90c6..7ae35566725ea5fd3d489c29ea8b4d330695a534 100644 --- a/en/application-dev/reference/apis/js-apis-inputmethodengine.md +++ b/en/application-dev/reference/apis/js-apis-inputmethodengine.md @@ -46,6 +46,11 @@ Provides the constants. | FLAG_SINGLE_LINE | number | Yes| No| The edit box allows only single-line input.| | DISPLAY_MODE_PART | number | Yes| No| The edit box is displayed in half-screen mode.| | DISPLAY_MODE_FULL | number | Yes| No| The edit box is displayed in full screen.| +| CURSOR_UP9+ | number | Yes| No| The caret moves upward.| +| CURSOR_DOWN9+ | number | Yes| No| The caret moves downward.| +| CURSOR_LEFT9+ | number | Yes| No| The caret moves leftward.| +| CURSOR_RIGHT9+ | number | Yes| No| The caret moves rightward.| +| WINDOW_TYPE_INPUT_METHOD_FLOAT9+ | number | Yes| No| The input method is displayed in a floating window.| ## inputMethodEngine.getInputMethodEngine @@ -95,7 +100,7 @@ In the following API examples, you must first use [getInputMethodEngine](#getInp on(type: 'inputStart', callback: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void -Listens for the input method binding event. This API uses a callback to return the result. +Listens for the input method binding event. This API uses a callback to return the result. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -119,7 +124,7 @@ Listens for the input method binding event. This API uses a callback to return t off(type: 'inputStart', callback?: (kbController: KeyboardController, textInputClient: TextInputClient) => void): void -Cancels listening for the input method binding event. +Cancels listening for the input method binding event. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -135,14 +140,108 @@ Cancels listening for the input method binding event. **Example** ```js - InputMethodEngine.off('inputStart'); + InputMethodEngine.off('inputStart', (kbController, textInputClient) => { + console.log('delete inputStart notification.'); + }); + ``` + +### on('inputStop')9+ + +on(type: 'inputStop', callback: () => void): void + +Listens for the input method stop event. This API uses a callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'inputStop'**, which indicates listening for the input method stop event.| +| callback | void | Yes | Callback used to return the result. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().on('inputStop', () => { + console.log('inputMethodEngine inputStop'); +}); + ``` + +### off('inputStop')9+ + +off(type: 'inputStop', callback: () => void): void + +Cancels listening for the input method stop event. This API uses a callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'inputStop'**, which indicates listening for the input method stop event.| +| callback | void | Yes | Callback used to return the result. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().off('inputStop', () => { + console.log('inputMethodEngine delete inputStop notification.'); +}); + ``` + +### on('setCallingWindow')9+ + +on(type: 'setCallingWindow', callback: (wid:number) => void): void + +Listens for the window invocation setting event. This API uses a callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'setCallingWindow'**, which indicates listening for the window invocation setting event.| +| callback | number | Yes | Window ID of the caller. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().on('setCallingWindow', (wid) => { + console.log('inputMethodEngine setCallingWindow'); +}); + ``` + +### off('setCallingWindow')9+ + +off(type: 'setCallingWindow', callback: (wid:number) => void): void + +Cancels listening for the window invocation setting event. This API uses a callback to return the result. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | Yes | Listening type.
Set it to **'setCallingWindow'**, which indicates listening for the window invocation setting event.| +| callback | number | Yes | Window ID of the caller. | + +**Example** + + ```js +InputMethodEngine.getInputMethodEngine().off('setCallingWindow', () => { + console.log('inputMethodEngine delete setCallingWindow notification.'); +}); ``` ### on('keyboardShow'|'keyboardHide') on(type: 'keyboardShow'|'keyboardHide', callback: () => void): void -Listens for an input method event. +Listens for an input method event. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -150,14 +249,17 @@ Listens for an input method event. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| +| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the keyboard.
- The value **'keyboardHide'** means to listen for hiding of the keyboard. | | callback | void | No | Callback used to return the result. | **Example** ```js - InputMethodEngine.on('keyboardShow', (err) => { - console.info('keyboardShow'); + InputMethodEngine.on('keyboardShow', () => { + console.log('inputMethodEngine keyboardShow.'); + }); + InputMethodEngine.on('keyboardHide', () => { + console.log('inputMethodEngine keyboardHide.'); }); ``` @@ -165,7 +267,7 @@ Listens for an input method event. off(type: 'keyboardShow'|'keyboardHide', callback?: () => void): void -Cancels listening for an input method event. +Cancels listening for an input method event. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -173,13 +275,18 @@ Cancels listening for an input method event. | Name | Type | Mandatory| Description | | -------- | ------ | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the input method.
- The value **'keyboardHide'** means to listen for hiding of the input method.| +| type | string | Yes | Listening type.
- The value **'keyboardShow'** means to listen for displaying of the keyboard.
- The value **'keyboardHide'** means to listen for hiding of the keyboard.| | callback | void | No | Callback used to return the result. | **Example** ```js - InputMethodEngine.off('keyboardShow'); + InputMethodEngine.off('keyboardShow', () => { + console.log('inputMethodEngine delete keyboardShow notification.'); + }); + InputMethodEngine.off('keyboardHide', () => { + console.log('inputMethodEngine delete keyboardHide notification.'); + }); ``` @@ -191,7 +298,7 @@ In the following API examples, you must first use [createKeyboardDelegate](#crea on(type: 'keyDown'|'keyUp', callback: (event: KeyEvent) => boolean): void -Listens for a hard keyboard even. This API uses a callback to return the key information. +Listens for a hard keyboard even. This API uses a callback to return the key information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -199,7 +306,7 @@ Listens for a hard keyboard even. This API uses a callback to return the key inf | Name | Type | Mandatory| Description | | -------- | ------------------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| +| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| | callback | [KeyEvent](#KeyEvent) | Yes| Callback used to return the key information.| @@ -207,8 +314,15 @@ Listens for a hard keyboard even. This API uses a callback to return the key inf **Example** ```js - KeyboardDelegate.on('keyDown', (event) => { - console.info('keyDown'); + KeyboardDelegate.on('keyUp', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyUp):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyUp):' + JSON.stringify(keyEvent.keyAction)); + return true; + }); + KeyboardDelegate.on('keyDown', (keyEvent) => { + console.info('inputMethodEngine keyCode.(keyDown):' + JSON.stringify(keyEvent.keyCode)); + console.info('inputMethodEngine keyAction.(keyDown):' + JSON.stringify(keyEvent.keyAction)); + return true; }); ``` @@ -216,7 +330,7 @@ Listens for a hard keyboard even. This API uses a callback to return the key inf off(type: 'keyDown'|'keyUp', callback?: (event: KeyEvent) => boolean): void -Cancels listening for a hard keyboard even. +Cancels listening for a hard keyboard even. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -224,20 +338,27 @@ Cancels listening for a hard keyboard even. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | -| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| +| type | string | Yes | Listening type.
- The value **'keyDown'** means to listen for pressing of a key.
- The value **'keyUp'** means to listen for releasing of a key.| | callback | [KeyEvent](#KeyEvent) | No | Callback used to return the key information. | **Example** ```js - KeyboardDelegate.off('keyDown'); + KeyboardDelegate.off('keyUp', (keyEvent) => { + console.log('delete keyUp notification.'); + return true; + }); + KeyboardDelegate.off('keyDown', (keyEvent) => { + console.log('delete keyDown notification.'); + return true; + }); ``` ### on('cursorContextChange') on(type: 'cursorContextChange', callback: (x: number, y:number, height:number) => void): void -Listens for cursor context changes. This API uses a callback to return the cursor information. +Listens for cursor context changes. This API uses a callback to return the cursor information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -253,18 +374,18 @@ Listens for cursor context changes. This API uses a callback to return the curso **Example** ```js - KeyboardDelegate.on('cursorContextChange', (x, y, height) => { - console.info('cursorContextChange'); + console.log('inputMethodEngine cursorContextChange x:' + x); + console.log('inputMethodEngine cursorContextChange y:' + y); + console.log('inputMethodEngine cursorContextChange height:' + height); }); - ``` ### off('cursorContextChange') off(type: 'cursorContextChange', callback?: (x: number, y:number, height:number) => void): void -Cancels listening for cursor context changes. +Cancels listening for cursor context changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -279,15 +400,15 @@ Cancels listening for cursor context changes. **Example** ```js - -KeyboardDelegate.off('cursorContextChange'); - +KeyboardDelegate.off('cursorContextChange', (x, y, height) => { + console.log('delete cursorContextChange notification.'); +}); ``` ### on('selectionChange') on(type: 'selectionChange', callback: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void -Listens for text selection changes. This API uses a callback to return the text selection information. +Listens for text selection changes. This API uses a callback to return the text selection information. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -301,18 +422,19 @@ Listens for text selection changes. This API uses a callback to return the text **Example** ```js - KeyboardDelegate.on('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { - console.info('selectionChange'); + console.log('inputMethodEngine beforeEach selectionChange oldBegin:' + oldBegin); + console.log('inputMethodEngine beforeEach selectionChange oldEnd:' + oldEnd); + console.log('inputMethodEngine beforeEach selectionChange newBegin:' + newBegin); + console.log('inputMethodEngine beforeEach selectionChange newEnd:' + newEnd); }); - ``` ### off('selectionChange') off(type: 'selectionChange', callback?: (oldBegin: number, oldEnd: number, newBegin: number, newEnd: number) => void): void -Cancels listening for text selection changes. +Cancels listening for text selection changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -326,9 +448,9 @@ Cancels listening for text selection changes. **Example** ```js - -KeyboardDelegate.off('selectionChange'); - +KeyboardDelegate.off('selectionChange', (oldBegin, oldEnd, newBegin, newEnd) => { + console.log('delete selectionChange notification.'); +}); ``` @@ -336,7 +458,7 @@ KeyboardDelegate.off('selectionChange'); on(type: 'textChange', callback: (text: string) => void): void -Listens for text changes. This API uses a callback to return the current text content. +Listens for text changes. This API uses a callback to return the current text content. This API requires two parameters, the first one being napi_string and the second one being napi_function. If either of these parameters is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -350,18 +472,16 @@ Listens for text changes. This API uses a callback to return the current text co **Example** ```js - KeyboardDelegate.on('textChange', (text) => { - console.info('textChange'); + console.log('inputMethodEngine textChange. text:' + text); }); - ``` ### off('textChange') off(type: 'textChange', callback?: (text: string) => void): void -Cancels listening for text changes. +Cancels listening for text changes. An exception is thrown in the following cases: (1) No parameter is passed; (2) Only one parameter is passed in, and it is not napi_string; (2) Two parameters are passed in, and the first parameter is not napi_string or the second parameter is not napi_function. If only one parameter is passed in, all listeners of the specified type will be canceled. If two parameters are passed in, the current listener of the specified type will be canceled. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -375,7 +495,9 @@ Cancels listening for text changes. **Example** ```js -KeyboardDelegate.off('textChange'); +keyboardDelegate.off('textChange', (text) => { + console.log('delete textChange notification. text:' + text); +}); ``` ## KeyboardController @@ -386,7 +508,7 @@ In the following API examples, you must first use [inputStart](#inputStart) to o hideKeyboard(callback: AsyncCallback<void>): void -Hides the keyboard. This API uses an asynchronous callback to return the result. +Hides the keyboard. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -400,28 +522,39 @@ Hides the keyboard. This API uses an asynchronous callback to return the result. ```js - KeyboardController.hideKeyboard(()=>{ - }); +KeyboardController.hideKeyboard((err) => { + if (err === undefined) { + console.error('hideKeyboard callback result---err: ' + err.msg); + return; + } + console.log('hideKeyboard callback.'); +}); ``` ### hideKeyboard hideKeyboard(): Promise<void> -Hides the keyboard. This API uses an asynchronous callback to return the result. +Hides the keyboard. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Return value** -| Type | Description | -| ---------------- | -------- | -| Promise<void> | Promise used to return the result.| +| Type | Description | +| ---------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** ```js - KeyboardController.hideKeyboard(); +async function InputMethodEngine() { + await KeyboardController.hideKeyboard().then(() => { + console.info('hideKeyboard promise.'); + }).catch((err) => { + console.info('hideKeyboard promise err: ' + err.msg); + }); +} ``` ## TextInputClient @@ -432,7 +565,7 @@ In the following API examples, you must first use [inputStart](#inputStart) to o getForward(length:number, callback: AsyncCallback<string>): void -Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. +Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -446,16 +579,21 @@ Obtains the specific-length text before the cursor. This API uses an asynchronou **Example** ```js - TextInputClient.getForward(5,(text) =>{ - console.info("text = " + text); - }); + var length = 1; + TextInputClient.getForward(length, (err, text) => { + if (err === undefined) { + console.error('getForward callback result---err: ' + err.msg); + return; + } + console.log('getForward callback result---text: ' + text); + }); ``` ### getForward getForward(length:number): Promise<string> -Obtains the specific-length text before the cursor. This API uses an asynchronous callback to return the result. +Obtains the specific-length text before the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -474,15 +612,21 @@ Obtains the specific-length text before the cursor. This API uses an asynchronou **Example** ```js - var text = TextInputClient.getForward(5); - console.info("text = " + text); + async function InputMethodEngine() { + var length = 1; + await TextInputClient.getForward(length).then((text) => { + console.info('getForward promise result---res: ' + text); + }).catch((err) => { + console.error('getForward promise err: ' + err.msg); + }); + } ``` ### getBackward getBackward(length:number, callback: AsyncCallback<string>): void -Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. +Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -496,8 +640,13 @@ Obtains the specific-length text after the cursor. This API uses an asynchronous **Example** ```js - TextInputClient.getBackward(5,(text)=>{ - console.info("text = " + text); + var length = 1; + TextInputClient.getBackward(length, (err, text) => { + if (err === undefined) { + console.error('getBackward callback result---err: ' + err.msg); + return; + } + console.log('getBackward callback result---text: ' + text); }); ``` @@ -505,7 +654,7 @@ Obtains the specific-length text after the cursor. This API uses an asynchronous getBackward(length:number): Promise<string> -Obtains the specific-length text after the cursor. This API uses an asynchronous callback to return the result. +Obtains the specific-length text after the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -524,15 +673,21 @@ Obtains the specific-length text after the cursor. This API uses an asynchronous **Example** ```js - var text = TextInputClient.getBackward(5); - console.info("text = " + text); + async function InputMethodEngine() { + var length = 1; + await TextInputClient.getBackward(length).then((text) => { + console.info('getBackward promise result---res: ' + text); + }).catch((err) => { + console.error('getBackward promise err: ' + err.msg); + }); + } ``` ### deleteForward deleteForward(length:number, callback: AsyncCallback<boolean>): void -Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -546,15 +701,24 @@ Deletes the fixed-length text before the cursor. This API uses an asynchronous c **Example** ```js - TextInputClient.deleteForward(5,(isSuccess)=>{ - console.info("isSuccess = " + isSuccess); + var length = 1; + TextInputClient.deleteForward(length, (err, result) => { + if (err === undefined) { + console.error('deleteForward callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to deleteForward.(callback) '); + } else { + console.error('Failed to deleteForward.(callback) '); + } }); ``` ### deleteForward deleteForward(length:number): Promise<boolean> -Deletes the fixed-length text before the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text before the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -573,15 +737,25 @@ Deletes the fixed-length text before the cursor. This API uses an asynchronous c **Example** ```js -var isSuccess = TextInputClient.deleteForward(5); - console.info("isSuccess = " + isSuccess); +async function InputMethodEngine() { + var length = 1; + await TextInputClient.deleteForward(length).then((result) => { + if (result) { + console.info('Success to deleteForward.(promise) '); + } else { + console.error('Failed to deleteForward.(promise) '); + } + }).catch((err) => { + console.error('deleteForward promise err: ' + err.msg); + }); +} ``` ### deleteBackward deleteBackward(length:number, callback: AsyncCallback<boolean>): void -Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -595,22 +769,30 @@ Deletes the fixed-length text after the cursor. This API uses an asynchronous ca **Example** ```js - - TextInputClient.deleteBackward(5, (isSuccess)=>{ - console.info("isSuccess = " + isSuccess); +var length = 1; +TextInputClient.deleteBackward(length, (err, result) => { + if (err === undefined) { + console.error('deleteBackward callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to deleteBackward.(callback) '); + } else { + console.error('Failed to deleteBackward.(callback) '); + } }); - ``` ### deleteBackward deleteBackward(length:number): Promise<boolean> -Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. +Deletes the fixed-length text after the cursor. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework **Parameters** + | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | length | number | Yes| Text length.| @@ -624,16 +806,24 @@ Deletes the fixed-length text after the cursor. This API uses an asynchronous ca **Example** ```js - - var isSuccess = TextInputClient.deleteBackward(5); - console.info("isSuccess = " + isSuccess); - +async function InputMethodEngine() { + var length = 1; + await TextInputClient.deleteBackward(length).then((result) => { + if (result) { + console.info('Success to deleteBackward.(promise) '); + } else { + console.error('Failed to deleteBackward.(promise) '); + } + }).catch((err) => { + console.error('deleteBackward promise err: ' + err.msg); + }); +} ``` ### sendKeyFunction sendKeyFunction(action:number, callback: AsyncCallback<boolean>): void -Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. +Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -647,18 +837,24 @@ Sets the Enter key to send the text to its target. This API uses an asynchronous **Example** ```js - - TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT,(isSuccess)=>{ - console.info("isSuccess = " + isSuccess); +TextInputClient.sendKeyFunction(keyFunction, (err, result) => { + if (err === undefined) { + console.error('sendKeyFunction callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to sendKeyFunction.(callback) '); + } else { + console.error('Failed to sendKeyFunction.(callback) '); + } }); - ``` ### sendKeyFunction sendKeyFunction(action:number): Promise<boolean> -Sets the Enter key to send the text to its target. This API uses an asynchronous callback to return the result. +Sets the Enter key to send the text to its target. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -677,15 +873,24 @@ Sets the Enter key to send the text to its target. This API uses an asynchronous **Example** ```js - var isSuccess = TextInputClient.sendKeyFunction(inputMethod.ENTER_KEY_TYPE_NEXT); - console.info("isSuccess = " + isSuccess); + async function InputMethodEngine() { + await client.sendKeyFunction(keyFunction).then((result) => { + if (result) { + console.info('Success to sendKeyFunction.(promise) '); + } else { + console.error('Failed to sendKeyFunction.(promise) '); + } + }).catch((err) => { + console.error('sendKeyFunction promise err:' + err.msg); + }); + } ``` ### insertText insertText(text:string, callback: AsyncCallback<boolean>): void -Inserts text. This API uses an asynchronous callback to return the result. +Inserts text. This API uses an asynchronous callback to return the result. If the required two parameters are not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -699,18 +904,24 @@ Inserts text. This API uses an asynchronous callback to return the result. **Example** ```js - -TextInputClient.insertText("test", (isSuccess)=>{ - console.info("isSuccess = " + isSuccess); +TextInputClient.insertText('test', (err, result) => { + if (err === undefined) { + console.error('insertText callback result---err: ' + err.msg); + return; + } + if (result) { + console.info('Success to insertText.(callback) '); + } else { + console.error('Failed to insertText.(callback) '); + } }); - ``` ### insertText insertText(text:string): Promise<boolean> -Inserts text. This API uses an asynchronous callback to return the result. +Inserts text. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -729,15 +940,24 @@ Inserts text. This API uses an asynchronous callback to return the result. **Example** ```js - var isSuccess = TextInputClient.insertText("test"); - console.info("isSuccess = " + isSuccess); + async function InputMethodEngine() { + await TextInputClient.insertText('test').then((result) => { + if (result) { + console.info('Success to insertText.(promise) '); + } else { + console.error('Failed to insertText.(promise) '); + } + }).catch((err) => { + console.error('insertText promise err: ' + err.msg); + }); + } ``` ### getEditorAttribute getEditorAttribute(callback: AsyncCallback<EditorAttribute>): void -Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. +Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -750,15 +970,21 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to **Example** ```js - TextInputClient.getEditorAttribute((EditorAttribute)=>{ - }); + TextInputClient.getEditorAttribute((err, editorAttribute) => { + if (err === undefined) { + console.error('getEditorAttribute callback result---err: ' + err.msg); + return; + } + console.log('editorAttribute.inputPattern(callback): ' + JSON.stringify(editorAttribute.inputPattern)); + console.log('editorAttribute.enterKeyType(callback): ' + JSON.stringify(editorAttribute.enterKeyType)); + }); ``` ### getEditorAttribute -getEditorAttribute(): EditorAttribute +getEditorAttribute(): Promise<EditorAttribute> -Obtains the attribute of the edit box. This API uses an asynchronous callback to return the result. +Obtains the attribute of the edit box. This API uses a promise to return the result. If any parameter is passed in, an exception is thrown. **System capability**: SystemCapability.MiscServices.InputMethodFramework @@ -766,14 +992,79 @@ Obtains the attribute of the edit box. This API uses an asynchronous callback to | Type | Description | | ------------------------------- | ------------------------------------------------------------ | -| Promise<[EditorAttribute](#EditorAttribute)> | Promise used to return the attribute of the edit box. | +| Promise<[EditorAttribute](#EditorAttribute)> | Promise used to return the attribute of the edit box. | **Example** ```js - var EditorAttribute = TextInputClient.getEditorAttribute(); + async function InputMethodEngine() { + await TextInputClient.getEditorAttribute().then((editorAttribute) => { + console.info('editorAttribute.inputPattern(promise): ' + JSON.stringify(editorAttribute.inputPattern)); + console.info('editorAttribute.enterKeyType(promise): ' + JSON.stringify(editorAttribute.enterKeyType)); + }).catch((err) => { + console.error('getEditorAttribute promise err: ' + err.msg); + }); + } ``` +### moveCursor9+ + +moveCursor(direction: number, callback: AsyncCallback<void>): void + +Moves the cursor. This API uses an asynchronous callback to return the result. If the required parameter is not passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | -------------- | +| direction | number | Yes | Direction in which the cursor moves.| +| callback | AsyncCallback<void> | Yes | Callback used to return the result. | + +**Example** + +```js +TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx, (err) => { + if (err === undefined) { + console.error('moveCursor callback result---err: ' + err.msg); + return; + } +}); +``` + +### moveCursor9+ + +moveCursor(direction: number): Promise<void> + +Moves the cursor. This API uses a promise to return the result. If the required parameter is not passed in, an exception is thrown. + +**System capability**: SystemCapability.MiscServices.InputMethodFramework + +**Parameters** + +| Name | Type | Mandatory| Description | +| --------- | ------ | ---- | -------------- | +| direction | number | Yes | Direction in which the cursor moves.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +async function InputMethodEngine() { + await TextInputClient.moveCursor(inputMethodEngine.CURSOR_xxx).then(async (err) => { + console.log('moveCursor success'); + }).catch((err) => { + console.error('moveCursor success err: ' + err.msg); + }); +} + ``` + ## EditorAttribute Describes the attribute of the edit box. diff --git a/en/application-dev/reference/apis/js-apis-media.md b/en/application-dev/reference/apis/js-apis-media.md index fca68b5554d6239a03415892d68570dc1b4e8574..b29a380a5b1b2e8afb4d41687a659dc29db4344c 100644 --- a/en/application-dev/reference/apis/js-apis-media.md +++ b/en/application-dev/reference/apis/js-apis-media.md @@ -229,7 +229,7 @@ Enumerates the codec MIME types. | VIDEO_MPEG2 | 'video/mpeg2' | Video in MPEG-2 format. | | VIDEO_MPEG4 | 'video/mp4v-es' | Video in MPEG-4 format. | | VIDEO_VP8 | 'video/x-vnd.on2.vp8' | Video in VP8 format. | -| AUDIO_AAC | "audio/mp4a-latm" | Audio in MP4A-LATM format.| +| AUDIO_AAC | 'audio/mp4a-latm' | Audio in MP4A-LATM format.| | AUDIO_VORBIS | 'audio/vorbis' | Audio in Vorbis format. | | AUDIO_FLAC | 'audio/flac' | Audio in FLAC format. | @@ -241,16 +241,16 @@ Enumerates the media description keys. | Name | Value | Description | | ------------------------ | --------------- | ------------------------------------------------------------ | -| MD_KEY_TRACK_INDEX | "track_index" | Track index, which is a number. | -| MD_KEY_TRACK_TYPE | "track_type" | Track type, which is a number. For details, see [MediaType](#mediatype8).| -| MD_KEY_CODEC_MIME | "codec_mime" | Codec MIME type, which is a string. | -| MD_KEY_DURATION | "duration" | Media duration, which is a number, in units of ms. | -| MD_KEY_BITRATE | "bitrate" | Bit rate, which is a number, in units of bit/s. | -| MD_KEY_WIDTH | "width" | Video width, which is a number, in units of pixel. | -| MD_KEY_HEIGHT | "height" | Video height, which is a number, in units of pixel. | -| MD_KEY_FRAME_RATE | "frame_rate" | Video frame rate, which is a number, in units of 100 fps.| -| MD_KEY_AUD_CHANNEL_COUNT | "channel_count" | Number of audio channels, which is a number. | -| MD_KEY_AUD_SAMPLE_RATE | "sample_rate" | Sampling rate, which is a number, in units of Hz. | +| MD_KEY_TRACK_INDEX | 'track_index' | Track index, which is a number. | +| MD_KEY_TRACK_TYPE | 'track_type' | Track type, which is a number. For details, see [MediaType](#mediatype8).| +| MD_KEY_CODEC_MIME | 'codec_mime' | Codec MIME type, which is a string. | +| MD_KEY_DURATION | 'duration' | Media duration, which is a number, in units of ms. | +| MD_KEY_BITRATE | 'bitrate' | Bit rate, which is a number, in units of bit/s. | +| MD_KEY_WIDTH | 'width' | Video width, which is a number, in units of pixel. | +| MD_KEY_HEIGHT | 'height' | Video height, which is a number, in units of pixel. | +| MD_KEY_FRAME_RATE | 'frame_rate' | Video frame rate, which is a number, in units of 100 fps.| +| MD_KEY_AUD_CHANNEL_COUNT | 'channel_count' | Number of audio channels, which is a number. | +| MD_KEY_AUD_SAMPLE_RATE | 'sample_rate' | Sampling rate, which is a number, in units of Hz. | ## BufferingInfoType8+ @@ -442,10 +442,10 @@ function printfDescription(obj) { } } -audioPlayer.getTrackDescription((error, arrlist) => { - if (arrlist != null) { - for (let i = 0; i < arrlist.length; i++) { - printfDescription(arrlist[i]); +audioPlayer.getTrackDescription((error, arrList) => { + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); } } else { console.log(`audio getTrackDescription fail, error:${error}`); @@ -478,9 +478,9 @@ function printfDescription(obj) { } } let arrayDescription = null -audioPlayer.getTrackDescription().then((arrlist) => { - if (arrlist != null) { - arrayDescription = arrlist; +audioPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; } else { console.log('audio getTrackDescription fail'); } @@ -1235,10 +1235,10 @@ function printfDescription(obj) { } } -videoPlayer.getTrackDescription((error, arrlist) => { - if ((arrlist) != null) { - for (let i = 0; i < arrlist.length; i++) { - printfDescription(arrlist[i]); +videoPlayer.getTrackDescription((error, arrList) => { + if ((arrList) != null) { + for (let i = 0; i < arrList.length; i++) { + printfDescription(arrList[i]); } } else { console.log(`video getTrackDescription fail, error:${error}`); @@ -1272,9 +1272,9 @@ function printfDescription(obj) { } let arrayDescription; -videoPlayer.getTrackDescription().then((arrlist) => { - if (arrlist != null) { - arrayDescription = arrlist; +videoPlayer.getTrackDescription().then((arrList) => { + if (arrList != null) { + arrayDescription = arrList; } else { console.log('video getTrackDescription fail'); } @@ -1618,10 +1618,10 @@ function printfItemDescription(obj, key) { console.info('audio value is ' + property); // Obtain the value of the key. The value can be any type. For details about the types, see [MediaDescriptionKey]. } let audioPlayer = media.createAudioPlayer(); -audioPlayer.getTrackDescription((error, arrlist) => { - if (arrlist != null) { - for (let i = 0; i < arrlist.length; i++) { - printfItemDescription(arrlist[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. +audioPlayer.getTrackDescription((error, arrList) => { + if (arrList != null) { + for (let i = 0; i < arrList.length; i++) { + printfItemDescription(arrList[i], media.MediaDescriptionKey.MD_KEY_TRACK_TYPE); // Print the MD_KEY_TRACK_TYPE value of each track. } } else { console.log(`audio getTrackDescription fail, error:${error}`); @@ -2533,8 +2533,8 @@ Enumerates the container format types (CFTs). | Name | Value | Description | | ----------- | ----- | --------------------- | -| CFT_MPEG_4 | "mp4" | Video container format MPEG-4.| -| CFT_MPEG_4A | "m4a" | Audio container format M4A.| +| CFT_MPEG_4 | 'mp4' | Video container format MPEG-4.| +| CFT_MPEG_4A | 'm4a' | Audio container format M4A.| ## Location diff --git a/en/application-dev/reference/apis/js-apis-pasteboard.md b/en/application-dev/reference/apis/js-apis-pasteboard.md index 00802493ea68efd037b17e0712d78b755d131059..be28e4b7590f1671660228d3e78f2e822451a847 100644 --- a/en/application-dev/reference/apis/js-apis-pasteboard.md +++ b/en/application-dev/reference/apis/js-apis-pasteboard.md @@ -1,149 +1,214 @@ # Pasteboard -The **pasteboard** module provides the pasteboard management client and pasteboard server. The pasteboard management client manages pasteboard APIs. Specifically, it provides pasteboard APIs in JavaScript for applications, creates pasteboard data on the application framework side, and requests the pasteboard SA to create, delete, query, convert text, and configure pasteboards. The pasteboard server manages pasteboard events as well as the pasteboard SA lifecycle, providing support for the copy and paste functions of the system. +The **pasteboard** module provides the copy and paste support for the system pasteboard. You can use the APIs of this module to operate pasteboard content of the plain text, HTML, URI, Want, pixel map, and other types. > **NOTE** -> +> > The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. - ## Modules to Import - -``` +```js import pasteboard from '@ohos.pasteboard'; ``` - ## Attributes **System capability**: SystemCapability.MiscServices.Pasteboard -| Name | Type | Readable | Writable | Description | +| Name| Type| Readable| Writable| Description| | -------- | -------- | -------- | -------- | -------- | -| MAX_RECORD_NUM7+ | number | Yes | No | Maximum number of records allowed in a **PasteData** object. | -| MIMETYPE_TEXT_HTML7+ | string | Yes | No | MIME type of the HTML text. | -| MIMETYPE_TEXT_WANT7+ | string | Yes | No | MIME type of the Want text. | -| MIMETYPE_TEXT_PLAIN7+ | string | Yes | No | MIME type of the plain text. | -| MIMETYPE_TEXT_URI7+ | string | Yes | No | MIME type of the URI text. | +| MAX_RECORD_NUM7+ | number | Yes| No| Maximum number of records in a **PasteData** object.| +| MIMETYPE_TEXT_HTML7+ | string | Yes| No| MIME type of the HTML content.| +| MIMETYPE_TEXT_WANT7+ | string | Yes| No| MIME type of the Want content.| +| MIMETYPE_TEXT_PLAIN7+ | string | Yes| No| MIME type of the plain text content.| +| MIMETYPE_TEXT_URI7+ | string | Yes| No| MIME type of the URI content.| +| MIMETYPE_PIXELMAP9+ | string | Yes| No| MIME type of the pixel map.| ## pasteboard.createPlainTextData -createPlainTextData(text:string): PasteData +createPlainTextData(text: string): PasteData -Creates a **PasteData** object for plain text. +Creates a **PasteData** object of the plain text type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| text | string | Yes | Plain text. | +| text | string | Yes| Plain text.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object with the specified content. | +| [PasteData](#pastedata) | **PasteData** object.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("content"); - ``` +```js +var pasteData = pasteboard.createPlainTextData("content"); +``` ## pasteboard.createHtmlData7+ -createHtmlData(htmlText:string): PasteData +createHtmlData(htmlText: string): PasteData -Creates a **PasteData** object for HTML text. +Creates a **PasteData** object of the HTML type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| htmlText | string | Yes | HTML text. | +| htmlText | string | Yes| HTML content.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteData](#pastedata) | **PasteData** object with the specified content. | +| [PasteData](#pastedata) | **PasteData** object.| **Example** - ```js - var html = "\n" + "\n" + "\n" + "\n" + "HTML-PASTEBOARD_HTML\n" + "\n" + "\n" + "

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

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

HEAD

\n" + "

\n" + "\n" + ""; +var htmlRecord = pasteboard.createHtmlTextRecord(html); +pasteData.addRecord(textRecord); +pasteData.addRecord(htmlRecord); +``` ### getMimeTypes7+ getMimeTypes(): Array<string> -Obtains **mimeTypes** in [PasteDataProperty](#pastedataproperty7) from this pasteboard. If the pasteboard is empty, the returned list is also empty. +Obtains a list of **mimeTypes** objects in [PasteDataProperty](#pastedataproperty7) from this pasteboard. If the pasteboard is empty, the returned list is also empty. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Array<string> | List of non-duplicate MIME types. | +| Array<string> | Non-repeating data types of the data records on the pasteboard.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var types = pasteData.getMimeTypes(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var types = pasteData.getMimeTypes(); +``` ### getPrimaryMimeType7+ getPrimaryMimeType(): string -Obtains the data type of the primary record. +Obtains the data type of the primary record in this pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| string | Data type of the primary record. | +| string | Data type of the primary record.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var type = pasteData.getPrimaryMimeType(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var type = pasteData.getPrimaryMimeType(); +``` ### getProperty7+ getProperty(): PasteDataProperty -Obtains the property description object. +Obtains the property of the pasteboard data. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataProperty](#pastedataproperty7) | Property description object. | +| [PasteDataProperty](#pastedataproperty7) | Property of the pasteboard data.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var property = pasteData.getProperty(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var property = pasteData.getProperty(); +``` + + +### setProperty9+ + +setProperty(property: PasteDataProperty): void + +Sets the property (attributes) for the pasteboard data. Currently, only the **shareOption** attribute is supported. + +**System capability**: SystemCapability.MiscServices.Pasteboard + +**Parameters** + +| Name| Type| Mandatory| Description| +| -------- | -------- | -------- | -------- | +| property | [PasteDataProperty](#pastedataproperty7) | Yes| Property of the pasteboard data.| + +**Example** + +```js +var pasteData = pasteboard.createHtmlData('application/xml'); +let prop = pasteData.getProperty(); +prop.shareOption = pasteboard.ShareOption.InApp; +pasteData.setProperty(prop); +``` ### getRecordAt7+ getRecordAt(index: number): PasteDataRecord -Obtains the record with the specified index. +Obtains the specified record in the pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes | Index of the specified record. | +| index | number | Yes| Index of the target record.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| [PasteDataRecord](#pastedatarecord7) | Record with the specified index. | +| [PasteDataRecord](#pastedatarecord7) | Record with the specified index.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var record = pasteData.getRecordAt(0); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var record = pasteData.getRecordAt(0); +``` ### getRecordCount7+ getRecordCount(): number -Obtains the number of data records in this pasteboard. +Obtains the number of records in the pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| number | Number of records. | +| number | Number of records.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var count = pasteData.getRecordCount(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var count = pasteData.getRecordCount(); +``` ### getTag7+ getTag(): string -Obtains the user-defined tag content. If the tag content is not set, null is returned. +Obtains the custom tag from the pasteboard. If no custom tag is set, null is returned. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| string | User-defined tag content if obtained and null if no tag is set. | +| string | Custom tag. If no custom tag is set, null is returned.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var tag = pasteData.getTag(); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var tag = pasteData.getTag(); +``` ### hasMimeType7+ hasMimeType(mimeType: string): boolean -Checks whether the content of this pasteboard contains the specified data type. +Checks whether the pasteboard contains data of the specified type. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| mimeType | string | Yes | Type of the data to query. | +| mimeType | string | Yes| Type of the data to query.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| boolean | Returns **true** if the specified data type exists; returns **false** otherwise. | +| boolean | Returns **true** if the specified data type exists; returns **false** otherwise.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var hasType = pasteData.hasMimeType(pasteboard.MIMETYPE_TEXT_PLAIN); +``` ### removeRecordAt7+ removeRecordAt(index: number): boolean -Removes the data record with a specified index from this pasteboard. +Removes the record with the specified index from the pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes | Specified index. | +| index | number | Yes| Specified index.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var isRemove = pasteData.removeRecordAt(0); - ``` +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var isRemove = pasteData.removeRecordAt(0); +``` ### replaceRecordAt7+ replaceRecordAt(index: number, record: PasteDataRecord): boolean -Replaces the data record with a specified index in this pasteboard. +Replaces the record with the specified index in the pasteboard with a new record. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| index | number | Yes | Specified index. | -| record | [PasteDataRecord](#pastedatarecord7) | Yes | New record. | +| index | number | Yes| Specified index.| +| record | [PasteDataRecord](#pastedatarecord7) | Yes| New record.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise. | +| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("hello"); - var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1?user.txt"); - var isReplace = pasteData.replaceRecordAt(0, record); - ``` - - -## pasteboard.getSystemPasteboard - -getSystemPasteboard(): SystemPasteboard - -Obtains the system pasteboard. - -**System capability**: SystemCapability.MiscServices.Pasteboard - -**Return value** - -| Type | Description | -| -------- | -------- | -| [SystemPasteboard](#systempasteboard) | System pasteboard. | - -**Example** - - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - ``` - +```js +var pasteData = pasteboard.createPlainTextData("hello"); +var record = pasteboard.createUriRecord("dataability:///com.example.myapplication1/user.txt"); +var isReplace = pasteData.replaceRecordAt(0, record); +``` ## SystemPasteboard -Before calling any **SystemPasteboard** method, you must obtain a **SystemPasteboard** object using [getSystemPasteboard](#pasteboardgetsystempasteboard). +Provides **SystemPasteboard** APIs. -``` +Before calling any **SystemPasteboard** API, you must obtain a **SystemPasteboard** object using [getSystemPasteboard](#pasteboardgetsystempasteboard). + +```js var systemPasteboard = pasteboard.getSystemPasteboard(); ``` ### setPasteData -setPasteData(data:PasteData, callback:AsyncCallback<void>): void +setPasteData(data: PasteData, callback: AsyncCallback<void>): void -Writes data to a pasteboard. This API uses an asynchronous callback to return the result. +Writes a **PasteData** object to the pasteboard. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| data | [PasteData](#pastedata) | Yes | **PasteData** object. | -| callback | AsyncCallback<void> | Yes | Callback used to return the data write result. | +| data | [PasteData](#pastedata) | Yes| **PasteData** object.| +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("content"); - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.setPasteData(pasteData, (error, data) => { - if (error) { - console.error('Failed to setPasteData. Cause: ' + error.message); - return; - } - console.info('setPasteData successfully.'); - }); - ``` +```js +var pasteData = pasteboard.createPlainTextData("content"); +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setPasteData(pasteData, (err, data) => { + if (err) { + console.error('Failed to set PasteData. Cause: ' + err.message); + return; + } + console.info('Succeeded in setting PasteData.'); +}); +``` ### setPasteData -setPasteData(data:PasteData): Promise<void> +setPasteData(data: PasteData): Promise<void> -Writes data to a pasteboard. This API uses a promise to return the result. +Writes a **PasteData** object to the pasteboard. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Description | +| Name| Type| Description| | -------- | -------- | -------- | -| data | [PasteData](#pastedata) | **PasteData** object. | +| data | [PasteData](#pastedata) | **PasteData** object.| **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the data write result. | +| Promise<void> | Promise that returns no value.| **Example** - ```js - var pasteData = pasteboard.createPlainTextData("content"); - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.setPasteData(pasteData).then((data) => { - console.info('setPasteData success.'); - }).catch((error) => { - console.error('Failed to setPasteData. Cause: ' + error.message); - }); - ``` +```js +var pasteData = pasteboard.createPlainTextData("content"); +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.setPasteData(pasteData).then((data) => { + console.info('Succeeded in setting PasteData.'); +}).catch((err) => { + console.error('Failed to set PasteData. Cause: ' + err.message); +}); +``` ### getPasteData -getPasteData( callback:AsyncCallback<PasteData>): void +getPasteData( callback: AsyncCallback<PasteData>): void -Reads the system pasteboard content. This API uses an asynchronous callback to return the result. +Obtains a **PasteData** object from the pasteboard. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[PasteData](#pastedata)> | Yes | Callback used to return the system pasteboard data. | +| callback | AsyncCallback<[PasteData](#pastedata)> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined** and **data** is the system pasteboard data. Otherwise, **err** is an error object.| **Example** - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.getPasteData((error, pasteData) => { - if (error) { - console.error('Failed to getPasteData. Cause: ' + error.message); - return; - } - var text = pasteData.getPrimaryText(); - }); - ``` +```js +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getPasteData((err, pasteData) => { + if (err) { + console.error('Failed to get PasteData. Cause: ' + err.message); + return; + } + var text = pasteData.getPrimaryText(); +}); +``` ### getPasteData getPasteData(): Promise<PasteData> -Reads the system pasteboard content. This API uses a promise to return the result. +Obtains a **PasteData** object from the pasteboard. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<[PasteData](#pastedata)> | Promise used to return the system pasteboard data. | +| Promise<[PasteData](#pastedata)> | Promise used to return the system pasteboard data.| **Example** - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - systemPasteboard.getPasteData().then((pasteData) => { - var text = pasteData.getPrimaryText(); - }).catch((error) => { - console.error('Failed to getPasteData. Cause: ' + error.message); - }) - ``` +```js +var systemPasteboard = pasteboard.getSystemPasteboard(); +systemPasteboard.getPasteData().then((pasteData) => { + var text = pasteData.getPrimaryText(); +}).catch((err) => { + console.error('Failed to get PasteData. Cause: ' + err.message); +}) +``` ### on('update')7+ on(type: 'update', callback: () =>void ): void -Subscribes to the content change event of the system pasteboard. If the pasteboard content changes, the callback is triggered. +Subscribes to the content change event of the system pasteboard. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Data type. The value **update** indicates the pasteboard content has changed. | -| callback | function | Yes | Callback invoked when the pasteboard content changes. | +| type | string | Yes| Event type. The value **'update'** indicates changes in the pasteboard content.| +| callback | function | Yes| Callback invoked when the pasteboard content changes.| **Example** - ```js - var systemPasteboard = pasteboard.getSystemPasteboard(); - var listener = () => { - console.info('The system pasteboard has changed'); - }; - systemPasteboard.on('update', listener); - ``` +```js +var systemPasteboard = pasteboard.getSystemPasteboard(); +var listener = () => { + console.info('The system pasteboard has changed.'); +}; +systemPasteboard.on('update', listener); +``` ### off('update')7+ @@ -981,120 +1248,120 @@ Unsubscribes from the system pasteboard content change event. **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes | Data type. The value **update** indicates the pasteboard content has changed. | -| callback | function | No | Callback invoked when the pasteboard content changes. | +| type | string | Yes| Event type. The value **'update'** indicates changes in the pasteboard content.| +| callback | function | No| Callback invoked when the pasteboard content changes.| **Example** - ```js - let listener = () => { - console.info('The system pasteboard has changed'); - }; - systemPasteboard.off('update', listener); - ``` +```js +let listener = () => { + console.info('The system pasteboard has changed.'); +}; +systemPasteboard.off('update', listener); +``` ### hasPasteData7+ hasPasteData(callback: AsyncCallback<boolean>): void -Checks whether the system pasteboard contains content. This API uses an asynchronous callback to return the result. +Checks whether the system pasteboard contains data. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<boolean> | Yes | Returns **true** if the pasteboard contains content; returns **false** otherwise. | +| callback | AsyncCallback<boolean> | Yes| Callback used to return the result. Returns **true** if the system pasteboard contains data; returns **false** otherwise.| **Example** - ```js - systemPasteboard.hasPasteData((err, data) => { - if (err) { - console.error('failed to hasPasteData because ' + JSON.stringify(err)); - return; - } - console.info('success hasPasteData : ' + JSON.stringify(data)); - }); - ``` +```js +systemPasteboard.hasPasteData((err, data) => { + if (err) { + console.error('Failed to check the PasteData. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in checking the PasteData. Data: ' + JSON.stringify(data)); +}); +``` ### hasPasteData7+ -hasPasteData(): Promise<boolean> +hasPasteData(): Promise<boolean> -Checks whether the system pasteboard contains content. This API uses a promise to return the result. +Checks whether the system pasteboard contains data. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<boolean> | Returns **true** if the pasteboard contains content; returns **false** otherwise. | +| Promise<boolean> | Promise used to return the result. Returns **true** if the system pasteboard contains data; returns **false** otherwise.| **Example** - ```js - systemPasteboard.hasPasteData().then((data) => { - console.info('success hasPasteData : ' + JSON.stringify(data)); - }).catch((error) => { - console.error('failed to hasPasteData because ' + JSON.stringify(error)); - }); - ``` +```js +systemPasteboard.hasPasteData().then((data) => { + console.info('Succeeded in checking the PasteData. Data: ' + JSON.stringify(data)); +}).catch((err) => { + console.error('Failed to check the PasteData. Cause: ' + JSON.stringify(err)); +}); +``` ### clear7+ -clear(callback: AsyncCallback<void>): void +clear(callback: AsyncCallback<void>): void -Clears the system pasteboard content. This API uses an asynchronous callback to return the result. +Clears the system pasteboard. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Parameters** -| Name | Type | Mandatory | Description | +| Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| callback | AsyncCallback<void> | Yes | Callback used to return the result. | +| callback | AsyncCallback<void> | Yes| Callback used to return the result. If the operation is successful, **err** is **undefined**; otherwise, **err** is an error object.| **Example** - ```js - systemPasteboard.clear((err, data) => { - if (err) { - console.error('failed to clear because ' + JSON.stringify(err)); - return; - } - console.info('success clear'); - }); - ``` +```js +systemPasteboard.clear((err, data) => { + if (err) { + console.error('Failed to clear the PasteData. Cause: ' + JSON.stringify(err)); + return; + } + console.info('Succeeded in clearing the PasteData.'); +}); +``` ### clear7+ -clear(): Promise<void> +clear(): Promise<void> -Clears the system pasteboard content. This API uses a promise to return the result. +Clears the system pasteboard. This API uses a promise to return the result. **System capability**: SystemCapability.MiscServices.Pasteboard **Return value** -| Type | Description | +| Type| Description| | -------- | -------- | -| Promise<void> | Promise used to return the result. | +| Promise<void> | Promise that returns no value.| **Example** - ```js - systemPasteboard.clear().then((data) => { - console.info('success clear'); - }).catch((error) => { - console.error('failed to clear because ' + JSON.stringify(error)); - }); - ``` +```js +systemPasteboard.clear().then((data) => { + console.info('Succeeded in clearing the PasteData.'); +}).catch((err) => { + console.error('Failed to clear the PasteData. Cause: ' + JSON.stringify(err)); +}); +``` diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md index 76d8bef4a2a4dd2606207a1f71c91d6703c99d43..1f3f64ff1aaaa2b5267cdfc55632c46b986df74f 100644 --- a/en/application-dev/reference/apis/js-apis-privacyManager.md +++ b/en/application-dev/reference/apis/js-apis-privacyManager.md @@ -3,7 +3,6 @@ The **PrivacyManager** module provides APIs for privacy management, such as management of permission usage records. > **NOTE** -> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. > The APIs of this module are system APIs and cannot be called by third-party applications. @@ -16,7 +15,7 @@ import privacyManager from '@ohos.privacyManager'; ## privacyManager.addPermissionUsedRecord -addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise<number> +addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number): Promise<void> Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses a promise to return the result. The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. @@ -29,7 +28,7 @@ The permission usage record includes the application identity of the invoker, na | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID of the invoker. | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission.| | successCount | number | Yes | Number of successful accesses.| | failCount | number | Yes | Number of failed accesses.| @@ -38,20 +37,28 @@ The permission usage record includes the application identity of the invoker, na | Type | Description | | :------------ | :---------------------------------- | -| Promise<number> | Promise used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| +| Promise<void> | Promise that returns no value.| **Example** ```js -var tokenID = appInfo.accessTokenId; // accessTokenId can be obtained by using getApplicationInfo(). -privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0).then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0).then(() => { + console.log('addPermissionUsedRecord success'); + }).catch((err) => { + console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## privacyManager.addPermissionUsedRecord -addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback<number>): void +addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: number, failCount: number, callback: AsyncCallback<void>): void Adds a permission usage record when an application protected by the permission is called by another service or application. This API uses an asynchronous callback to return the result. The permission usage record includes the application identity of the invoker, name of the permission used, and number of successful and failed accesses to the application. @@ -64,19 +71,29 @@ The permission usage record includes the application identity of the invoker, na | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | Yes | Application token ID of the invoker. | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md). | | permissionName | string | Yes | Name of the permission.| | successCount | number | Yes | Number of successful accesses.| | failCount | number | Yes | Number of failed accesses.| -| callback | AsyncCallback<number> | Yes | Callback used to return the result. If **0** is returned, the record is added successfully. If **-1** is returned, the record fails to be added.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| **Example** ```js -var tokenID = appInfo.accessTokenId; // accessTokenId can be obtained by using getApplicationInfo(). -privacyManager.privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (err, data) => { - console.log(`callback: data->${JSON.stringify(data)}`); -}); +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (data, err) => { + if (err) { + console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); + } else { + console.log('addPermissionUsedRecord success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## privacyManager.getPermissionUsedRecords @@ -104,19 +121,27 @@ Obtains historical permission usage records. This API uses a promise to return t **Example** ```js +import privacyManager from '@ohos.privacyManager'; + let request = { "tokenId": 1, - "isRemote": 1, + "isRemote": false, "deviceId": "device", "bundleName": "bundle", - "permissionNames": 1, + "permissionNames": [], "beginTime": 0, "endTime": 1, "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; -privacyManager.getPermissionUsedRecords(request).then(data => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + privacyManager.getPermissionUsedRecords(request).then((data) => { + console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + }).catch((err) => { + console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## privacyManager.getPermissionUsedRecords @@ -134,24 +159,256 @@ Obtains historical permission usage records. This API uses an asynchronous callb | Name | Type | Mandatory| Description | | -------- | ------------------- | ---- | ------------------------------------------ | | request | [PermissionUsedRequest](#permissionusedrequest) | Yes| Request for querying permission usage records.| -| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback used to return the permission usage records obtained.| +| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | Yes| Callback invoked to return the permission usage records obtained.| **Example** ```js +import privacyManager from '@ohos.privacyManager'; + let request = { "tokenId": 1, - "isRemote": 1, + "isRemote": false, "deviceId": "device", "bundleName": "bundle", - "permissionNames": 1, + "permissionNames": [], "beginTime": 0, "endTime": 1, "flag":privacyManager.PermissionUsageFlag.FLAG_PERMISSION_USAGE_DETAIL, }; -privacyManager.getPermissionUsedRecords(request, (err, data) => { - console.log(`promise: data->${JSON.stringify(data)}`); -}); +try { + privacyManager.getPermissionUsedRecords(request, (err, data) => { + if (err) { + console.log(`getPermissionUsedRecords fail, err->${JSON.stringify(err)}`); + } else { + console.log(`getPermissionUsedRecords success, data->${JSON.stringify(data)}`); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.startUsingPermission + +startUsingPermission(tokenID: number, permissionName: string): Promise<void> + +Starts to record a permission usage event. This API is called by a system service and uses a promise to return the result. The permissions used by an app in the foreground and background can be observed, and the permission usage records can be saved. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS").then(() => { + console.log('startUsingPermission success'); + }).catch((err) => { + console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.startUsingPermission + +startUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void + +Starts to record a permission usage event. This API is called by a system service and uses an asynchronous callback to return the result. The permissions used by an app in the foreground and background can be observed and saved. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | --------------------- | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (data, err) => { + if (err) { + console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('startUsingPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.stopUsingPermission + +stopUsingPermission(tokenID: number, permissionName: string): Promise<void> + +Stops recording the permission usage event. This API is called by a system service and uses a promise to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | ------ | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | + +**Return value** + +| Type | Description | +| ------------- | --------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS").then(() => { + console.log('stopUsingPermission success'); + }).catch((err) => { + console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.stopUsingPermission + +stopUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void + +Stops recording the permission usage event. This API is called by the system service and uses an asynchronous callback to return the result. **startUsingPermission** and **stopUsingPermission** are used in pairs. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS (available only to system applications) + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------------- | --------------------- | ---- | ------------------------------------ | +| tokenID | number | Yes | Application token ID of the invoker. You can obtain it from [ApplicationInfo](js-apis-bundle-ApplicationInfo.md).| +| permissionName | string | Yes | Permission to use. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let tokenID = 0; // You can use getApplicationInfo to obtain the access token ID. +try { + privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (data, err) => { + if (err) { + console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); + } else { + console.log('stopUsingPermission success'); + } + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.on + +on(type: 'activeStateChange', permissionNameList: Array<string>, callback: Callback<ActiveChangeResponse>): void + +Subscribes to the changes in the usage of the specified permission list. This API uses a callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type to subscribe to. The value is **activeStateChange**, which indicates permission usage change event. | +| permissionNameList | Array<string> | No | List of permissions to be observed. If this parameter is left empty, the usage changes of all permissions are observed. | +| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | Yes| Callback invoked to return a change in permission usage.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let permissionNameList: Array = []; +try { + atManager.on('activeStateChange', permissionNameList, (data) => { + console.debug("receive permission state change, data:" + JSON.stringify(data)); + }); +} catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} +``` + +## privacyManager.off + +off(type: 'activeStateChange', permissionNameList: Array<string>, callback?: Callback<ActiveChangeResponse>): void; + +Unsubscribes from the changes in the usage of the specified permission list. This API uses a callback to return the result. + +This is a system API. + +**Required permissions**: ohos.permission.PERMISSION_USED_STATS + +**System capability**: SystemCapability.Security.AccessToken + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------------------ | --------------------- | ---- | ------------------------------------------------------------ | +| type | string | Yes | Event type to subscribe to. The value is **activeStateChange**, which indicates permission usage change event. | +| permissionNameList | Array<string> | No | List of permissions to be observed. If this parameter is left blank, the usage changes of all permissions are unsubscribed from. The value must be the same as that specified in **on()**.| +| callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | No| Callback for the permission usage change event.| + +**Example** + +```js +import privacyManager from '@ohos.privacyManager'; + +let permissionNameList: Array = []; +try { + privacyManager.off('activeStateChange', permissionNameList); +}catch(err) { + console.log(`catch err->${JSON.stringify(err)}`); +} ``` ## PermissionUsageFlag @@ -236,3 +493,28 @@ Represents the details of a single access record. | status | number | No | Access status. | | timestamp | number | No | Access timestamp, in ms.| | accessDuration | number | No | Access duration, in ms. | + +## PermissionActiveStatus + +Enumerates of permission usage statuses. + +**System capability**: SystemCapability.Security.AccessToken + +| Name | Default Value| Description | +| ------------------------- | ------ | ---------------- | +| PERM_INACTIVE | 0 | The permission is not used. | +| PERM_ACTIVE_IN_FOREGROUND | 1 | The permission is being used in the foreground.| +| PERM_ACTIVE_IN_BACKGROUND | 2 | The permission is being used in the background.| + +## ActiveChangeResponse + +Defines the detailed permission usage information. + + **System capability**: SystemCapability.Security.AccessToken + +| Name | Type | Readable| Writable| Description | +| -------------- | ---------------------- | ---- | ---- | --------------------- | +| tokenId | number | Yes | No | Token ID of the application that applies for the permission. | +| permissionName | string | Yes | No | Name of the permission.| +| deviceId | string | Yes | No | Device number. | +| activeStatus | [PermissionActiveStatus](#permissionactivestatus) | Yes | No | Permission usage status. | diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md index d2dcd1fdd0b4dd88d4a6917d260f052aa9198eca..245865cc40144c8910a4c245a9485641c0452627 100644 --- a/en/application-dev/reference/apis/js-apis-screen-lock.md +++ b/en/application-dev/reference/apis/js-apis-screen-lock.md @@ -233,61 +233,46 @@ Locks the screen. This API uses a promise to return the result. }); ``` +## EventType -## screenlock.on9+ - -on(type: 'beginWakeUp' | 'endWakeUp' | 'beginScreenOn' | 'endScreenOn' | 'beginScreenOff' | 'endScreenOff' | 'unlockScreen' | 'beginExitAnimation', callback: Callback\): void - -Subscribes to screen lock status changes. +Defines the system event type. **System capability**: SystemCapability.MiscServices.ScreenLock -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.| -| callback | Callback\ | Yes| Callback used to return the result.| - -**Example** - - ```js - screenlock.on('beginWakeUp', () => { - console.log('beginWakeUp triggered'); - }); - ``` - -## screenlock.on9+ - -on(type: 'beginSleep' | 'endSleep' | 'changeUser', callback: Callback\): void - -Subscribes to screen lock status changes. +| Name| Description| +| -------- | -------- | +| beginWakeUp | Wakeup starts when the event starts.| +| endWakeUp | Wakeup ends when the event ends.| +| beginScreenOn | Screen turn-on starts when the event starts.| +| endScreenOn | Screen turn-on ends when the event ends.| +| beginScreenOff | Screen turn-off starts when the event starts.| +| endScreenOff | Screen turn-off ends when the event ends.| +| unlockScreen | The screen is unlocked.| +| lockScreen | The screen is locked.| +| beginExitAnimation | Animation starts to exit.| +| beginSleep | The screen enters sleep mode.| +| endSleep | The screen exits sleep mode.| +| changeUser | The user is switched.| +| screenlockEnabled | Screen lock is enabled.| +| serviceRestart | The screen lock service is restarted.| + + +## SystemEvent + +Defines the structure of the system event callback. **System capability**: SystemCapability.MiscServices.ScreenLock -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** - -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.| -| callback | Callback\ | Yes| Callback used to return the result. | - -**Example** +| Name| Description| +| -------- | -------- | +| eventType | System event type.| +| params | System event parameters.| - ```js - screenlock.on('beginSleep', (why) => { - console.log('beginSleep triggered:' + why); - }); - ``` -## screenlock.on9+ +## screenlock.onSystemEvent9+ -on(type: 'screenlockEnabled', callback: Callback\): void +onSystemEvent(callback: Callback\): boolean -Subscribes to screen lock status changes. +Registers a callback for system events related to screen locking. **System capability**: SystemCapability.MiscServices.ScreenLock @@ -297,41 +282,26 @@ Subscribes to screen lock status changes. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"screenlockEnabled"**: Screen lock is enabled.| -| callback | Callback\ | Yes| Callback used to return the result. | - -**Example** - - ```js - screenlock.on('screenlockEnabled', (isEnabled) => { - console.log('screenlockEnabled triggered, result:' + isEnabled); - }); - ``` - -## screenlock.off9+ +| callback | Callback\ | Yes| Callback for system events related to screen locking| -off(type: 'beginWakeUp' | 'endWakeUp' | 'beginScreenOn' | 'endScreenOn' | 'beginScreenOff' | 'endScreenOff' - | 'unlockScreen' | 'beginExitAnimation' | 'screenlockEnabled' | 'beginSleep' | 'endSleep' | 'changeUser', callback: Callback\): void - -Unsubscribes from screen lock status changes. - -**System capability**: SystemCapability.MiscServices.ScreenLock - -**System API**: This is a system API and cannot be called by third-party applications. - -**Parameters** +**Return value** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type.
- **"beginWakeUp"**: Wakeup starts.
- **"endWakeUp"**: Wakeup ends.
- **"beginScreenOn"**: Screen turn-on starts.
- **"endScreenOn"**: Screen turn-on ends.
- **"beginScreenOff"**: Screen turn-off starts.
- **"endScreenOff"**: Screen turn-off ends.
- **"unlockScreen"**: The screen is unlocked.
- **"beginExitAnimation"**: Animation starts to exit.
- **"screenlockEnabled"**: Screen lock is enabled.
- **"beginSleep"**: The screen enters sleep mode.
- **"endSleep"**: The screen exits sleep mode.
- **"changeUser"**: The user is switched.| -| callback | Callback\ | Yes| Callback used to return the result.| +| Type | Description | +| ------- | -------------------------------------------- | +| boolean | The value **true** means that the callback is registered successfully, and **false** means the opposite.| **Example** ```js - screenlock.off('beginWakeUp', () => { - console.log("callback"); - }); + let isSuccess = screenlock.onSystemEvent((err, event)=>{ + console.log(`onSystemEvent:callback:${event.eventType}`) + if (err) { + console.log(`onSystemEvent callback error -> ${JSON.stringify(err)}`); + } + }); + if (!isSuccess) { + console.log(`onSystemEvent result is false`) + } ``` ## screenlock.sendScreenLockEvent9+ @@ -375,7 +345,7 @@ Sends an event to the screen lock service. This API uses a promise to return the | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | event | String | Yes| Event type.
- **"unlockScreenResult"**: Screen unlock result.
- **"screenDrawDone"**: Screen drawing is complete.| -| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock failed.
- **2**: The unlock was canceled.| +| parameter | number | Yes| Screen unlock status.
- **0**: The unlock is successful.
- **1**: The unlock fails.
- **2**: The unlock is canceled.| **Return value** diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index ec32f9279c250a823484d0894e5ce56c82386601..193e6a66e01abe1a23b94805038b0613b7640b13 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -3,8 +3,8 @@ The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. > **NOTE** ->- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ->- The APIs of this module are system APIs and cannot be called by third-party applications. +> +> - The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import @@ -60,7 +60,7 @@ Sets the system time. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------ | ---- | ------------------ | -| time | number | Yes | Timestamp to set, in milliseconds. | +| time | number | Yes | Timestamp to set, in milliseconds.| **Return value** @@ -83,7 +83,7 @@ Sets the system time. This API uses a promise to return the result. ## systemTime.getCurrentTime8+ -getCurrentTime(isNano?: boolean, callback: AsyncCallback<number>): void +getCurrentTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. @@ -93,7 +93,7 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | | callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -109,6 +109,33 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal ``` +## systemTime.getCurrentTime8+ + +getCurrentTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since the Unix epoch. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + + ```js + systemTime.getCurrentTime((error, data) => { + if (error) { + console.error(`failed to systemTime.getCurrentTime because ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.getCurrentTime success data : ` + JSON.stringify(data)); + }); + ``` + + ## systemTime.getCurrentTime8+ getCurrentTime(isNano?: boolean): Promise<number> @@ -121,7 +148,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** @@ -142,7 +169,7 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return ## systemTime.getRealActiveTime8+ -getRealActiveTime(isNano?: boolean, callback: AsyncCallback<number>): void +getRealActiveTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system start, excluding the deep sleep time. This API uses an asynchronous callback to return the result. @@ -152,7 +179,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | | callback | AsyncCallback<number> | Yes | Callback used to return the time.| **Example** @@ -168,6 +195,33 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ``` +## systemTime.getRealActiveTime8+ + +getRealActiveTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since system start, excluding the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| + +**Example** + + ```js + systemTime.getRealActiveTime((error, data) => { + if (error) { + console.error(`failed to systemTime.getRealActiveTimebecause ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.getRealActiveTime success data : ` + JSON.stringify(data)); + }); + ``` + + ## systemTime.getRealActiveTime8+ getRealActiveTime(isNano?: boolean): Promise<number> @@ -180,7 +234,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** @@ -201,7 +255,7 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This ## systemTime.getRealTime8+ -getRealTime(isNano?: boolean, callback: AsyncCallback<number>): void +getRealTime(isNano: boolean, callback: AsyncCallback<number>): void Obtains the time elapsed since system start, including the deep sleep time. This API uses an asynchronous callback to return the result. @@ -211,7 +265,7 @@ Obtains the time elapsed since system start, including the deep sleep time. This | Name | Type | Mandatory| Description | | -------- | --------------------------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | Yes | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | | callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -229,6 +283,32 @@ Obtains the time elapsed since system start, including the deep sleep time. This ## systemTime.getRealTime8+ +getRealTime(callback: AsyncCallback<number>): void + +Obtains the time elapsed since system start, including the deep sleep time. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | + +**Example** + + ```js + systemTime.getRealTime((error, data) => { + if (error) { + console.error(`failed to systemTime.getRealTime because ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.getRealTime success data: ` + JSON.stringify(data)); + }); + ``` + +## systemTime.getRealTime8+ + getRealTime(isNano?: boolean): Promise<number> Obtains the time elapsed since system start, including the deep sleep time. This API uses a promise to return the result. @@ -239,7 +319,7 @@ Obtains the time elapsed since system start, including the deep sleep time. This | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** @@ -278,7 +358,7 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Example** ```js - var data = new Date("October 13, 2020 11:13:00"); + var data = new Date(); systemTime.setDate(data,(error, data) => { if (error) { console.error('failed to systemTime.setDate because ' + JSON.stringify(error)); @@ -314,7 +394,7 @@ Sets the system date. This API uses a promise to return the result. **Example** ```js - var data = new Date("October 13, 2020 11:13:00"); + var data = new Date(); systemTime.setDate(data).then((value) => { console.log(`systemTime.setDate success data : ` + JSON.stringify(value)); }).catch((error) => { diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md index f952b38c3de656864d42ad8c2c42b108b0c53f3d..b7880eebd39edf24bec47aafaece182f6a1ef5c2 100644 --- a/en/application-dev/reference/apis/js-apis-system-timer.md +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -2,7 +2,7 @@ The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services. -> **NOTE**
+> **NOTE** >- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. >- The APIs of this module are system APIs and cannot be called by third-party applications. @@ -24,12 +24,9 @@ Creates a timer. This API uses an asynchronous callback to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | -| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | -| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------| ---- | --------------------------------------------------------------------------- | +| options | [TimerOptions](#timeroptions) | Yes | Timer options. | **Return value** @@ -68,12 +65,9 @@ Creates a timer. This API uses a promise to return the result. **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | -| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| -| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | -| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | -| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | +| Name | Type | Mandatory| Description | +| ------- | ---------------------------------| ---- | --------------------------------------------------------------------------- | +| options | [TimerOptions](#timeroptions) | Yes | Timer options. | **Return value** @@ -112,7 +106,7 @@ Starts a timer. This API uses an asynchronous callback to return the result. | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| timer | number | Yes | ID of the timer. | | triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | @@ -125,8 +119,10 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 10000, (error, data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime, (error, data) => { if (error) { console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); return; @@ -136,7 +132,7 @@ export default { } } ``` - + ## systemTime.startTimer startTimer(timer: number, triggerTime: number): Promise<void> @@ -149,9 +145,7 @@ Starts a timer. This API uses a promise to return the result. | Name | Type | Mandatory| Description | | ----------- | --------------------------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | -| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | - +| timer | number | Yes | ID of the timer. | | triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | **Example** @@ -162,8 +156,10 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 10000).then((data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime).then((data) => { console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); }).catch((error) => { console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); @@ -196,9 +192,11 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) - systemTimer.stoptTimer(timerId, 10000, (error, data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) + systemTimer.stoptTimer(timerId, (error, data) => { if (error) { console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); return; @@ -222,7 +220,7 @@ Stops a timer. This API uses a promise to return the result. | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | -| timer | number | Yes | ID of the timer. | +| timer | number | Yes | ID of the timer. | **Example** @@ -233,9 +231,11 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) - systemTimer.stoptTimer(timerId, 10000).then((data) => { + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) + systemTimer.stoptTimer(timerId).then((data) => { console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); }).catch((error) => { console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); @@ -268,8 +268,10 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) systemTimer.destroyTimer(timerId, (error, data) => { if (error) { @@ -306,10 +308,12 @@ export default { type: systemTimer.TIMER_TYPE_REALTIME, repeat:false } - let timerId = systemTimer.Timer(options) - systemTimer.startTimer(timerId, 100000) + let timerId = systemTimer.createTimer(options) + let triggerTime = new Date().getTime() + triggerTime += 3000 + systemTimer.startTimer(timerId, triggerTime) systemTimer.stopTimer(timerId) - systemTimer.destroytTimer(timerId, 10000).then((data) => { + systemTimer.destroyTimer(timerId, 10000).then((data) => { console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); }).catch((error) => { console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); @@ -317,3 +321,17 @@ export default { } } ``` + + ## TimerOptions + +Defines the initialization options for **createTimer**. + +**System capability**: SystemCapability.MiscServices.Time + +| Name | Type | Mandatory| Description | +| -------- | ------------------| ---- | ------------------------------------------------------------------------------------------------------------------------- | +| type | number | Yes | **const TIMER_TYPE_REALTIME**: sets the timer to the CPU time type. (When the set time is later than the timer startup time, the timer expires.) If it is not specified, the timer is of the wall-time type.
**const TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**const TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**const TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported). | +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | +| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An application MainAbility can be started, but not a Service ability.) | +| callback | number | Yes | Callback used to return the timer ID. | diff --git a/en/application-dev/reference/apis/js-apis-url.md b/en/application-dev/reference/apis/js-apis-url.md index c060118f7e466da51f2ee5b7fdd6ad20f7e256ca..221decfb35ae0a6667eb9f96c60c713f8536949b 100755 --- a/en/application-dev/reference/apis/js-apis-url.md +++ b/en/application-dev/reference/apis/js-apis-url.md @@ -128,7 +128,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th | Type| Description| | -------- | -------- | -| IterableIterator<[string, string]> | ES6 iterator.| +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -192,7 +192,7 @@ Obtains the value of the first key-value pair based on the specified key. | Type| Description| | -------- | -------- | | string | Returns the value of the first key-value pair if obtained.| -| null | Returns null if no value is obtained.| +| null | Returns **null** if no value is obtained.| **Example** @@ -333,7 +333,7 @@ Obtains an ES6 iterator. Each item of the iterator is a JavaScript array, and th | Type| Description| | -------- | -------- | -| IterableIterator<[string, string]> | ES6 iterator.| +| IterableIterator<[string, string]> | ES6 iterator.| **Example** @@ -404,7 +404,7 @@ Creates a URL. | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | url | string | Yes| Input object.| -| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| +| base | string \| URL | No| Input parameter, which can be any of the following:
- **string**: string
- **URL**: string or object| **Example** @@ -442,7 +442,7 @@ Converts the parsed URL into a string. ```js const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toString() +url.toString(); ``` @@ -463,5 +463,5 @@ Converts the parsed URL into a JSON string. **Example** ```js const url = new Url.URL('http://username:password@host:8080/directory/file?query=pppppp#qwer=da'); -url.toJSON() +url.toJSON(); ``` diff --git a/en/application-dev/reference/apis/js-apis-vibrator.md b/en/application-dev/reference/apis/js-apis-vibrator.md index 8d0c0ad48f1dc919c5032dc1d37ad39026071583..699ab299f5050594fd943c95e36c0538e9d0ec24 100644 --- a/en/application-dev/reference/apis/js-apis-vibrator.md +++ b/en/application-dev/reference/apis/js-apis-vibrator.md @@ -13,11 +13,11 @@ The **Vibrator** module provides APIs for triggering or stopping vibration. import vibrator from '@ohos.vibrator'; ``` -## vibrator.vibrate +## vibrator.startVibration9+ -vibrate(duration: number): Promise<void> +startVibration(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void -Triggers vibration with the specified duration. This API uses a promise to return the result. +Triggers vibration with the specified effect and attribute. This API uses a promise to return the result. **Required permissions**: ohos.permission.VIBRATE @@ -25,29 +25,37 @@ Triggers vibration with the specified duration. This API uses a promise to retur **Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------ | ---- | ---------------------- | -| duration | number | Yes | Vibration duration, in ms.| - -**Return value** - -| Type | Description | -| ------------------- | -------------------------------------- | -| Promise<void> | Promise that returns no value.| +| Name | Type | Mandatory| Description | +| --------- | -------------------------------------- | ---- | :--------------------------------------------------------- | +| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. | +| attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | +| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** - ```js - vibrator.vibrate(1000).then(()=>{ - console.log("Promise returned to indicate a successful vibration."); - }, (error)=>{ - console.log("error.code"+error.code+"error.message"+error.message); - }); - ``` +```js +try { + vibrator.startVibration({ + type:'time', + duration:1000, + },{ + id:0, + usage: 'alarm' + }, (error)=>{ + if(error){ + console.log('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); + }else{ + console.log('Callback returned to indicate a successful vibration.'); + } + }); +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} +``` -## vibrator.vibrate9+ +## vibrator.startVibration9+ -vibrate(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> +startVibration(effect: VibrateEffect, attribute: VibrateAttribute): Promise<void> Triggers vibration with the specified effect and attribute. This API uses a promise to return the result. @@ -58,7 +66,7 @@ Triggers vibration with the specified effect and attribute. This API uses a prom **Parameters** | Name | Type | Mandatory| Description | -| --------- | -------------------------------------- | ---- | :------------- | +| --------- | -------------------------------------- | ---- | -------------- | | effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect.| | attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute.| @@ -70,146 +78,60 @@ Triggers vibration with the specified effect and attribute. This API uses a prom **Example** -```js -vibrator.vibrate({ + ```js +try { + vibrator.startVibration({ type: 'time', duration: 1000 -}, { - id: 0, - usage: 'alarm' -}).then(()=>{ - console.log("Promise returned to indicate a successful vibration"); -}).catch((error)=>{ - console.log("error.code" + error.code + "error.message" + error.message); -}) -``` - -## vibrator.vibrate - -vibrate(duration: number, callback?: AsyncCallback<void>): void - -Triggers vibration with the specified duration. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.VIBRATE - -**System capability**: SystemCapability.Sensors.MiscDevice - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------------------------------- | -| duration | number | Yes | Vibration duration, in ms. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| - -**Example** - - ```js - vibrator.vibrate(1000,function(error){ - if(error){ - console.log("error.code" + error.code + "error.message" + error.message); - }else{ - console.log("Callback returned to indicate a successful vibration."); - } - }) + }, { + id: 0, + usage: 'alarm' + }).then(()=>{ + console.log('Promise returned to indicate a successful vibration'); + }).catch((error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); + }) +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` +## vibrator.stopVibration9+ -## vibrator.vibrate +stopVibration(stopMode: VibratorStopMode, callback: AsyncCallback<void>): void -vibrate(effectId: EffectId): Promise<void> - -Triggers vibration with the specified effect. This API uses a promise to return the result. +Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. **Required permissions**: ohos.permission.VIBRATE **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** -| Name | Type | Mandatory| Description | -| -------- | --------------------- | ---- | ------------------ | -| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID.| -**Return value** -| Type | Description | -| ------------------- | -------------------------------------- | -| Promise<void> | Promise that returns no value.| - -**Example** - ```js - vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ - console.log("Promise returned to indicate a successful vibration."); - }, (error)=>{ - console.log("error.code" + error.code + "error.message" + error.message); - }); - ``` - - -## vibrator.vibrate - -vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void - -Triggers vibration with the specified effect. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.VIBRATE - -**System capability**: SystemCapability.Sensors.MiscDevice - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------- | ---- | ---------------------------------------------------------- | -| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | +| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| **Example** ```js - vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ - if(error){ - console.log("error.code" + error.code + "error.message" + error.message); - }else{ - console.log("Callback returned to indicate a successful vibration."); - } - }) +try { + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate successful.'); + } + }) +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` -## vibrator.vibrate9+ - -vibrate(effect: VibrateEffect, attribute: VibrateAttribute, callback: AsyncCallback<void>): void - -Triggers vibration with the specified effect and attribute. This API uses an asynchronous callback to return the result. - -**Required permissions**: ohos.permission.VIBRATE +## vibrator.stopVibration9+ -**System capability**: SystemCapability.Sensors.MiscDevice - -**Parameters** - -| Name | Type | Mandatory| Description | -| --------- | -------------------------------------- | ---- | :--------------------------------------------------------- | -| effect | [VibrateEffect](#vibrateeffect9) | Yes | Vibration effect. | -| attribute | [VibrateAttribute](#vibrateattribute9) | Yes | Vibration attribute. | -| callback | AsyncCallback<void> | Yes | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| - -**Example** - -```js -vibrator.vibrate({ - type:'time', - duration:1000, -},{ - id:0, - usage: 'alarm' -}, (error)=>{ - if(error){ - console.log("vibrate fail, error.code:" + error.code + ",error.message:" + error.message); - }else{ - console.log("Callback returned to indicate a successful vibration."); - } -}); -``` - -## vibrator.stop - -stop(stopMode: VibratorStopMode): Promise<void> +stopVibration(stopMode: VibratorStopMode): Promise<void> Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. @@ -218,6 +140,7 @@ Stops the vibration with the specified **stopMode**. This API uses a promise to **System capability**: SystemCapability.Sensors.MiscDevice **Parameters** + | Name | Type | Mandatory| Description | | -------- | ------------------------------------- | ---- | ------------------------ | | stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration.| @@ -231,43 +154,17 @@ Stops the vibration with the specified **stopMode**. This API uses a promise to **Example** ```js - vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ - console.log("Promise returned to indicate a successful vibration."); - }, (error)=>{ - console.log("error.code" + error.code + "error.message" + error.message); - }); - ``` - - -## vibrator.stop - -stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void; - -Stops the vibration with the specified **stopMode**. This API uses an asynchronous callback to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. - -**Required permissions**: ohos.permission.VIBRATE - -**System capability**: SystemCapability.Sensors.MiscDevice - -**Parameters** -| Name | Type | Mandatory| Description | -| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | -| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | -| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| - -**Example** - - ```js - vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ - if(error){ - console.log("error.code" + error.code + "error.message" + error.message); - }else{ - console.log("Callback returned to indicate a successful stop."); - } - }) +try { + vibrator.stopVibration(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); + }, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); + }); +} catch(err) { + console.info('errCode: ' + err.code + ' ,msg: ' + err.message); +} ``` - ## EffectId Describes the vibration effect ID. @@ -352,3 +249,201 @@ Enumerates the vibration scenarios. | media | string | Multimedia vibration scenario. | | physicalFeedback | string | Physical feedback vibration scenario. | | simulateReality | string | Simulated reality vibration scenario. | + +## vibrator.vibrate(deprecated) + +vibrate(duration: number): Promise<void> + +Triggers vibration with the specified duration. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9-1) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------------------- | +| duration | number | Yes | Vibration duration, in ms.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +vibrator.vibrate(1000).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); +}, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); +}); + ``` + +## vibrator.vibrate(deprecated) + +vibrate(duration: number, callback?: AsyncCallback<void>): void + +Triggers vibration with the specified duration. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------------- | +| duration | number | Yes | Vibration duration, in ms. | +| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + + ```js +vibrator.vibrate(1000,function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate a successful vibration.'); + } +}) + ``` + + +## vibrator.vibrate(deprecated) + +vibrate(effectId: EffectId): Promise<void> + +Triggers vibration with the specified effect. This API uses a promise to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9-1) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ------------------ | +| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); +}, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); +}); + ``` + + +## vibrator.vibrate(deprecated) + +vibrate(effectId: EffectId, callback?: AsyncCallback<void>): void + +Triggers vibration with the specified effect. This API uses an asynchronous callback to return the result. + +This API is deprecated since API version 9. You are advised to use [vibrator.startVibration](#vibratorstartvibration9) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------------- | +| effectId | [EffectId](#effectid) | Yes | Preset vibration effect ID. | +| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration starts, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + + ```js +vibrator.vibrate(vibrator.EffectId.EFFECT_CLOCK_TIMER, function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate a successful vibration.'); + } +}) + ``` + +## vibrator.stop(deprecated) + +stop(stopMode: VibratorStopMode): Promise<void> + +Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. + +This API is deprecated since API version 9. You are advised to use [vibrator.stopVibration](#vibratorstopvibration9-1) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------ | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration.| + +**Return value** + +| Type | Description | +| ------------------- | -------------------------------------- | +| Promise<void> | Promise that returns no value.| + +**Example** + + ```js +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET).then(()=>{ + console.log('Promise returned to indicate a successful vibration.'); +}, (error)=>{ + console.log('error.code' + error.code + 'error.message' + error.message); +}); + ``` + + +## vibrator.stop(deprecated) + +stop(stopMode: VibratorStopMode, callback?: AsyncCallback<void>): void + +Stops the vibration with the specified **stopMode**. This API uses a promise to return the result. If the specified **stopMode** is different from the mode used to trigger the vibration, this API fails to be called. + +This API is deprecated since API version 9. You are advised to use [vibrator.stopVibration](#vibratorstopvibration9) instead. + +**Required permissions**: ohos.permission.VIBRATE + +**System capability**: SystemCapability.Sensors.MiscDevice + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ | +| stopMode | [VibratorStopMode](#vibratorstopmode) | Yes | Mode to stop the vibration. | +| callback | AsyncCallback<void> | No | Callback used to the result. If the vibration stops, **err** is **undefined**. Otherwise, **err** is an error object.| + +**Example** + + ```js +vibrator.stop(vibrator.VibratorStopMode.VIBRATOR_STOP_MODE_PRESET, function(error){ + if(error){ + console.log('error.code' + error.code + 'error.message' + error.message); + }else{ + console.log('Callback returned to indicate successful.'); + } +}) + ``` diff --git a/en/application-dev/reference/apis/js-apis-wifi.md b/en/application-dev/reference/apis/js-apis-wifi.md index 7f5b41145c5831f3ecd0014687a52366b598f9d4..13014cfed8a6cc95d124535c89b399b12348395f 100644 --- a/en/application-dev/reference/apis/js-apis-wifi.md +++ b/en/application-dev/reference/apis/js-apis-wifi.md @@ -25,9 +25,9 @@ Enables WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.disableWifi @@ -44,9 +44,9 @@ Disables WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.isWifiActive @@ -61,9 +61,9 @@ Checks whether WLAN is enabled. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if WLAN is enabled; returns **false** otherwise.| ## wifi.scan @@ -78,9 +78,9 @@ Starts a scan for WLAN. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getScanInfos @@ -95,9 +95,9 @@ Obtains the scan result. This API uses a promise to return the result. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| + | **Type**| **Description**| + | -------- | -------- | + | Promise< Array<[WifiScanInfo](#wifiscaninfo)> > | Promise used to return the detected hotspots.| ## wifi.getScanInfos @@ -112,9 +112,9 @@ Obtains the scan result. This API uses an asynchronous callback to return the re **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiScanInfo](#wifiscaninfo)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the detected hotspots. Otherwise, **err** is a non-zero value and **data** is empty.| **Example** ```js @@ -247,9 +247,9 @@ Obtains the scan result. This API returns the result synchronously. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiScanInfo](#wifiscaninfo)> | Scan result obtained.| ## wifi.addDeviceConfig @@ -266,15 +266,15 @@ Adds network configuration. This API uses a promise to return the result. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the WLAN configuration ID. If **-1** is returned, the operation has failed.| ## WifiDeviceConfig @@ -412,10 +412,10 @@ Adds network configuration. This API uses an asynchronous callback to return the **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| ## wifi.addUntrustedConfig7+ @@ -430,15 +430,15 @@ Adds the configuration of an untrusted network. This API uses a promise to retur **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.addUntrustedConfig7+ @@ -453,10 +453,10 @@ Adds the configuration of an untrusted network. This API uses an asynchronous ca **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| ## wifi.removeUntrustedConfig7+ @@ -471,15 +471,15 @@ Removes the configuration of an untrusted network. This API uses a promise to re **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<boolean> | Promise used to return the result. If the operation is successful, **true** is returned; otherwise, **false** is returned.| ## wifi.removeUntrustedConfig7+ @@ -494,10 +494,10 @@ Removes the configuration of an untrusted network. This API uses an asynchronous **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to remove.| -| callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| + | callback | AsyncCallback<boolean> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is **true**. If the operation fails, **data** is **false**. If **err** is not **0**, an error has occurred.| ## wifi.addCandidateConfig9+ @@ -512,15 +512,15 @@ Adds the configuration of a candidate network. This API uses a promise to return **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<number> | Promise used to return the network configuration ID.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<number> | Promise used to return the network configuration ID.| ## wifi.addCandidateConfig9+ @@ -535,10 +535,10 @@ Adds the configuration of a candidate network. This API uses an asynchronous cal **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| -| callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration to add.| + | callback | AsyncCallback<number> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the network configuration ID. If **data** is **-1**, the operation has failed. If **err** is not **0**, an error has occurred.| ## wifi.removeCandidateConfig9+ @@ -553,15 +553,15 @@ Removes the configuration of a candidate network. This API uses a promise to ret **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | networkId | number | Yes| ID of the network configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| Promise<void> | Promise used to return the result.| + | **Type**| **Description**| + | -------- | -------- | + | Promise<void> | Promise used to return the result.| ## wifi.removeCandidateConfig9+ @@ -576,8 +576,8 @@ Removes the configuration of a candidate network. This API uses an asynchronous **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | networkId | number | Yes| ID of the network configuration to remove.| | callback | AsyncCallback<void> | Yes| Callback invoked to return the result. If the operation is successful, the value of **err** is **0**. If **err** is not **0**, an error has occurred.| @@ -594,9 +594,9 @@ Obtains candidate network configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Candidate network configuration obtained.| ## wifi.connectToCandidateConfig9+ @@ -611,9 +611,9 @@ Connects to a candidate network. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| ID of the candidate network configuration.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| ID of the candidate network configuration.| ## wifi.connectToNetwork @@ -630,15 +630,15 @@ Connects to the specified network. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| networkId | number | Yes| Network configuration ID.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | networkId | number | Yes| Network configuration ID.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.connectToDevice @@ -656,15 +656,15 @@ Connects to the specified network. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| WLAN configuration.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.disconnect @@ -682,9 +682,9 @@ Disconnects the network. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getSignalLevel @@ -699,16 +699,16 @@ Obtains the WLAN signal level. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| rssi | number | Yes| RSSI of the hotspot, in dBm.| -| band | number | Yes| Frequency band of the WLAN AP.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | rssi | number | Yes| RSSI of the hotspot, in dBm.| + | band | number | Yes| Frequency band of the WLAN AP.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | Signal level obtained. The value range is [0, 4].| + | **Type**| **Description**| + | -------- | -------- | + | number | Signal level obtained. The value range is [0, 4].| ## wifi.getLinkedInfo @@ -723,9 +723,9 @@ Obtains WLAN connection information. This API uses a promise to return the resul **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiLinkedInfo](#wifilinkedinfo)> | Promise used to return the WLAN connection information obtained.| ## wifi.getLinkedInfo @@ -740,9 +740,9 @@ Obtains WLAN connection information. This API uses an asynchronous callback to r **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiLinkedInfo](#wifilinkedinfo)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the WLAN connection information obtained. If **err** is not **0**, an error has occurred.| **Example** ```js @@ -844,9 +844,9 @@ Checks whether the WLAN is connected. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the WLAN is connected; returns **false** otherwise.| ## wifi.getSupportedFeatures7+ @@ -863,9 +863,9 @@ Obtains the features supported by this device. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | Feature value. | + | **Type**| **Description**| + | -------- | -------- | + | number | Feature value. | **Feature IDs** @@ -896,15 +896,15 @@ Checks whether the device supports the specified WLAN feature. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| featureId | number | Yes| Feature ID.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | featureId | number | Yes| Feature ID.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| ## wifi.getDeviceMacAddress7+ @@ -921,9 +921,9 @@ Obtains the device MAC address. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| string[] | MAC address obtained.| + | **Type**| **Description**| + | -------- | -------- | + | string[] | MAC address obtained.| ## wifi.getIpInfo7+ @@ -938,9 +938,9 @@ Obtains IP information. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| [IpInfo](#ipinfo7) | IP information obtained.| + | **Type**| **Description**| + | -------- | -------- | + | [IpInfo](#ipinfo7) | IP information obtained.| ## IpInfo7+ @@ -972,9 +972,9 @@ Obtains the country code. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| string | Country code obtained.| + | **Type**| **Description**| + | -------- | -------- | + | string | Country code obtained.| ## wifi.reassociate7+ @@ -991,9 +991,9 @@ Re-associates with the network. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.reconnect7+ @@ -1010,9 +1010,9 @@ Reconnects to the network. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getDeviceConfigs7+ @@ -1029,9 +1029,9 @@ Obtains network configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[WifiDeviceConfig](#wifideviceconfig)> | Array of network configuration obtained.| ## wifi.updateNetwork7+ @@ -1048,15 +1048,15 @@ Updates network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | config | [WifiDeviceConfig](#wifideviceconfig) | Yes| New WLAN configuration.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| + | **Type**| **Description**| + | -------- | -------- | + | number | ID of the updated network configuration. The value **-1** indicates that the operation has failed.| ## wifi.disableNetwork7+ @@ -1073,15 +1073,15 @@ Disables network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| netId | number | Yes| ID of the network configuration to disable.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the network configuration to disable.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.removeAllNetwork7+ @@ -1098,9 +1098,9 @@ Removes the configuration of all networks. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.removeDevice7+ @@ -1117,15 +1117,15 @@ Removes the specified network configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | | id | number | Yes| ID of the network configuration to remove.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.enableHotspot7+ @@ -1142,9 +1142,9 @@ Enables this hotspot. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.disableHotspot7+ @@ -1161,9 +1161,9 @@ Disables this hotspot. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.isHotspotDualBandSupported7+ @@ -1180,9 +1180,9 @@ Checks whether the hotspot supports dual band. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the feature is supported; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the feature is supported; returns **false** otherwise.| ## wifi.isHotspotActive7+ @@ -1199,9 +1199,9 @@ Checks whether this hotspot is active. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the hotspot is active; returns **false** otherwise.| ## wifi.setHotspotConfig7+ @@ -1218,15 +1218,15 @@ Sets hotspot configuration. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | config | [HotspotConfig](#hotspotconfig7) | Yes| Hotspot configuration to set.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## HotspotConfig7+ @@ -1260,9 +1260,9 @@ obtains hotspot configuration. **Return value** -| **Type**| **Description**| -| -------- | -------- | -| [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| + | **Type**| **Description**| + | -------- | -------- | + | [HotspotConfig](#hotspotconfig7) | Hotspot configuration obtained.| ## wifi.getStations7+ @@ -1279,9 +1279,9 @@ Obtains information about the connected stations. **Return value** -| **Type**| **Description**| -| -------- | -------- | -|  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| + | **Type**| **Description**| + | -------- | -------- | + |  Array<[StationInfo](#stationinfo7)> | Connected stations obtained.| ## StationInfo7+ @@ -1311,9 +1311,9 @@ Obtains P2P link information. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Promise used to return the P2P link information obtained.| @@ -1354,9 +1354,9 @@ Obtains P2P link information. This API uses an asynchronous callback to return t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the P2P link information. If **err** is not **0**, an error has occurred.| ## wifi.getCurrentGroup8+ @@ -1371,9 +1371,9 @@ Obtains the current P2P group information. This API uses a promise to return the **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Promise used to return the group information obtained.| ## wifi.getCurrentGroup8+ @@ -1388,9 +1388,9 @@ Obtains the current P2P group information. This API uses an asynchronous callbac **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| ## wifi.getP2pPeerDevices8+ @@ -1405,9 +1405,9 @@ Obtains the peer device list in the P2P connection. This API uses a promise to r **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice[]](#wifip2pdevice8)> | Promise used to return the peer device list.| ## wifi.getP2pPeerDevices8+ @@ -1422,9 +1422,9 @@ Obtains the peer device list in the P2P connection. This API uses an asynchronou **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the peer device list obtained. If **err** is not **0**, an error has occurred.| ## WifiP2pDevice8+ @@ -1469,9 +1469,9 @@ Obtains the local device information in the P2P connection. This API uses a prom **Return value** -| Type| Description| -| -------- | -------- | -| Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| + | Type| Description| + | -------- | -------- | + | Promise<[WifiP2pDevice](#wifip2pdevice8)> | Promise used to return the local device information obtained.| ## wifi.getP2pLocalDevice9+ @@ -1486,9 +1486,9 @@ Obtains the local device information in the P2P connection. This API uses an asy **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the local device information obtained. If **err** is not **0**, an error has occurred.| ## wifi.createGroup8+ @@ -1503,15 +1503,15 @@ Creates a P2P group. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| Group configuration.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## WifiP2PConfig8+ @@ -1554,9 +1554,9 @@ Removes this P2P group. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.p2pConnect8+ @@ -1572,15 +1572,15 @@ Sets up a P2P connection. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | config | [WifiP2PConfig](#wifip2pconfig8) | Yes| P2P group configuration.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example** @@ -1662,9 +1662,9 @@ Cancels this P2P connection. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.startDiscoverDevices8+ @@ -1679,9 +1679,9 @@ Starts to discover devices. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.stopDiscoverDevices8+ @@ -1696,9 +1696,9 @@ Stops discovering devices. **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.deletePersistentGroup8+ @@ -1716,15 +1716,15 @@ Deletes a persistent group. **Parameters** -| **Name**| **Type**| Mandatory| **Description**| -| -------- | -------- | -------- | -------- | -| netId | number | Yes| ID of the group to delete.| + | **Name**| **Type**| Mandatory| **Description**| + | -------- | -------- | -------- | -------- | + | netId | number | Yes| ID of the group to delete.| **Return value** -| Type| Description| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | Type| Description| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.getP2pGroups9+ @@ -1741,9 +1741,9 @@ Obtains information about all P2P groups. This API uses a promise to return the **Return value** -| Type| Description| -| -------- | -------- | -| Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| + | Type| Description| + | -------- | -------- | + | Promise< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)> > | Promise used to return the group information obtained.| ## WifiP2pGroupInfo8+ @@ -1779,9 +1779,9 @@ Obtains information about all P2P groups. This API uses an asynchronous callback **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| + | Name| Type| Mandatory| Description| + | -------- | -------- | -------- | -------- | + | callback | AsyncCallback< Array<[WifiP2pGroupInfo](#wifip2pgroupinfo8)>> | Yes| Callback invoked to return the result. If the operation is successful, **err** is **0** and **data** is the group information obtained. If **err** is not **0**, an error has occurred.| ## wifi.setDeviceName8+ @@ -1798,15 +1798,15 @@ Sets the device name. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| devName | string | Yes| Device name to set.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | devName | string | Yes| Device name to set.| **Return value** -| **Type**| **Description**| -| -------- | -------- | -| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| + | **Type**| **Description**| + | -------- | -------- | + | boolean | Returns **true** if the operation is successful; returns **false** otherwise.| ## wifi.on('wifiStateChange')7+ @@ -1821,10 +1821,10 @@ Registers the WLAN state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN state.| **WLAN states** @@ -1848,10 +1848,10 @@ Unregisters the WLAN state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiStateChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiStateChange**.| + | callback | Callback<number> | No| Callback used to return the WLAN state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| **Example** ```js @@ -1881,10 +1881,10 @@ Registers the WLAN connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiConnectionChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN connection state.| **WLAN connection states** @@ -1906,10 +1906,10 @@ Unregisters the WLAN connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiConnectionChange**.| -| callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiConnectionChange**.| + | callback | Callback<number> | No| Callback used to return the WLAN connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| ## wifi.on('wifiScanStateChange')7+ @@ -1924,10 +1924,10 @@ Registers the WLAN scan state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiScanStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiScanStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the WLAN scan state.| **WLAN scan states** @@ -1967,10 +1967,10 @@ Registers the RSSI change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiRssiChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the RSSI, in dBm.| ## wifi.off('wifiRssiChange')7+ @@ -1985,9 +1985,9 @@ Unregisters the RSSI change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **wifiRssiChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **wifiRssiChange**.| | callback | Callback<number> | No| Callback used to return the RSSI. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| @@ -2003,10 +2003,10 @@ Registers the hotspot state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **hotspotStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the hotspot state.| **Hotspot states** @@ -2030,9 +2030,9 @@ Unregisters the hotspot state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **hotspotStateChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **hotspotStateChange**.| | callback | Callback<number> | No| Callback used to return the hotspot state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| @@ -2048,10 +2048,10 @@ Registers the P2P state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pStateChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P state.| **P2P states** @@ -2075,9 +2075,9 @@ Unregisters the P2P state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pStateChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pStateChange**.| | callback | Callback<number> | No| Callback used to return the P2P state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| @@ -2093,10 +2093,10 @@ Registers the P2P connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pConnectionChange**.| -| callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the P2P connection state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | Yes| Callback invoked to return the P2P connection state.| ## wifi.off('p2pConnectionChange')8+ @@ -2111,9 +2111,9 @@ Unregisters the P2P connection state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pConnectionChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pConnectionChange**.| | callback | Callback<[WifiP2pLinkedInfo](#wifip2plinkedinfo8)> | No| Callback used to return the P2P connection state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| @@ -2129,10 +2129,10 @@ Registers the P2P device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDeviceChange**.| -| callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P device state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P device state.| ## wifi.off('p2pDeviceChange')8+ @@ -2147,9 +2147,9 @@ Unregisters the P2P device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDeviceChange**.| | callback | Callback<[WifiP2pDevice](#wifip2pdevice8)> | No| Callback used to return the P2P device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| @@ -2165,9 +2165,9 @@ Registers the P2P peer device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | Yes| Callback invoked to return the P2P peer device state.| @@ -2183,9 +2183,9 @@ Unregisters the P2P peer device state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPeerDeviceChange**.| | callback | Callback<[WifiP2pDevice[]](#wifip2pdevice8)> | No| Callback used to return the peer device state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| @@ -2201,10 +2201,10 @@ Registers the P2P persistent group state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| -| callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | callback | Callback<void> | Yes| Callback invoked to return the P2P persistent group state.| ## wifi.off('p2pPersistentGroupChange')8+ @@ -2219,9 +2219,9 @@ Unregisters the P2P persistent group state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pPersistentGroupChange**.| | callback | Callback<void> | No| Callback used to return the P2P persistent group state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| @@ -2237,10 +2237,10 @@ Registers the P2P device discovery state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| -| callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | callback | Callback<number> | Yes| Callback invoked to return the P2P device discovery state.| **P2P discovered device states** @@ -2262,7 +2262,7 @@ Unregisters the P2P device discovery state change events. **Parameters** -| **Name**| **Type**| **Mandatory**| **Description**| -| -------- | -------- | -------- | -------- | -| type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| + | **Name**| **Type**| **Mandatory**| **Description**| + | -------- | -------- | -------- | -------- | + | type | string | Yes| Event type. The value is **p2pDiscoveryChange**.| | callback | Callback<number> | No| Callback used to return the P2P device discovery state. If this parameter is not specified, all callbacks associated with the specified event will be unregistered.| diff --git a/en/application-dev/reference/arkui-js/figures/EventParameters.gif b/en/application-dev/reference/arkui-js/figures/EventParameters.gif new file mode 100644 index 0000000000000000000000000000000000000000..3012b0fe3edabe15d0b48373fb738b5c4879842d Binary files /dev/null and b/en/application-dev/reference/arkui-js/figures/EventParameters.gif differ diff --git a/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md b/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md index b1b63b3e16d1e973c7a0854c29d84853f20806ea..55131eddc7e7613ae7fa58086ca5c59cc9ee35c9 100644 --- a/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md +++ b/en/application-dev/reference/arkui-js/js-components-custom-event-parameter.md @@ -1,40 +1,46 @@ -# Event Parameter +# Event Parameter A child component can also pass parameters to an upper-layer component through the bound event. The following example describes how to pass parameters through the custom event: -``` + +```html
- Click here to view the hidden text. - hello world + Click to View Hidden Text + hello world
``` -``` + +```js // comp.js export default { childClicked () { - this.$emit('eventType1', {text: 'Receive the parameters from the child component.'}); + this.$emit('eventType1', {text: 'Received parameters from the child component.'}); this.showObj = !this.showObj; }, } ``` -In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**: -``` +In the following example, the child component passes the **text** parameter to the parent component, and the parent component obtains the parameter through **e.detail**: + + +```html +
Parent component: {{text}}
``` -``` + +```js // xxx.js export default { data: { - text: 'Start', + text: 'Start' }, textClicked (e) { this.text = e.detail.text; @@ -42,3 +48,4 @@ export default { } ``` +![EventParameters](figures/EventParameters.gif) diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md index 925e02a88bce8e5a9fb13a752e178e422afad645..deb88ab76fc047354169bbaadf95b225775335f0 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-checkboxgroup.md @@ -8,7 +8,7 @@ The **\** component is used to select or deselect all check boxes ## Child Components -None +Not supported ## APIs @@ -18,8 +18,6 @@ Creates a check box group so that you can select or deselect all check boxes in **Parameters** - - | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | | group | string | No| Group name.| diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md index fe13a114dcd9c8407c74c6d6193d232998af4034..8a755a02ff75cf3bcbf44a68cfa64e4898b99c33 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-image.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-image.md @@ -27,7 +27,7 @@ Obtains an image from the specified source for subsequent rendering and display. | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. \ The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.
\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability.| +| src | string\| [PixelMap](../apis/js-apis-image.md#pixelmap7) \| [Resource](ts-types.md#resource) | Yes | Image source. Both local and online images are supported.
When using an image referenced using a relative path, for example, `Image("common/test.jpg")`, the **\** component cannot be called across bundles or modules. Therefore, you are advised to use `$r` to reference image resources that need to be used globally.
- The following image formats are supported: PNG, JPG, BMP, SVG, GIF.
\- Base64 strings are supported. The value format is `data:image/[png\|jpeg\|bmp\|webp];base64,[base64 data]`, where `[base64 data]` is a Base64 string.
\- The value can also be a path starting with `dataability://`, which is used to access the image path provided by a Data ability. | ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md index a9e80d2923b42027be871830988f5d380f77808f..f000af680f63404ce37e365b777fbe9e03b96b5d 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-radio.md @@ -9,7 +9,7 @@ The **\** component allows users to select from a set of mutually exclusi ## Child Components -None +Not supported ## APIs diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md b/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md index eee8ee70f12c7bf07bb30b5741e659d827b0eb0e..ffb479fd90217da2d88543706e2913f5cf04850f 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-textclock.md @@ -19,7 +19,7 @@ TextClock(options?: { timeZoneOffset?: number, controller?: TextClockController | Name | Type | Mandatory | Description | | -------------- | -------- | ------ | --------------------------------------------------------------------------- | | timeZoneOffset | number | No | Time zone offset.
The value range is [-14, 12], indicating UTC+12 to UTC-12. A negative value indicates Eastern Standard Time, and a positive value indicates Western Standard Time. For example, **-8** indicates UTC+8.
For countries or regions crossing the International Date Line, use -13 (UTC+13) and -14 (UTC+14) to ensure consistent time within the entire country or region. If the set value is not within the valid range, the time zone offset of the current system will be used.
Default value: time zone offset of the current system| -| controller | [TextClockController](#textclockcontroller) | No | Binds a controller to control the status of the **** component.| +| controller | [TextClockController](#textclockcontroller) | No | Controller to control the status of the **** component. | ## Attributes @@ -31,7 +31,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## Events -In addition to the universal events (ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. | Name | Description | | -------------------------------------------- | ------------------------------------------------------------ | diff --git a/en/application-dev/reference/arkui-ts/ts-container-list.md b/en/application-dev/reference/arkui-ts/ts-container-list.md index beed8908018fafdcdbc03ec99e8ec54fedad00dc..6a7cb32d7647f0293a0530829cfe071bd089b474 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-list.md +++ b/en/application-dev/reference/arkui-ts/ts-container-list.md @@ -10,7 +10,7 @@ The **\** component provides a list container that presents a series of li ## Child Components -This component supports the [\(ts-container-listitem.md) and [\](ts-container-listitemgroup.md) child components. +This component supports the [\](ts-container-listitem.md) and [\](ts-container-listitemgroup.md) child components. ## APIs diff --git a/en/application-dev/reference/arkui-ts/ts-container-row.md b/en/application-dev/reference/arkui-ts/ts-container-row.md index cdd62b8b32f2928375743c23c930e7fe2abcfbc8..d8b0cf68c9a9914d44f121f6d9ac0bb3ffe947c9 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-row.md +++ b/en/application-dev/reference/arkui-ts/ts-container-row.md @@ -20,7 +20,7 @@ Row(value?:{space?: number | string }) | Name| Type| Mandatory| Description| | -------- | -------- | -------- | -------- | -| space | string \| number | No| Space between two adjacent child components in the horizontal layout.
Default value: **0**| +| space | string \| number | No| Space between two adjacent child components in the horizontal layout.
Default value: **0**, in vp | ## Attributes @@ -28,7 +28,7 @@ Row(value?:{space?: number | string }) | Name| Type| Description| | -------- | -------- | -------- | | alignItems | [VerticalAlign](ts-appendix-enums.md#verticalalign) | Alignment mode of child components in the vertical direction.
Default value: **VerticalAlign.Center**| -| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the horizontal direction.
FlexAlign.Start | +| justifyContent8+ | [FlexAlign](ts-appendix-enums.md#flexalign) | Alignment mode of the child components in the horizontal direction.
Default value: **FlexAlign.Start** | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md index a9d5a32e480f4d0ad3f4536dc806edd593bda36a..4858f2c37345ea8d074fdd68dae68860a57e20ee 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md +++ b/en/application-dev/reference/arkui-ts/ts-container-rowsplit.md @@ -1,15 +1,10 @@ # RowSplit -> **NOTE** -> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. - - The **\** lays out child components horizontally and inserts a vertical divider between every two child components. - -## Required Permissions - -None +> **NOTE** +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Child Components @@ -24,12 +19,13 @@ RowSplit() ## Attributes -| Name| Type| Description| +| Name| Type| Description| | -------- | -------- | -------- | -| resizeable | boolean | Whether the divider can be dragged. The default value is **false**.| +| resizeable | boolean | Whether the divider can be dragged. The default value is **false**.| > **NOTE** -> Similar to **\**, the divider of **\** can be dragged to a position that just fully holds a component. +> +> Similar to **\**, the divider of **\** can be dragged to a position that just fully holds a component. ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md index 4119473322b8ea13d46ff31a7d8fe7eb4c95ed14..3eaa86b6d332b7ee7699efc3243da173a01b260e 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabcontent.md @@ -7,7 +7,7 @@ The **\** component is used only in the **\** component. It co > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. -## Child Component +## Child Components This component supports only one child component. @@ -23,7 +23,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the | Name| Type| Description| | -------- | -------- | -------- | -| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
> **NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image.| +| tabBar | string \| Resource \| {
icon?: string \| Resource,
text?: string \| Resource
}
\| [CustomBuilder](ts-types.md)8+ | Content displayed on the tab bar.
**CustomBuilder**: builder, to which components can be passed (applicable to API version 8 and later versions).
**NOTE**
If an icon uses an SVG image, the width and height attributes of the SVG image must be deleted. Otherwise, the icon size will be determined by the width and height attributes of the SVG image. | > **NOTE** > - The **\** component does not support setting of the common width attribute. By default, its width is the same as that of the parent **\** component. diff --git a/en/application-dev/reference/arkui-ts/ts-container-tabs.md b/en/application-dev/reference/arkui-ts/ts-container-tabs.md index cf2877be17fa2cf33cb609c061d598a20ac12738..82503cc45bae76b09dd443e1c935ebd877528303 100644 --- a/en/application-dev/reference/arkui-ts/ts-container-tabs.md +++ b/en/application-dev/reference/arkui-ts/ts-container-tabs.md @@ -2,7 +2,7 @@ The **\** component is a container component that allows users to switch between content views through tabs. Each tab page corresponds to a content view. -> **NOTE**
+> **NOTE** > > This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. @@ -54,7 +54,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## Events -In addition to the universal events (ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. | Name| Description| | -------- | -------- | diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md index 9963f4e41348f73d784b2d67aae0f7d2ed375252..a4dad2bb721a0e4db791ae84bed8a660d717b04b 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-line.md @@ -4,7 +4,8 @@ The **\** component is used to draw a straight line. > **NOTE** -> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> +> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Required Permissions diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md index df8578babc490378d574449deccb716d05ec0e45..15b4da37a04970d3cbfcdce429ede77ec46291b8 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-polygon.md @@ -16,18 +16,18 @@ Not supported Polygon(value?: {width?: string | number, height?: string | number}) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | width | string \| number | No| 0 | Width.| - | height | string \| number | No| 0 | Height.| +**Parameters** +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| width | string \| number | No| 0 | Width.| +| height | string \| number | No| 0 | Height.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Default Value| Mandatory| Description| +| Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | | points | Array<Point> | [] | No| Vertex coordinates of the polygon.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md index 90b1d2a7aa350976b8ce1a6b9bce84ea079fe07f..8475647b5707a180dba18377ee45ae41796b9a69 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-polyline.md @@ -16,20 +16,20 @@ Not supported Polyline(value?: {width?: string | number, height?: string | number}) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | width | string \| number | No| 0 | Width.| - | height | string \| number | No| 0 | Height.| +**Parameters** +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| width | string \| number | No| 0 | Width.| +| height | string \| number | No| 0 | Height.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Default Value| Mandatory| Description| +| Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| points | Array<Point> | [] | No| List of coordinates that the polyline passes through.| +| points | Array<Point> | [] | No| List of coordinates that the polyline passes through.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.| | stroke | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Stroke color.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md index 9d0dd2d44a9563306e11895e31e7a295093eb407..bb9a06be8dfc2d71663807a7fc9f9cb2cf3529bf 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-rect.md @@ -17,24 +17,25 @@ Not supported Rect(value?: {width?: string | number,height?: string | number,radius?: string | number | Array<string | number>} | {width?: string | number,height?: string | number,radiusWidth?: string | number,radiusHeight?: string | number}) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | width | string \| number | No| 0 | Width.| - | height | string \| number | No| 0 | Height.| - | radius | string \| number \| Array<string \| number> | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.| - | radiusWidth | string \| number | No| 0 | Width of the rounded corner.| - | radiusHeight | string \| number | No| 0 | Height of the rounded corner.| +**Parameters** + +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| width | string \| number | No| 0 | Width.| +| height | string \| number | No| 0 | Height.| +| radius | string \| number \| Array<string \| number> | No| 0 | Radius of the rounded corner. You can set separate radiuses for four rounded corners.| +| radiusWidth | string \| number | No| 0 | Width of the rounded corner.| +| radiusHeight | string \| number | No| 0 | Height of the rounded corner.| ## Attributes In addition to the [universal attributes](ts-universal-attributes-size.md), the following attributes are supported. -| Name| Type| Default Value| Mandatory| Description| +| Name| Type| Default Value| Mandatory| Description| | -------- | -------- | -------- | -------- | -------- | -| radiusWidth | string \| number | 0 | No| Width of the rounded corner. The width and height are the same when only the width is set.| -| radiusHeight | string \| number | 0 | No| Height of the rounded corner. The width and height are the same only when the height is set.| +| radiusWidth | string \| number | 0 | No| Width of the rounded corner. The width and height are the same when only the width is set.| +| radiusHeight | string \| number | 0 | No| Height of the rounded corner. The width and height are the same only when the height is set.| | radius | string \| number \| Array<string \| number> | 0 | No| Radius of the rounded corner. You can set separate radiuses for four rounded corners.| | fill | [ResourceColor](ts-types.md#resourcecolor) | Color.Black | No| Color of the fill area.| | fillOpacity | number \| string \| [Resource](ts-types.md#resource)| 1 | No| Opacity of the fill area.| diff --git a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index ce61ce33769363c5b331ea3f476a1bd7fa4c9d68..1341cc20d871001547be2084eb35a3feb4d026a9 100644 --- a/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/en/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -21,10 +21,10 @@ This component can contain child components. Shape(value?: PixelMap) -- Parameters - | Name| Type| Mandatory| Default Value| Description| - | -------- | -------- | -------- | -------- | -------- | - | value | PixelMap | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.| +**Parameters** +| Name| Type| Mandatory| Default Value| Description| +| -------- | -------- | -------- | -------- | -------- | +| value | PixelMap | No| - | Shape to draw. You can draw a shape in the specified **PixelMap** object. If no object is specified, the shape is drawn in the current drawing target.| ## Attributes diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index 2fe2e87870ad855044790259a8709986120d3244..158a8f0395f635c7417de49579d1f9bdfa61ab8e 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -53,7 +53,7 @@ In addition to the [universal attributes](ts-universal-attributes-size.md), the ## Events -In addition to the universal events (ts-universal-events-click.md), the following events are supported. +In addition to the [universal events](ts-universal-events-click.md), the following events are supported. | Name | Description | | ------------------------------------------------------------ | ------------------------------------------------------------ | @@ -70,7 +70,7 @@ In addition to the universal events (ts-universal-events-click.md), the followin ## VideoController -A **VideoController** object can control one or more videos. +Defines a **VideoController** object to control one or more videos. ### Objects to Import diff --git a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md index e6e19c44e7387dfb6682a9a296a461df72566b21..63f0e8300b8530cc0e7404cfb881ba3eff5d5d03 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-action-sheet.md @@ -28,10 +28,10 @@ Defines and shows the action sheet. | confirm | {
value: string \| [Resource](ts-types.md#resource),
action: () => void
} | No | Text content of the confirm button and callback upon button clicking.
Default value:
**value**: button text.
**action**: callback upon button clicking.| | cancel | () => void | No | Callback invoked when the dialog box is closed after the overlay is clicked. | | alignment | [DialogAlignment](ts-methods-custom-dialog-box.md#dialogalignment) | No | Alignment mode of the dialog box in the vertical direction.
Default value: **DialogAlignment.Default**| -| offset | {
dx: Length,
dy: Length
} | No | Offset of the dialog box relative to the alignment position.{
dx: 0,
dy: 0
} | +| offset | {
dx: Length,
dy: Length
} | No | Offset of the dialog box relative to the alignment position.
Default value: **{
dx: 0,
dy: 0
}** | | sheets | Array<SheetInfo> | Yes | Options in the dialog box. Each option supports the image, text, and callback.| -## SheetInfo parameters +## SheetInfo | Name| Type | Mandatory| Description | | ------ | ------------------------------------------------------------ | ---- | ----------------- | diff --git a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md index 5754a1b194653e4df5afde37bf50b815e14ce2e2..e8488281d24a6b93a24e2fbfceafccba5a657e4e 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-datepicker-dialog.md @@ -6,11 +6,6 @@ A date picker dialog box is a dialog box that allows users to select a date from > > The APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. - -## Required Permissions - -None - ## DatePickerDialog.show show(options?: DatePickerDialogOptions) diff --git a/en/application-dev/reference/arkui-ts/ts-methods-menu.md b/en/application-dev/reference/arkui-ts/ts-methods-menu.md index b019c06841a6e94017a9b167b438d5ff90411354..4400e9cbf87afc5854228a1b25a6d74fcf44fd8f 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-menu.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-menu.md @@ -1,21 +1,16 @@ # Menu -The menu bound to a component through [bindContextMenu](./ts-universal-attributes-menu.md#atrributes) on a page can be closed as needed. +The menu bound to a component through [bindContextMenu](./ts-universal-attributes-menu.md#attributes) on a page can be closed as needed. > **NOTE** > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. -## Required Permissions - -None - - ## ContextMenu.close |Name|Description| |----|---| -| close(): void | Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#atrributes) on a page.| +| close(): void | Closes the menu bound to this component through [bindContextMenu](./ts-universal-attributes-menu.md#attributes) on a page. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md index f575385cdac4842a96f03b6516ec40f6bb4c8699..87d6cdb9909b8fb118cebcdfe923bfaffc4544c4 100644 --- a/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md +++ b/en/application-dev/reference/arkui-ts/ts-methods-textpicker-dialog.md @@ -6,11 +6,6 @@ A text picker dialog box is a dialog box that allows users to select text from t > > The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. - -## Required Permissions - -None - ## TextPickerDialog.show show(options?: TextPickerDialogOptions) diff --git a/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md b/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md index c35cfd163fc86189bfb52182513ce2202d17e398..c393bf5812f9508448891111012d6c839cf6fb5c 100644 --- a/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md +++ b/en/application-dev/reference/arkui-ts/ts-transition-animation-shared-elements.md @@ -17,7 +17,7 @@ Shared element transition can be used for transition between pages, for example, ## Example - The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image. +The example implements the custom transition of a shared image during redirection from one page to another, which is triggered by a click on the image. ```ts // xxx.ets diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md index f6a533065bdf4cb67d2dd683989b87c78af56eda..25737f363751988499f8bc93232b6d4733470b54 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-background.md @@ -10,10 +10,10 @@ You can set the background of a component. | Name| Type| Description| | -------- | -------- | -------- | -| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | The table below describes the attributes used to set the background color of a component.| -| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | **src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used.| +| backgroundColor | [ResourceColor](ts-types.md#resourcecolor) | Background color of the component. | +| backgroundImage | src: [ResourceStr](ts-types.md#resourcestr),
repeat?: [ImageRepeat](ts-appendix-enums.md#imagerepeat) | Background image of the component.
**src**: image address, which can be the address of an Internet or a local image. (SVG images are not supported.)
**repeat**: whether the background image is repeatedly used. By default, the background image is not repeatedly used. | | backgroundImageSize | {
width?: [Length](ts-types.md#length),
height?: [Length](ts-types.md#length)
} \| [ImageSize](ts-appendix-enums.md#imagesize) | Width and height of the background image. If the input is a **{width: Length, height: Length}** object and only one attribute is set, the other attribute is the set value multiplied by the original aspect ratio of the image. By default, the original image aspect ratio remains unchanged.
Default value: **ImageSize.Auto**| -| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.
Default value:
{
x: 0,
y: 0
} | +| backgroundImagePosition | [Position](ts-types.md#position8) \| [Alignment](ts-appendix-enums.md#alignment) | Position of the background image in the component.
Default value:
**{
x: 0,
y: 0
}** | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md index 7f9b88479d562dad8a2644f1bd4c1be9176e02b7..0b055bbfa0c84cf592d13c4fe26a04ab400b3a5a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md @@ -14,11 +14,11 @@ You can apply background blur effects to a component. ## BlurStyle - | Name | Description | - | ------- | ---------- | - | Thin | Thin material. | - | Regular | Regular material. | - | Thick | Thick material. | +| Name | Description | +| ------- | ---------- | +| Thin | Thin material. | +| Regular | Regular material. | +| Thick | Thick material. | ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md index 9396d3f0fc3cf34b1eff351edbd3f1af19cf26da..c02876ce0f77ca67db58378aa68dc044846dbc75 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-image-effect.md @@ -17,8 +17,8 @@ None | Name | Type | Default Value| Description | | ----------------------------- | ------------------------------------------------------------ | ------ | ------------------------------------------------------------ | -| blur | number | - | Blur effect of the current component' content. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred.| -| backdropBlur | number | - | Blur effect of the current component' background. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred.| +| blur | number | - | Adds the content blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the content is. If the value is **0**, the content is not blurred. | +| backdropBlur | number | - | Adds the background blur effect to the current component. The input parameter is the blur radius. The larger the radius is, the more blurred the background is. If the value is **0**, the background is not blurred. | | shadow | {
radius: number \| [Resource](ts-types.md#resource),
color?: Color \| string \| Resource,
offsetX?: number \| Resource,
offsetY?: number \| Resource
} | - | Adds the shadow effect to the current component. The input parameters are the fuzzy radius (mandatory), shadow color (optional; gray by default), x-axis offset (optional; 0 by default), and y-axis offset (optional; 0 by default). The offset unit is px.| | grayscale | number | 0.0 | Converts the input image to grayscale. The value indicates the grayscale conversion ratio. If the input value is **1.0**, the image is converted into a grayscale image. If the input value is **0.0**, the image does not change. If the input value is between **0.0** and **1.0**, the effect changes in linear mode. The unit is percentage.| | brightness | number | 1.0 | Adds a brightness to the current component. The input parameter is a brightness ratio. The value **1** indicates no effects. The value **0** indicates the complete darkness. If the value is less than **1**, the brightness decreases. If the value is greater than **1**, the brightness increases. A larger value indicates a higher brightness.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md index 69037d82bd8efc5e3028823381c6a8d9406fe329..3cab264048f797063baf0d40f5b489807033967a 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md @@ -4,7 +4,7 @@ The location attribute sets the alignment mode, layout direction, and position o > **NOTE** > -> This event is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +> The APIs of this module are supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. ## Attributes @@ -15,8 +15,8 @@ The location attribute sets the alignment mode, layout direction, and position o | align | [Alignment](ts-appendix-enums.md#alignment) | Alignment of the component content. This attribute is valid only when the values of **width** and **height** are greater than the size of the component content.
Default value: **Alignment.Center**| | direction | [Direction](ts-appendix-enums.md#direction) | Horizontal layout of the component.
Default value: **Direction.Auto**| | position | [Position](ts-types.md#position8) | Offset of the component anchor point relative to the top start edge of the parent component. The offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.| -| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.
Default value:
{
x: 0,
y: 1
} | -| offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 1
} | +| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The top start edge of the component is used as the reference point for offset.
Default value:
**{
x: 0,
y: 1**
} | +| offset | [Position](ts-types.md#position8) | Coordinate offset of the relative layout. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
**{
x: 0,
y: 1
}** | | alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md index 446cc542dcd6d1e9110c3975e8b1d16fe5ceeb02..f7937b97bffbb5ab4f596940910a22e9922b4040 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-text-style.md @@ -16,7 +16,7 @@ The text style attributes are used to set the style for text in a component. | fontColor | [ResourceColor](ts-types.md#resourcecolor) | Font color. | | fontSize | Length \| [Resource](ts-types.md#resource) | Font size. If the value is of the number type, the unit fp is used. | | fontStyle | [FontStyle](ts-appendix-enums.md#fontstyle) | Font style.
Default value: **FontStyle.Normal** | -| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, 400, "bold", "bolder", "lighter", "regular", and "medium", which correspond to the enumerated values in FontWeight.
Default value: **FontWeight.Normal** | +| fontWeight | number \| [FontWeight](ts-appendix-enums.md#fontweight) \| string | Font weight. For the number type, the value ranges from 100 to 900, at an interval of 100. The default value is **400**. A larger value indicates a larger font weight. The string type supports only the string of the number type, for example, **400**, **"bold"**, **"bolder"**, **"lighter"**, **"regular"**, and **"medium"**, which correspond to the enumerated values in **FontWeight**.
Default value: **FontWeight.Normal** | | fontFamily | string \| [Resource](ts-types.md#resource) | Font family. Use commas (,) to separate multiple fonts, for example, **'Arial, sans-serif'**. The priority of the fonts is the sequence in which they are placed.| diff --git a/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md b/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md index c777a2a3dbf580505a97ff0fabd3908423d8e004..02d3179909afd790d353e4f02eefba814bff35c4 100644 --- a/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md +++ b/en/application-dev/reference/arkui-ts/ts-universal-events-drag-drop.md @@ -27,9 +27,9 @@ A drag event is triggered when a component is dragged. ## extraParam - Provides additional information required for dragging an item. +Provides additional information required for dragging an item. - **extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**. +**extraParam** is a string converted from a JSON object. You can obtain the following attributes using the JSON object converted from **Json.parse**. | Name | Type | Description | | ------------- | ------ | ---------------------------------------- | @@ -38,7 +38,7 @@ A drag event is triggered when a component is dragged. ## DragEvent -| Sample Code | Return Value Type | Description | +| Name | Return Value Type | Description | | ------ | ------ | ---------------- | | getX() | number | X-coordinate of the item that is being dragged, in vp.| | getY() | number | Y-coordinate of the item that is being dragged, in vp.| diff --git a/en/application-dev/reference/syscap-list.md b/en/application-dev/reference/syscap-list.md new file mode 100644 index 0000000000000000000000000000000000000000..c3d849539af2d3bed9fa49cc27cc4c8162527226 --- /dev/null +++ b/en/application-dev/reference/syscap-list.md @@ -0,0 +1,1396 @@ +# SysCap List + +SysCap, short for System Capability, refers to a standalone feature in the operating system. + +Before using an API for development, you are advised to read [SysCap](../quick-start/syscap.md) to familiarize yourself with Syscap, and then consult the following tables to see whether the SysCap set required for the API is supported by the target device type. + +## SystemCapability.ArkUI.ArkUI.Full + +ArKUI standard system + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ArkUI.ArkUI.Lite + +ArkUI small system + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.ArkUI.ArkUI.Napi + +NAPI functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ArkUI.ArkUI.Libuv + +libuv functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ArkUI.UiAppearance + +Appearance configuration + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleFramework + +Bundle manager service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.DistributedBundleFramework + +Distributed scheduler + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.BundleTool + +Bundle manager CLI tool + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.Zlib + +zlib compression and decompression tool + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BundleManager.PackingTool + +Packing and unpacking tools for bundle management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.Graphic.Graphic2D.WebGL + +WebGL 1.0 API + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Graphic.Graphic2D.WebGL2 + +WebGL 2.0 API + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | No | No | No | No | No | + +## SystemCapability.WindowManager.WindowManager.Core + +Window manager + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.WindowManager.WindowManager.MutiScreen + +Multi-screen capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.CommonEvent + +Common event + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.Notification + +Notification + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.ReminderAgent + +reminderAgent + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Notification.Emitter + +Event emitter service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.IPC.Core + +Inter-process communication (IPC) + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | Yes | No | + +## SystemCapability.Communication.SoftBus.Core + +DSoftBus + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Communication.NetManager.Core + +Basic network management services + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NetManager.Extension + +Extended network management services + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NetStack + +Basic network stack capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.Core + +Basic Wi-Fi capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.STA + +Wi-Fi STA capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.AP.Core + +Wi-Fi AP capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.WiFi.AP.Extension + +Wi-Fi AP extension capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | Yes | + +## SystemCapability.Communication.WiFi.P2P + +Wi-Fi P2P capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.Bluetooth.Core + +Bluetooth service and protocol stack + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.Bluetooth.Lite + +Bluetooth lightweight service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Communication.NFC.Core + +NFC + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.Communication.ConnectedTag + +Active NFC tag service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.Location.Location.Core + +Basic capabilities of the location service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Geocoder + +Geocoding capability +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Geofence + +Geofencing capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Gnss + +GNSS hardware capabilities + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Location.Location.Lite + +Lite device capabilities of the location service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | No | No | No | + +## SystemCapability.MultimodalInput.Input.Core + +Basic input capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputDevice + +Input device management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.RemoteInputDevice + +Distributed input device management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputMonitor + +Input event listener + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputConsumer + +Input event consumer + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputSimulator + +Input event simulator + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.MultimodalInput.Input.InputFilter + +Input event filter + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.PowerManager.BatteryManager.Extension + +Battery manager extension capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.PowerManager.BatteryStatistics + +Power consumption statistics + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.PowerManager.DisplayPowerManager + +Power management display + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.PowerManager.ThermalManager + +Temperature control + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.PowerManager.PowerManager.Core + +Core capabilities of the system power management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.PowerManager.PowerManager.Lite + +Lite device capabilities of the system power management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.PowerManager.BatteryManager.Core + +Core capabilities of the battery service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.PowerManager.BatteryManager.Lite + +Lite device capabilities of the battery service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.PowerManager.PowerManager.Extension + +Extension capabilities of the system power management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Multimedia.Media.Core + +Basic media capabilities + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioPlayer + +Media audio player capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioRecorder + +Media audio recorder capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoPlayer + +Media video player capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoRecorder + +Media video recorder capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.CodecBase + +Basic media codec capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioDecoder + +Media audio decoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.AudioEncoder + +Media audio encoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoDecoder + +Media video decoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.VideoEncoder + +Media video encoding capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.Spliter + +Media splitter capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Media.Muxer + +Media muxer capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.AVSession.Core + +Basic media session capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.AVSession.Manager + +Media session management capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Core + +Basic audio capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Renderer + +Audio output capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Capturer + +Audio input capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Device + +Audio device management capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Volume + +Audio volume management capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Audio.Communication + +Audio communication capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Camera.Core + +Basic camera capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Camera.DistributedCore + +Distributed camera capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.Core + +Basic image capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.ImageSource + +Image source decoding and parsing capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.ImagePacker + +Image packaging capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.Image.ImageReceiver + +Image receiving capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.MediaLibrary.Core + +Basic capabilities of the media library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.MediaLibrary.SmartAlbum + +Smart album capability of the media library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Multimedia.MediaLibrary.DistributedCore + +Distributed capability of the media library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Telephony.CoreService + +Basic cellular service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.CallManager + +Call management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Telephony.CellularCall + +Cellular call service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.CellularData + +Cellular data service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.SmsMms + +SMS and MMS services + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Telephony.StateRegistry + +Cellular network status registration service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Global.I18n + +Internationalization + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Global.ResourceManager + +Resource management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Customization.ConfigPolicy + +Customization framework + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Customization.EnterpriseDeviceManager + +Enterprise device management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Core + +Accessibility capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Vision + +Visual accessibility capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Hearing + +Audio accessibility capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.BarrierFree.Accessibility.Interaction + +Interaction assistance capability in accessibility + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | Yes | No | No | + +## SystemCapability.ResourceSchedule.WorkScheduler + +Work Scheduler + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.BackgroundTaskManager.ContinuousTask + +Continuous task management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask + +Transient task management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.UsageStatistics.App + +Application usage statistics + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.ResourceSchedule.UsageStatistics.AppGroup + +Application activity group + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Utils.Lang + +TS/JS language base library + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiLog + +HiLog functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiLogLite + +Lite HiLog functionality + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.HiviewDFX.HiTrace + +HiTrace for distributed tracing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.Hiview.FaultLogger + +FaultLogger for event recording + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiviewLite + +Lightweight Hiview service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | Yes | Yes | + +## SystemCapability.HiviewDFX.HiChecker + +HiChecker mode + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiCollie + +HiCollie for suspension fault detection + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiDumper + +HiDumper for system information exporting + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiAppEvent + +HiAppEvent for application event logging + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiSysEvent + +HiAppEvent for system event logging + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.HiviewDFX.HiEventLite + +HiEventLite for lightweight event logging + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | Yes | No | No | No | No | No | Yes | + +## SystemCapability.HiviewDFX.HiProfiler.HiDebug + +Debugging and tuning + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Update.UpdateService + +Update + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.DistributedHardware.DeviceManager + +Distributed Device Management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.DeviceAuth + +Mutual authentication between devices + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.DataTransitManager + +Library of data transmission management and control policies + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.DeviceSecurityLevel + +Device security level management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.Huks + +Hardware Unique Key (HUK) management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.Security.AccessToken + +Access control + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Security.Cipher + +Encryption and decryption + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | Yes | No | + +## SystemCapability.Account.OsAccount + +Account + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Account.AppAccount + +Application account + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.UserIAM.UserAuth.Core + +Unified user authentication + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.UserIAM.UserAuth.PinAuth + +PIN authentication + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.UserIAM.UserAuth.FaceAuth + +Facial authentication + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.MiscServices.InputMethodFramework + +Input method framework + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Pasteboard + +Pasteboard service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Time + +Time, time zone, and timing service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | Yes | No | No | + +## SystemCapability.MiscServices.Wallpaper + +Wallpaper framework + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.ScreenLock + +Screen lock service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Upload + +Upload service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.MiscServices.Download + +Download service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | No | No | No | No | + +## SystemCapability.FileManagement.StorageService.Backup + +Backup and restoration + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.StorageService.SpatialStatistics + +Spatial statistics + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.StorageService.Volume + +Volume management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.StorageService.Encryption + +File encryption capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.File.FileIO + +Basic file I/O interfaces + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.FileManagement.File.Environment + +Environment-related interfaces + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.FileManagement.File.DistributedFile + +Distributed file extension interfaces + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.AppFileService + +Application file sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.FileManagement.UserFileService + +User file access service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.USB.USBManager + +USB service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.Sensors.Sensor + +Sensor service subscription + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Sensors.MiscDevice + +Miscellaneous devices- sensors + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | No | No | No | No | + +## SystemCapability.Startup.SystemInfo + +Basic system information + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.DistributedDataManager.RelationalStore.Core + +Basic relational database capabilities + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.RelationalStore.Synchronize + +Distributed capability of relational databases + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.RelationalStore.Lite + +Lightweight relational database + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.DistributedDataManager.KVStore.Core + +Core capabilities of key-value databases + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.KVStore.Lite + +Core capabilities of lightweight key-value databases + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| No | No | No | No | No | No | No | No | + +## SystemCapability.DistributedDataManager.KVStore.DistributedKVStore + +Distributed key-value database + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataObject.DistributedObject + +Distributed data object + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.Preferences.Core + +Core capabilities of preferences data storage + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataShare.Core + +Basic capabilities of cross-process data sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataShare.Consumer + +Data conumser of cross-process data sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.DistributedDataManager.DataShare.Provider + +Data provider of cross-process data sharing + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityBase + +Definition of basic component running data, including wants and system configuration + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.Core + +Core basic functional modules for component runtime, including application initialization and GUI-less component running + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.FAModel + +Feature ability (FA) model + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.AbilityCore + +Universal components (with GUIs) + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityRuntime.Mission + +Task management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.AbilityTools.AbilityAssistant + +CLI tool + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.Form + +Widget management + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Ability.DistributedAbilityManager + +continuationManager for starting the device selection module and updating the continuation status. + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Applications.ContactsData + +Contacts database + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Applications.Contacts + +Contacts + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | No | No | No | + +## SystemCapability.Applictaions.settings.Core + +API setting + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Test.UiTest + +UiTest capability + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | No | Yes | Yes | No | No | No | + +## SystemCapability.Web.Webview.Core + +Webview component + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | No | Yes | Yes | Yes | Yes | No | No | + +## SystemCapability.Cloud.AAID + +AAID management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Cloud.OAID + +OAID management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | + +## SystemCapability.Cloud.VAID + +VAID management service + +| Default | Sports Watch| Smart Watch| Tablet| Head Unit| Smart TV| Smart Vision | Router | +| ------- | ------ | ------ | ---- | ---- | ------ | ------------ | ------ | +| Yes | Yes | Yes | Yes | Yes | Yes | Yes | Yes | diff --git a/en/application-dev/ui/Readme-EN.md b/en/application-dev/ui/Readme-EN.md index 20d4a865e9ed33c9b7413adb2498d4826518ccb0..2b4efca72f4786729d4f11234febd406778bc266 100644 --- a/en/application-dev/ui/Readme-EN.md +++ b/en/application-dev/ui/Readme-EN.md @@ -1,26 +1,24 @@ # UI Development - [ArkUI Overview](arkui-overview.md) -- TypeScript-based Declarative Development Paradigm +- UI Development with eTS-based Declarative Development Paradigm - [Overview](ui-ts-overview.md) - Framework Overview - File Organization - [Directory Structure](ts-framework-directory.md) - [Rules for Accessing Application Code Files](ts-framework-file-access-rules.md) - - ["js" Tag](ts-framework-js-tag.md) - Resource Management - [Resource File Categories](ui-ts-basic-resource-file-categories.md) - - [Accessing Resources](ts-resource-access.md) + - [Resource Access](ts-resource-access.md) - [Pixel Units](ts-pixel-units.md) - Declarative Syntax - - [Overview](ts-syntax-intro.md) - - General UI Description Specifications + - [About Usage of UI Description Specifications](ts-syntax-intro.md) + - About General UI Description Specifications - [Basic Concepts](ts-general-ui-concepts.md) - Declarative UI Description Specifications - [Configuration Without Parameters](ts-parameterless-configuration.md) - [Configuration with Mandatory Parameters](ts-configuration-with-mandatory-parameters.md) - - - [Attribute Configuration](ts-attribution-configuration.md) + - [Attribute Configuration](ts-attribution-configuration.md) - [Event Configuration](ts-event-configuration.md) - [Child Component Configuration](ts-child-component-configuration.md) - Componentization @@ -46,21 +44,21 @@ - [@Observed and @ObjectLink](ts-other-states-observed-objectlink.md) - [@Consume and @Provide](ts-other-states-consume-provide.md) - [@Watch](ts-other-states-watch.md) - - About Rendering Control Syntax - - [if/else](ts-rending-control-syntax-if-else.md) - - [ForEach](ts-rending-control-syntax-foreach.md) - - [LazyForEach](ts-rending-control-syntax-lazyforeach.md) - - About @Component + - Rendering Control Syntax + - [if/else](ts-rending-control-syntax-if-else.md) + - [ForEach](ts-rending-control-syntax-foreach.md) + - [LazyForEach](ts-rending-control-syntax-lazyforeach.md) + - About Componentization - [build Function](ts-function-build.md) - [Initialization of Custom Components' Member Variables](ts-custom-component-initialization.md) - [Custom Component Lifecycle Callbacks](ts-custom-component-lifecycle-callbacks.md) - - [Component Creation and Re-initialization](ts-component-creation-re-initialization.md) + - [Examples: Component Creation and Re-initialization](ts-component-creation-re-initialization.md) - [About Syntactic Sugar](ts-syntactic-sugar.md) - Common Component Development Guidelines - [Button](ui-ts-basic-components-button.md) - [Web](ui-ts-components-web.md) - Common Layout Development Guidelines - - [Flex Layout](ui-ts-layout-flex.md) + - [Flexible Layout](ui-ts-layout-flex.md) - [Grid Layout](ui-ts-layout-grid-container.md) - [Media Query](ui-ts-layout-mediaquery.md) - Experiencing the Declarative UI @@ -74,9 +72,9 @@ - [Implementing Page Redirection and Data Transmission](ui-ts-page-redirection-data-transmission.md) - [Recommendations for Improving Performance](ts-performance-improvement-recommendation.md) -- JavaScript-based Web-like Development Paradigm +- UI Development with JavaScript-compatible Web-like Development Paradigm - [Overview](ui-js-overview.md) - - Framework + - Framework Overview - [File Organization](js-framework-file.md) - ["js" Tag](js-framework-js-tag.md) - [app.js](js-framework-js-file.md) @@ -100,14 +98,14 @@ - [Defining Gesture Events](ui-js-building-ui-event.md) - [Defining Page Routes](ui-js-building-ui-routes.md) - Common Component Development Guidelines - - Container Components + - Container Component Development - [List Development](ui-js-components-list.md) - [Dialog Development](ui-js-components-dialog.md) - [Form Development](ui-js-components-form.md) - [Stepper Development](ui-js-components-stepper.md) - [Tabs Development](ui-js-component-tabs.md) - [Swiper Development](ui-js-components-swiper.md) - - Basic Components + - Basic Component Development - [Text Development](ui-js-components-text.md) - [Input Development](ui-js-components-input.md) - [Button Development](ui-js-components-button.md) @@ -128,8 +126,8 @@ - [CanvasRenderingContext2D](ui-js-components-canvasrenderingcontext2d.md) - [Path2D](ui-js-components-path2d.md) - [OffscreenCanvas](ui-js-components-offscreencanvas.md) - - [Grid-container Development](ui-js-components-grid.md) - - Svg + - [Grid Container Development](ui-js-components-grid.md) + - SVG Development - [Basics](ui-js-components-svg-overview.md) - [Graph Drawing](ui-js-components-svg-graphics.md) - [Path Drawing](ui-js-components-svg-path.md) diff --git a/en/application-dev/ui/ts-framework-directory.md b/en/application-dev/ui/ts-framework-directory.md index 1e788f32305a7be845f4dbc95631dac2c42bb764..5d2704f3f9647df9c90ead125e723e9a46d8dea6 100644 --- a/en/application-dev/ui/ts-framework-directory.md +++ b/en/application-dev/ui/ts-framework-directory.md @@ -1,30 +1,38 @@ # Directory Structure -The following figure shows the typical directory structure of the eTS module (entry/src/main) for an application with feature abilities (FAs). +The following figure shows the typical directory structure of the **ets** module (in **entry/src/main**) for an application with feature abilities (FAs). ![en-us_image_0000001222967752](figures/en-us_image_0000001222967752.png) -Functions of the files are as follows: +The **ets** directory contains the following files: -- The Extended TypeScript (eTS) files that end with the .ets extension describe the UI layouts, styles, event interactions, and page logics. - +**.ets** files: Extended TypeScript (eTS) files that describe the UI layouts, styles, event interactions, and page logics. Functions of the folders and files are as follows: - - The **app.ets** file manages global application logics and lifecycles. -- The **pages** directory stores all component pages. +- The **pages** directory stores all pages. + +- The **common** directory stores common code files, such as files of custom components and public methods. + + +> **NOTE** +> +> - For details about the **resources** directory in **src/main**, see [Resource File Categories](ui-ts-basic-resource-file-categories.md). +>- TypeScript and JavaScript files can be imported as page files. + +"js" tag configuration: -- The **common** directory stores common code files, such as custom components and public methods. +Configure the **"js"** tag in the configuration file of your application. The **"js"** tag contains the instance name, page route, and window configuration information. > **NOTE** > -> - The **resources** directory is located in **src/main**. For details about this directory, see [Resource File Categories](ui-ts-basic-resource-file-categories.md). +> For details about the **"js"** tag in the FA model, see [Table 22 Internal structure of the js attribute](../quick-start/package-structure.md#internal-structure-of-the-js-attribute). > -> - TypeScript and JavaScript files can be imported as page files. +> For details about the **"js"** tag in the stage model, see [Table 3 Internal structure of the module tag](../quick-start/stage-structure.md#internal-structure-of-the-module-tag). diff --git a/en/application-dev/ui/ts-framework-js-tag.md b/en/application-dev/ui/ts-framework-js-tag.md deleted file mode 100644 index f13461a7e8c8844cfc85586412a52319125f8fd4..0000000000000000000000000000000000000000 --- a/en/application-dev/ui/ts-framework-js-tag.md +++ /dev/null @@ -1,102 +0,0 @@ -# "js" Tag - - -Configure the "js" tag in the **config.json** file of your application. The "js" tag contains the instance name, page route, and window configuration information. - - -| Tag | Type | Default Value | Mandatory | Description | -| -------- | -------- | -------- | -------- | -------- | -| name | string | default | Yes | Name of the eTS instance. | -| pages | Array | - | Yes | Page route information. For details, see ["pages"](#pages). | -| window | Object | - | No | Window configuration information. For details, see ["window"](#window). | -| mode | Object | - | No | Running type and syntax style of the JS component. For details, see ["mode"](#mode). | - - -## pages - -The "pages" defines the route information of each page's entry component. Each page consists of the page path and page name. The following is an example: - -```json -{ - "pages": [ - "pages/index", - "pages/detail" - ] -} -``` - -> **NOTE** -> - The first page in the "pages" list is the home page of the application. -> -> - The page name must not be a component name, for example, Text.ets or Button.ets. -> -> - Each page file must contain the [page entry component](../ui/ts-component-based-entry.md) (with the @Entry decoration). - - -## window - -The "window" configures the view window. The following attributes can be configured: - -| Type | Default Value | Description | -| -------- | -------- | -------- | -| designWidth | - | Logical width of the view. The default value is 720. (The default value is 454 for wearables.) The logical width of the view determines the unit size of lpx. For example, if designWidth is 720 and the view width is 1440 physical pixels, 1 lpx is 2 physical pixels. For details, see [lpx](../ui/ts-pixel-units.md). | - -```json -{ - ... - "window": { - "designWidth": 720 - } - ... -} -``` - - -## mode - -The "mode" configures the running type and syntax style of a JS component. The following attributes are supported: - -| Type | Default Value | Description | -| -------- | -------- | -------- | -| type | - | Running type of the JS component. The options are as follows:
- pageAbility: Run the JS component in ability mode.
- form: Run the JS component as a service widget. | -| syntax | - | Syntax type of the JS component. The options are as follows:
- hml: compiled in the .hml, .css, or .js style.
- ets: compiled in the declarative syntax style. | - -> **NOTE** -> If type is set to form, syntax cannot be ets. - - -## Example - -config.json: - -```json -{ - "app": { - "bundleName": "com.example.player", - "version": { - "code": 1, - "name": "1.0" - }, - "vendor": "example" - }, - "module": { - "js": [{ - "name": "default", - "pages": [ - "pages/index", - "pages/detail" - ], - "window": { - "designWidth": 720 - }, - "mode": { - "type": "pageAbility", - "syntax": "ets" - }, - }], - "abilities": [{ - ... - }] - } -} -``` diff --git a/en/application-dev/ui/ts-resource-access.md b/en/application-dev/ui/ts-resource-access.md index f6c6d7e96bd4bd5f9e9e35e9205a0d84069b0d7f..271aaef3ca39ae9db50f9e3b410351dbc202928c 100644 --- a/en/application-dev/ui/ts-resource-access.md +++ b/en/application-dev/ui/ts-resource-access.md @@ -1,4 +1,4 @@ -# Accessing Application Resources +# Resource Access ## Accessing Application Resources diff --git a/en/application-dev/website.md b/en/application-dev/website.md index 1039ccfc5707c4a4253eb87d7e51f20a08867e4e..123f42406d4570caf213019a48bcd8ff8b213f5c 100644 --- a/en/application-dev/website.md +++ b/en/application-dev/website.md @@ -1,7 +1,7 @@ # Application Development - - [Application Development Overview](application-dev-guide.md) - Quick Start + - Getting Started - [Preparations](quick-start/start-overview.md) - [Getting Started with eTS in Stage Model](quick-start/start-with-ets-stage.md) @@ -43,12 +43,10 @@ - File Organization - [Directory Structure](ui/ts-framework-directory.md) - [Rules for Accessing Application Code Files](ui/ts-framework-file-access-rules.md) - - ["js" Tag](ui/ts-framework-js-tag.md) - Resource Management - [Resource File Categories](ui/ui-ts-basic-resource-file-categories.md) - [Accessing Resources](ui/ts-resource-access.md) - [Pixel Units](ui/ts-pixel-units.md) - - [Types](ui/ts-types.md) - Declarative Syntax - [Overview](ui/ts-syntax-intro.md) - General UI Description Specifications @@ -108,6 +106,7 @@ - [Building a Food Category List Layout](ui/ui-ts-building-category-list-layout.md) - [Building a Food Category Grid Layout](ui/ui-ts-building-category-grid-layout.md) - [Implementing Page Redirection and Data Transmission](ui/ui-ts-page-redirection-data-transmission.md) + - [Recommendations for Improving Performance](ui/ts-performance-improvement-recommendation.md) - JavaScript-based Web-like Development Paradigm - [Overview](ui/ui-js-overview.md) - Framework @@ -181,7 +180,6 @@ - [Animation Frame](ui/ui-js-animate-frame.md) - [Custom Components](ui/ui-js-custom-components.md) - Common Event and Notification - - [Common Event and Notification Overview](notification/notification-brief.md) - [Common Event Development](notification/common-event.md) - [Notification Development](notification/notification-guidelines.md) @@ -198,12 +196,12 @@ - [WebGL Overview](webgl/webgl-overview.md) - [WebGL Development](webgl/webgl-guidelines.md) - Media - - Audio - [Audio Overview](media/audio-overview.md) - [Audio Playback Development](media/audio-playback.md) - [Audio Recording Development](media/audio-recorder.md) - [Audio Rendering Development](media/audio-renderer.md) + - [Audio Stream Management Development](media/audio-stream-manager.md) - [Audio Capture Development](media/audio-capturer.md) - [OpenSL ES Audio Playback Development](media/opensles-playback.md) - [OpenSL ES Audio Recording Development](media/opensles-capture.md) @@ -215,8 +213,8 @@ - [Image Development](media/image.md) - Camera - [Camera Development](media/camera.md) + - [Distributed Camera Development](media/remote-camera.md) - Security - - Access Control - [Access Control Overview](security/accesstoken-overview.md) - [Access Control Development](security/accesstoken-guidelines.md) @@ -354,6 +352,9 @@ - [Component ID](reference/arkui-ts/ts-universal-attributes-component-id.md) - [Touch Target](reference/arkui-ts/ts-universal-attributes-touch-target.md) - [Polymorphic Style](reference/arkui-ts/ts-universal-attributes-polymorphic-style.md) + - [Hit Test Control](reference/arkui-ts/ts-universal-attributes-hit-test-behavior.md) + - [Background Blur](reference/arkui-ts/ts-universal-attributes-backgroundBlurStyle.md) + - [restoreId](reference/arkui-ts/ts-universal-attributes-restoreId.md) - Gesture Processing - [Gesture Binding Methods](reference/arkui-ts/ts-gesture-settings.md) - Basic Gestures @@ -412,10 +413,13 @@ - [Counter](reference/arkui-ts/ts-container-counter.md) - [Flex](reference/arkui-ts/ts-container-flex.md) - [GridContainer](reference/arkui-ts/ts-container-gridcontainer.md) + - [GridCol](reference/arkui-ts/ts-container-gridcol.md) + - [GridRow](reference/arkui-ts/ts-container-gridrow.md) - [Grid](reference/arkui-ts/ts-container-grid.md) - [GridItem](reference/arkui-ts/ts-container-griditem.md) - [List](reference/arkui-ts/ts-container-list.md) - [ListItem](reference/arkui-ts/ts-container-listitem.md) + - [ListItemGroup](reference/arkui-ts/ts-container-listitemgroup.md) - [Navigator](reference/arkui-ts/ts-container-navigator.md) - [Panel](reference/arkui-ts/ts-container-panel.md) - [Refresh](reference/arkui-ts/ts-container-refresh.md) @@ -468,6 +472,7 @@ - [Text Picker Dialog Box](reference/arkui-ts/ts-methods-textpicker-dialog.md) - [Menu](reference/arkui-ts/ts-methods-menu.md) - [Built-in Enums](reference/arkui-ts/ts-appendix-enums.md) + - [Types](reference/arkui-ts/ts-types.md) - Component Reference (JavaScript-based Web-like Development Paradigm) - Universal Component Information - [Universal Attributes](reference/arkui-js/js-components-common-attributes.md) @@ -627,6 +632,7 @@ - [ExtensionRunningInfo](reference/apis/js-apis-extensionrunninginfo.md) - [MissionSnapshot](reference/apis/js-apis-application-MissionSnapshot.md) - [ProcessRunningInfo](reference/apis/js-apis-processrunninginfo.md) + - [ProcessRunningInformation](reference/apis/js-apis-processrunninginformation.md) - [shellCmdResult](reference/apis/js-apis-application-shellCmdResult.md) - [ContinuationResult](reference/apis/js-apis-continuation-continuationResult.md) - Common Event and Notification @@ -677,7 +683,6 @@ - [@ohos.multimedia.camera](reference/apis/js-apis-camera.md) - [@ohos.multimedia.image](reference/apis/js-apis-image.md) - [@ohos.multimedia.media](reference/apis/js-apis-media.md) - - [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md) - Resource Management - [@ohos.i18n](reference/apis/js-apis-i18n.md) - [@ohos.intl](reference/apis/js-apis-intl.md) @@ -689,12 +694,14 @@ - [@ohos.WorkSchedulerExtensionAbility](reference/apis/js-apis-WorkSchedulerExtensionAbility.md) - Custom Management - [@ohos.configPolicy](reference/apis/js-apis-config-policy.md) - - [@ohos.enterpriseDeviceManager](reference/apis/js-apis-enterprise-device-manager.md) - [@ohos.EnterpriseAdminExtensionAbility](reference/apis/js-apis-EnterpriseAdminExtensionAbility.md) + - [@ohos.enterpriseDeviceManager](reference/apis/js-apis-enterprise-device-manager.md) + - [DeviceSettingsManager](reference/apis/js-apis-enterpriseDeviceManager-DeviceSettingsManager.md) - Security - [@ohos.abilityAccessCtrl](reference/apis/js-apis-abilityAccessCtrl.md) - [@ohos.privacyManager](reference/apis/js-apis-privacyManager.md) - [@ohos.security.huks](reference/apis/js-apis-huks.md) + - [@ohos.userIAM.faceAuth](reference/apis/js-apis-useriam-faceauth.md) - [@ohos.userIAM.userAuth](reference/apis/js-apis-useriam-userauth.md) - [@system.cipher](reference/apis/js-apis-system-cipher.md) - Data Management @@ -713,24 +720,25 @@ - [@ohos.environment](reference/apis/js-apis-environment.md) - [@ohos.fileio](reference/apis/js-apis-fileio.md) - [@ohos.fileManager](reference/apis/js-apis-filemanager.md) + - [@ohos.multimedia.medialibrary](reference/apis/js-apis-medialibrary.md) + - [@ohos.securityLabel](reference/apis/js-apis-securityLabel.md) - [@ohos.statfs](reference/apis/js-apis-statfs.md) - [@ohos.storageStatistics](reference/apis/js-apis-storage-statistics.md) - [@ohos.volumeManager](reference/apis/js-apis-volumemanager.md) - - [@ohos.securityLabel](reference/apis/js-apis-securityLabel.md) - Telephony Service - [@ohos.contact](reference/apis/js-apis-contact.md) - [@ohos.telephony.call](reference/apis/js-apis-call.md) + - [@ohos.telephony.data](reference/apis/js-apis-telephony-data.md) - [@ohos.telephony.observer](reference/apis/js-apis-observer.md) - [@ohos.telephony.radio](reference/apis/js-apis-radio.md) - [@ohos.telephony.sim](reference/apis/js-apis-sim.md) - [@ohos.telephony.sms](reference/apis/js-apis-sms.md) - - [@ohos.telephony.data](reference/apis/js-apis-telephony-data.md) - Network Management - [@ohos.net.connection](reference/apis/js-apis-net-connection.md) - [@ohos.net.http](reference/apis/js-apis-http.md) - - [@ohos.request](reference/apis/js-apis-request.md) - [@ohos.net.socket](reference/apis/js-apis-socket.md) - [@ohos.net.webSocket](reference/apis/js-apis-webSocket.md) + - [@ohos.request](reference/apis/js-apis-request.md) - Connectivity - [@ohos.bluetooth](reference/apis/js-apis-bluetooth.md) - [@ohos.connectedTag](reference/apis/js-apis-connectedTag.md) @@ -740,6 +748,8 @@ - [@ohos.rpc](reference/apis/js-apis-rpc.md) - [@ohos.wifi](reference/apis/js-apis-wifi.md) - [@ohos.wifiext](reference/apis/js-apis-wifiext.md) + - [nfctech](reference/apis/js-apis-nfctech.md) + - [tagSession](reference/apis/js-apis-tagSession.md) - Basic Features - [@ohos.accessibility](reference/apis/js-apis-accessibility.md) - [@ohos.faultLogger](reference/apis/js-apis-faultLogger.md) @@ -752,11 +762,13 @@ - [@ohos.hiTraceMeter](reference/apis/js-apis-hitracemeter.md) - [@ohos.inputMethod](reference/apis/js-apis-inputmethod.md) - [@ohos.inputMethodEngine](reference/apis/js-apis-inputmethodengine.md) + - [@ohos.inputmethodextensionability](reference/apis/js-apis-inputmethod-extension-ability.md) + - [@ohos.inputmethodextensioncontext](reference/apis/js-apis-inputmethod-extension-context.md) - [@ohos.pasteboard](reference/apis/js-apis-pasteboard.md) - [@ohos.screenLock](reference/apis/js-apis-screen-lock.md) - [@ohos.systemTime](reference/apis/js-apis-system-time.md) - - [@ohos.wallpaper](reference/apis/js-apis-wallpaper.md) - [@ohos.systemTimer](reference/apis/js-apis-system-timer.md) + - [@ohos.wallpaper](reference/apis/js-apis-wallpaper.md) - [Timer](reference/apis/js-apis-timer.md) - Device Management - [@ohos.batteryInfo](reference/apis/js-apis-battery-info.md) @@ -772,6 +784,7 @@ - [@ohos.multimodalInput.keyCode](reference/apis/js-apis-keycode.md) - [@ohos.multimodalInput.keyEvent](reference/apis/js-apis-keyevent.md) - [@ohos.multimodalInput.mouseEvent](reference/apis/js-apis-mouseevent.md) + - [@ohos.multimodalInput.pointer](reference/apis/js-apis-pointer.md) - [@ohos.multimodalInput.touchEvent](reference/apis/js-apis-touchevent.md) - [@ohos.power](reference/apis/js-apis-power.md) - [@ohos.runningLock](reference/apis/js-apis-runninglock.md) @@ -787,6 +800,7 @@ - [@ohos.account.distributedAccount](reference/apis/js-apis-distributed-account.md) - [@ohos.account.osAccount](reference/apis/js-apis-osAccount.md) - Language Base Class Library + - [@ohos.buffer](reference/apis/js-apis-buffer.md) - [@ohos.convertxml](reference/apis/js-apis-convertxml.md) - [@ohos.process](reference/apis/js-apis-process.md) - [@ohos.uri](reference/apis/js-apis-uri.md) @@ -844,4 +858,17 @@ - [EGL Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/egl-symbol.md) - [OpenGL ES 3.0 Symbols Exported from Native APIs](reference/native-lib/third_party_opengl/openglesv3-symbol.md) - FAQs - - [Guide to Switching to Full SDK](quick-start/full-sdk-switch-guide.md) \ No newline at end of file + - [Guide to Switching to Full SDK](quick-start/full-sdk-switch-guide.md) + - [Ability Framework Development](faqs/faqs-ability.md) + - [ArkUI (JavaScript) Development](faqs/faqs-ui-js.md) + - [ArkUI (eTS) Development](faqs/faqs-ui-ets.md) + - [Graphics and Image Development](faqs/faqs-graphics.md) + - [File Management Development](faqs/faqs-file-management.md) + - [Network and Connection Development](faqs/faqs-connectivity.md) + - [Device Management Development](faqs/faqs-data-management.md) + - [Device Management Development](faqs/faqs-device-management.md) + - [Native API Usage](faqs/faqs-native.md) + - [Usage of Third- and Fourth-Party Libraries](faqs/faqs-third-party-library.md) + - [IDE Usage](faqs/faqs-ide.md) + - [hdc_std Command Usage](faqs/faqs-hdc-std.md) + - [Development Board](faqs/faqs-development-board.md) diff --git a/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md b/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md index 92a1a7c405e461bb182db62964360dc8f3da46f3..ec4fa18e05b99cfae7ac312c27153e98f79aefd1 100644 --- a/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md +++ b/en/contribute/OpenHarmony-c-cpp-secure-coding-guide.md @@ -6,7 +6,8 @@ This document provides some secure coding suggestions based on the C\&C++ langua ## Check the validity of all values received from external sources -**\[Description]** +**\[Description]** + External sources are networks, user input, command lines, files (including program configuration files), environment variables, user-mode data (for kernel programs), inter-process communications (including pipes, messages, shared memory, sockets, RPCs, and communications between different boards in a device), API parameters, and global variables. Data from outside programs is often considered untrusted and needs to be properly checked for validity before being used. If data from an external source is not checked before use, unexpected security risks may occur. @@ -15,15 +16,45 @@ Note: Do not use assertions to check external input data. Assertions should be u Data from outside programs must be checked before being used. Typical scenarios include: -**Used as an array index**If untrusted data is used as an array index, the array upper bound may be exceeded, causing invalid memory access. **Used as a memory offset address** -Using untrusted data as the pointer offset for memory access may result in invalid memory access and cause further damages, for example, any address read/write. **Used as a memory allocation size parameter** -Zero-byte allocation may cause invalid memory access; an unrestricted memory allocation size leads to excessive resource consumption. **Used a loop condition** -If untrusted data is used as a loop condition, problems such as buffer overflow, out-of-bounds read/write, and infinite loop may occur. **Used as a divisor** -Divide-by-zero errors may occur. **Used as a command line parameter** -Command injection vulnerabilities may occur. **Used as the parameter of a database query statement**SQL injection vulnerabilities may occur. **Used as an input/output format string** -Format string vulnerabilities may occur. **Used as a memory copy length** -Buffer overflows may occur. **Used a file path** -Direct access to an untrusted file path may result in directory traversal attacks. As a result, the system is controlled by the attacker who can perform file operations without permissions. +- **Used as an array index** + + If untrusted data is used as an array index, the array upper bound may be exceeded, causing invalid memory access. + +- **Used as a memory offset address** + + Using untrusted data as the pointer offset for memory access may result in invalid memory access and cause further damages, for example, any address read/write. + +- **Used as a memory allocation size parameter** + + Zero-byte allocation may cause invalid memory access; an unrestricted memory allocation size leads to excessive resource consumption. + +- **Used a loop condition** + + If untrusted data is used as a loop condition, problems such as buffer overflow, out-of-bounds read/write, and infinite loop may occur. + +- **Used as a divisor** + + Divide-by-zero errors may occur. + +- **Used as a command line parameter** + + Command injection vulnerabilities may occur. + +- **Used as the parameter of a database query statement** + + SQL injection vulnerabilities may occur. + +- **Used as an input/output format string** + + Format string vulnerabilities may occur. + +- **Used as a memory copy length** + + Buffer overflows may occur. + +- **Used a file path** + + Direct access to an untrusted file path may result in directory traversal attacks. As a result, the system is controlled by the attacker who can perform file operations without permissions. Input validation includes but is not limited to: @@ -33,19 +64,32 @@ Input validation includes but is not limited to: - Data type and format check - Check on inputs that can only contain permitted characters (in the trustlist), especially special characters in certain cases. -**External Data Validation Principles - -1. Trust boundary** - External data is untrusted. Therefore, if data is transmitted and processed across different trust boundaries during system operation, validity check must be performed on data from modules outside the trust boundaries to prevent attacks from spreading. (a) Different so (or dll) modules - As an independent third-party module, the so or dll module is used to export common API functions for other modules to call. The so/dll module is unable to determine whether the caller passes on valid arguments. Therefore, the common function of the so/dll module needs to check the validity of the arguments provided by the caller. The so/dll module should be designed in low coupling and high reusability. Although the so/dll module is designed to be used only in this software in certain cases, different so/dll modules should still be regarded as different trust boundaries. (b) Different processes - To prevent privilege escalation through processes with high permissions, the IPC communications between processes (including IPC communications between boards and network communications between hosts) should be regarded as communications across different trust boundaries. (c) Application layer processes and operating system kernel - The operating system kernel has higher permissions than the application layer. The interface provided by the kernel for the application layer should process the data from the application layer as untrusted data. (d) Internal and external environments of TEE +**External Data Validation Principles** + +1. Trust boundary + + External data is untrusted. Therefore, if data is transmitted and processed across different trust boundaries during system operation, validity check must be performed on data from modules outside the trust boundaries to prevent attacks from spreading. + + (a) Different so (or dll) modules + + As an independent third-party module, the so or dll module is used to export common API functions for other modules to call. The so/dll module is unable to determine whether the caller passes on valid arguments. Therefore, the common function of the so/dll module needs to check the validity of the arguments provided by the caller. The so/dll module should be designed in low coupling and high reusability. Although the so/dll module is designed to be used only in this software in certain cases, different so/dll modules should still be regarded as different trust boundaries. + + (b) Different processes + + To prevent privilege escalation through processes with high permissions, the IPC communications between processes (including IPC communications between boards and network communications between hosts) should be regarded as communications across different trust boundaries. + + (c) Application layer processes and operating system kernel + The operating system kernel has higher permissions than the application layer. The interface provided by the kernel for the application layer should process the data from the application layer as untrusted data. + + (d) Internal and external environments of TEE To prevent attacks from spreading to the TEE, the interfaces provided by the TEE and SGX for external systems should process external data as untrusted data. -**2. External data validation** -The external data received by a module must be validated before being used. After data validation is completed, the data stored in the module does not need to be verified again by other internal subfunctions in the module. +2. External data validation + + The external data received by a module must be validated before being used. After data validation is completed, the data stored in the module does not need to be verified again by other internal subfunctions in the module. + +**\[Noncompliant Code Example]** -**\[Noncompliant Code Example]** The **Foo()** function processes external data. Because the buffer does not necessarily end with '\\0', the **nameLen** value returned by **strlen** may exceed **len**. As a result, out-of-bounds read occurs. ```cpp @@ -60,7 +104,8 @@ void Foo(const unsigned char* buffer, size_t len) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + External data is checked for validity. In this example, **strnlen** is used to calculate the string length to reduce the risk of out-of-bounds read. ```cpp @@ -138,7 +183,8 @@ For module A, the buffer is an external untrusted input, which must be strictly ## Class member variables must be explicitly initialized -**\[Description]** +**\[Description]** + If a class member variable is not explicitly initialized, the object will have an indeterminate value. If the class member variable has a default constructor, it does not need to be explicitly initialized. **\[Noncompliant Code Example]** @@ -162,7 +208,8 @@ Message message; // The message member variable is not com message.Process(); // Potential risks exist in subsequent use. ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + One practice is to explicitly initialize the class member variable in declarations. ```cpp @@ -202,8 +249,10 @@ private: ## Clearly define the special member functions to be implemented -**\[Description]** -**Rule of three** +**\[Description]** + +**Rule of three** + If a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three. ```cpp @@ -245,7 +294,8 @@ The implicitly-defined special member functions are typically incorrect if the c Classes that manage non-copyable resources through copyable handles may have to declare copy assignment and copy constructor private and not provide their definitions or define them as deleted. -**Rule of five** +**Rule of five** + The presence of a user-defined destructor, copy-constructor, or copy-assignment operator can prevent implicit definition of the move constructor and the move assignment operator. Therefore, any class for which move semantics are desirable has to declare all five special member functions. ```cpp @@ -298,7 +348,8 @@ private: However, failure to provide the move constructor and move assignment operator is usually not an error, but a missed optimization opportunity. -**Rule of zero** +**Rule of zero** + If a class does not need to deal exclusively with resource ownership, the class should not have custom destructors, copy/move constructors, or copy/move assignment operators. ```cpp @@ -345,10 +396,12 @@ public: ## The copy constructor, copy assignment operator, move constructor, and move assignment operator in the base class must be defined as non-public or deleted -**\[Description]** +**\[Description]** + Slicing occurs if a derived class object is directly assigned to a base class object. In this case, only the base class part is copied or moved, which undermines polymorphism. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code, the copy constructor and copy assignment operator of the base class are declared as default. Slicing occurs if a derived class object is assigned to the base class object. The copy constructor and copy assignment operator can be declared as deleted so that the compiler can check such assignment behavior. ```cpp @@ -377,7 +430,8 @@ Foo(d); ## The resources of the source object must be correctly reset in move constructors and move assignment operators -**\[Description]** +**\[Description]** + The move constructor and move assignment operator move the ownership of a resource from one object to another. Once the resource is moved, the resource of the source object should be reset correctly. This can prevent the source object from freeing the moved resources in destructors. Some non-resource data can be retained in the moved object, but the moved object must be in a state that can be properly destructed. Therefore, after an object is moved, do not reply on the value of the moved object unless the object is explicitly specified. lvalue reference may lead to unexpected behavior. @@ -454,10 +508,12 @@ std::cout << str << std::endl; ## The base class destructor must be declared as virtual when a derived class is released through a base class pointer -**\[Description]** +**\[Description]** + The destructor of the derived class can be called through polymorphism only when the base class destructor is declared as virtual. If the base class destructor is not declared as virtual, only the base class destructor (instead of the derived class destructor) is called when the derived class is released through a base class pointer, causing memory leaks. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + Memory leaks occur because the base class destructor is not declared as virtual. ```cpp @@ -530,7 +586,8 @@ Foo(d); ## Ensure that objects have been initialized before being used -**\[Description]** +**\[Description]** + Initialization is the process of setting the expected value for an object by means of explicit initialization, default constructor initialization, and value assignment. Reading an uninitialized value may result in undefined behaviour. Therefore, ensure that objects have been initialized before being used. **\[Noncompliant Code Example]** @@ -587,12 +644,14 @@ std::string data; // Compliant: Default constructor initialization ## Avoid using reinterpret\_cast -**\[Description]** +**\[Description]** + `reinterpret_cast` is used to convert irrelevant types. `reinterpret_cast` tries to cast one type to another type, which destroys the type of security and reliability. It is an unsafe conversion. It is advised to use reinterpret\_cast as little as possible. ## Avoid using const\_cast -**\[Description]** +**\[Description]** + `const_cast` is used to remove the `const` and `volatile` attributes of an object. Using a pointer or reference converted by **const\_cast** to modify a **const** or **volatile** object will result in undefined behavior. @@ -622,7 +681,8 @@ int main() ## Ensure no overflows in signed integer operations -**\[Description]** +**\[Description]** + In the C++ standard, signed integer overflow is undefined behavior. Therefore, signed integer overflows are handled differently in implementations. For example, after defining a signed integer type as a modulus, the compiler may not detect integer overflows. Using overflowed values may cause out-of-bounds read/write risks in the buffer. For security purposes, ensure that operations do not cause overflows when signed integers in external data are used in the following scenarios: @@ -636,7 +696,8 @@ Using overflowed values may cause out-of-bounds read/write risks in the buffer. Integer promotion needs to be considered when the operation is performed for the integer types whose precision is less than **int**. Programmers also need to master integer conversion rules, including implicit conversion rules, to design secure arithmetic operations. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the integers involved in the subtraction operation are external data and are not validated before being used. As a result, integer overflow may occur, which further results in buffer overflow due to memory copy operations. ```cpp @@ -652,7 +713,8 @@ std::copy_n(&content[skipLen], totalLen - skipLen, std::back_inserter(dest)); ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, code is refactored to use the variable of the `size_t` type to indicate the data length and check whether the external data length is valid. ```cpp @@ -670,7 +732,8 @@ std::copy_n(&content[skipLen], totalLen - skipLen, std::back_inserter(dest)); ... ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the value range of external data is validated. However, the second type is `int`, and `std::numeric_limits::max()` is incorrectly used as a validation condition. As a result, integer overflow occurs. ```cpp @@ -684,7 +747,8 @@ int millisecond = second * 1000; // Integer overflow may occur. ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + One option is to change the second type to `unsigned long`. This solution is applicable to the scenario where the new variable type is more fit for service logic. ```cpp @@ -708,12 +772,14 @@ if (second < 0 || second > (std::numeric_limits::max() / 1000)) { int millisecond = second * 1000; ``` -**\[Impact]** +**\[Impact]** + Integer overflows may cause buffer overflows and arbitrary code execution. ## Ensure that unsigned integer operations do not wrap -**\[Description]** +**\[Description]** + Integer wrap may occur in the arithmetic operation results of unsigned integers, which may cause risks such as out-of-bounds read/write in the buffer. For security purposes, ensure that operations do not cause wrapping when unsigned integers in external data are used in the following scenarios: - Pointer offset value (integer operands in pointer arithmetic operations) @@ -722,7 +788,8 @@ Integer wrap may occur in the arithmetic operation results of unsigned integers, - Parameter of the memory allocation function - Loop judgment condition -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the program checks whether the total length of the next sub-packet and the processed packet exceeds the maximum packet length. The addition operation in the check condition may cause integer wrapping, causing potential validation bypassing issues. ```cpp @@ -738,7 +805,8 @@ readLen += pktLen; ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + The readLen variable is the length of the processed packet and is definitely less than totalLen. Therefore, the use of the subtraction operation instead of the addition operation will not bypass the condition check. ```cpp @@ -754,7 +822,8 @@ readLen += pktLen; ... ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, integer wrapping may occur in the operation of len validation, resulting in condition check bypassing. ```cpp @@ -767,7 +836,8 @@ if (SCTP_SIZE_MAX - len < sizeof(SctpAuthBytes)) { // Integer wrapping may occur ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, the subtraction operation is relocated (ensure that the value of the subtraction expression is not reversed during compilation) to avoid integer wrapping. ```cpp @@ -780,15 +850,18 @@ if (len > SCTP_SIZE_MAX - sizeof(SctpAuthBytes)) { // Ensure no integer wrapping ... ``` -**\[Exception]** +**\[Exception]** + Unsigned integers can exhibit modulo behavior (wrapping) when necessary for the proper execution of the program. It is recommended that the variable declaration and each operation on that integer be clearly commented as supporting modulo behavior. -**\[Impact]** +**\[Impact]** + Integer wrapping is likely to cause buffer overflows and arbitrary code execution. ## Ensure that division and remainder operations do not cause divide-by-zero errors -**\[Description]** +**\[Description]** + Division remainder operations performed on integers with the divisor of zero are undefined behavior. Ensure that the divisor is not 0 in division and remainder operations. The ISO/IEEE 754-1985 standard for binary floating-point arithmetic specifies the behavior and results of floating-point number division by zero. However, the presence of undefined behavior depends on whether the hardware and software environments comply with this standard. Therefore, before dividing a floating point number by zero, ensure that the hardware and software environments comply with the binary floating-point arithmetic. Otherwise, undefined behavior still exists. @@ -802,7 +875,8 @@ size_t c = 1000 % a; // Noncompliant: a may be 0 ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, a=0 validation is added to prevent divide-by-zero errors. ```c @@ -815,12 +889,14 @@ size_t c = 1000 % a; // Compliant: Ensure that a is not 0. ... ``` -**\[Impact]** +**\[Impact]** + Divide-by-zero errors are likely to cause DoS. ## Bitwise operations can be performed only on unsigned integers -**\[Description]** +**\[Description]** + Undefined behavior may occur during bitwise operations on signed integers. To avoid undefined behavior, ensure that bitwise operations are performed only on unsigned integers. In addition, the unsigned integer type with less precision than **int** is promoted when a bitwise operation is performed on the unsigned integer. Then the bitwise operation is performed on the promoted integer. Therefore, beware of the bitwise operations on such unsigned integers to avoid unexpected results. The bitwise operators are as follows: - `~` (Complement operator) @@ -837,7 +913,8 @@ Undefined behavior may occur during bitwise operations on signed integers. To av C++20 defines bitwise shift operations on signed integers, and such operations can be performed in compliance with C++20. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In versions earlier than C++20, the right shift operation `data >> 24` can be implemented as arithmetic (signed) shift or logic (unsigned) shift. If the value in `value << data` is a negative number or the result of the left shift operation is out of the representable range of the promoted integer type, undefined behavior occurs. ```cpp @@ -897,10 +974,12 @@ uint32_t type = id >> SHIFT_BITS; ## Ensure validation of external data that is used as an array index or memory operation length -**\[Description]** +**\[Description]** + When external data is used as an array index for memory access, the data size must be strictly validated to ensure that the array index is within the valid scope. Otherwise, serious errors may occur. Buffer overflows will occur if data is copied to the memory space insufficient for storing the data. To prevent such errors, limit the size of data to be copied based on the target capacity or ensure that the target capacity is sufficient to store the data to be copied. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the **SetDevId()** function has an off-by-one error. When index equals `DEV_NUM`, an element is written out of bounds. ```cpp @@ -922,7 +1001,8 @@ int SetDevId(size_t index, int id) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, the index validation condition is modified to avoid the off-by-one error. ```cpp @@ -943,7 +1023,8 @@ int SetDevId(size_t index, int id) } ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + External input data may not be directly used as the memory copy length, but may be indirectly involved in memory copy operations. In the following code, **inputTable.count** is from external packets. It is used as the upper limit of the **for** loop body and indirectly involved in memory copy operations, instead of being directly used as the memory copy length. Buffer overflows may occur because the length is not validated. ```cpp @@ -963,7 +1044,8 @@ void ValueTableDup(const ValueTable& inputTable) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, **inputTable.count** is validated. ```cpp @@ -989,15 +1071,18 @@ void ValueTableDup(const ValueTable& inputTable) } ``` -**\[Impact]** +**\[Impact]** + If the length of the copied data is externally controllable, buffer overflows may occur during data copy operations, which may cause arbitrary code execution vulnerabilities. ## Verify the requested memory size before requesting memory -**\[Description]** +**\[Description]** + When the requested memory size is an external input, it must be verified to prevent the request for zero-length memory or excessive and illegal memory requests. This is because memory resources are limited and can be exhausted. If the requested memory is too large (memory requested at a time is too large, or requested multiple times in a loop), resources may be used up unexpectedly. Unexpected buffer allocation may result from incorrect parameter values, improper range checks, integer overflows, or truncation. If memory requests are controlled by attackers, security issues such as buffer overflows may occur. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the memory space specified by **size** is dynamically allocated. However, **size** is not validated. ```c @@ -1011,7 +1096,8 @@ int DoSomething(size_t size) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, before the memory space specified by **size** is dynamically allocated, the validity check required by the program is performed. ```c @@ -1028,12 +1114,14 @@ int DoSomething(size_t size) } ``` -**\[Impact]** +**\[Impact]** + If the size of the requested memory is externally controllable, resources may be exhausted, resulting in DoS. ## An array should not be passed as a pointer separately when it is passed into a function as a parameter -**\[Description]** +**\[Description]** + When the function parameter type is array (not array reference) or pointer, the array that is being passed into a function is degraded to a pointer. As a result, the array length information is lost, causing potential out-of-bounds read/write issues. If a function receives only fixed-length arrays as parameters, define the parameter type as an array reference or `std::array`. If the function receives a pointer without a length, then the length should also be passed into the function as a parameter. **\[Noncompliant Code Example]** @@ -1118,7 +1206,8 @@ void Test() ## When a lambda escapes the current scope, do not capture local variables by reference -**\[Description]** +**\[Description]** + If a lambda is not limited to local use (for example, when it is transferred to the outside of a function or to another thread), do not capture local variables by reference. Capturing by reference in a lambda means storing a reference to a local object. If the life cycle of the lambda is longer than that of local variables, memory may be insecure. **\[Noncompliant Code Example]** @@ -1145,10 +1234,12 @@ void Foo() ## Assign a new value to the variable pointing to a resource handle or descriptor immediately after the resource is freed -**\[Description]** +**\[Description]** + Variables pointing to resource handles or descriptors include pointers, file descriptors, socket descriptors, and other variables pointing to resources. Take a pointer as an example. If a pointer that has successfully obtained a memory segment is not immediately set to **nullptr** after the memory segment is freed and no new object is allocated, the pointer is a dangling pointer. Operations on a dangling pointer may lead to double-free and access-freed-memory vulnerabilities. An effective way to mitigate these vulnerabilities is to immediately set freed pointers to new values, such as **nullptr**. For a global resource handle or descriptor, a new value must be set immediately after the resource is freed, so as to prevent the invalid value from being used. For a resource handle or descriptor that is used only in a single function, ensure that the invalid value is not used again after the resource is freed. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the message is processed based on the message type. After the message is processed, the memory to which the **body** points is freed, but the pointer is not set to **nullptr**. If other functions process the message structure again, double-free and access-freed-memory errors may occur. ```c @@ -1175,7 +1266,8 @@ int Fun() } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, the released pointer is immediately set to **nullptr** to avoid double-free errors. ```c @@ -1205,7 +1297,8 @@ int Fun() The default memory freeing function does not perform any action on NULL pointers. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, no new value is assigned to the file descriptor after it is closed. ```c @@ -1218,7 +1311,8 @@ close(fd); ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, a new value is assigned to the corresponding variable immediately after the resource is freed. ```c @@ -1233,12 +1327,14 @@ fd = -1; ... ``` -**\[Impact]** +**\[Impact]** + The practices of using the freed memory, freeing the freed memory again, or using the freed resources may cause DoS or arbitrary code execution. ## new and delete operators must be used in pairs, and new\[] and delete\[] operators must also be used in pairs. -**\[Description]** +**\[Description]** + The object created using the new operator can be destroyed only using the delete operator. The object array created using the new\[] operator can be destroyed only using the delete\[] operator. **\[Noncompliant Code Example]** @@ -1272,7 +1368,8 @@ private: ## The custom operators new and delete must be defined in pairs, and the behavior specified in the operators must be the same as that of the operators to be replaced -**\[Description]** +**\[Description]** + The custom operators new and delete as well as new\[] and delete\[] must be defined in pairs. The behavior specified in the new/delete operators must be the same as that of the operators to be replaced. **\[Noncompliant Code Example]** @@ -1342,7 +1439,8 @@ void* operator new(size_t size, const std::nothrow_t& tag) ## Throw an object itself instead of the pointer to the object when throwing an exception -**\[Description]** +**\[Description]** + The recommended exception throwing method in C++ is to throw the object itself instead of the pointer to the object. When the throw statement is used to throw an exception, a temporary object, called an exception object, is constructed. The life cycle of the exception object is clearly defined in the C++ standard: The exception object is constructed when it is thrown. It is destructed when a catch statement of the exception object does not end with `throw` (that is, it is not thrown again) or when the `std::exception_ptr` object that captures the exception is destructed. @@ -1393,7 +1491,8 @@ By default, destructors have the `noexcept` attribute. If they throw exceptions, ## Do not create a std::string from a null pointer -**\[Description]** +**\[Description]** + The null pointer is dereferenced when it is passed to the std::string constructor, causing undefined behavior. **\[Noncompliant Code Example]** @@ -1432,7 +1531,8 @@ void Foo() ## Do not save the pointers returned by the **c\_str()** and **data()** member functions of std::string -**\[Description]** +**\[Description]** + To ensure the validity of the reference values returned by the **c\_str()** and **data()** member functions of the std::string object, do not save the **c\_str()** and **data()** results of std::string. Instead, call them directly when needed (the call overhead is optimized through compiler inlining). Otherwise, when the std::string object is modified by calling its modify method, or when the std::string object is out of the scope, the stored pointer becomes invalid. Using an invalid pointer will result in undefined behavior. **\[Noncompliant Code Example]** @@ -1506,12 +1606,14 @@ void Foo3(std::string& s) } ``` -**\[Exception]** +**\[Exception]** + In rare cases where high performance coding is required, you can temporarily save the pointer returned by the c\_str() method of std::string to match the existing functions which support only the input parameters of the `const char*` type. However, you should ensure that the life cycle of the std::string object is longer than that of the saved pointer, and that the std::string object is not modified within the life cycle of the saved pointer. ## Ensure that the buffer for strings has sufficient space for character data and terminators, and that the string is null-terminated -**\[Description]** +**\[Description]** + A C-style character string is a continuous sequence of characters, which is terminated by the first null character and contains the null character. When copying or storing a C-style string, ensure that the buffer has sufficient space to hold the character sequence including the null terminator, and that the string is null terminated. Otherwise, buffer overflows may occur. @@ -1570,15 +1672,18 @@ void Foo(std::istream& in) } ``` -**\[Impact]** +**\[Impact]** + Setting no limits to the integer values in external data is likely to cause DoS, buffer overflows, information leaks, or arbitrary code execution. ## Do not use std::string to store sensitive information -**\[Description]** +**\[Description]** + The std::string class is a string management class defined in C++. If sensitive information (such as passwords) is operated using std::string, it may be scattered in memory during program running and cannot be cleared. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the **Foo()** function obtains the password, saves it to the std::string variable **password**, and then passes it to the **VerifyPassword()** function. In this process, two copies of the password exist in memory. ```cpp @@ -1594,12 +1699,14 @@ void Foo() } ``` -**\[Impact]** +**\[Impact]** + Sensitive information is not deleted in due time, which may cause information leaks. ## Ensure that the external data used as container indexes or iterators is within the valid range -**\[Description]** +**\[Description]** + External data is untrusted. When it is used as container or array indexes, ensure that its value is within the valid range of the elements that can be accessed by containers or arrays. When external data is used for iterator offset, ensure that the iterator offset value range is \[begin(), end()] of the container associated with the iterator (created from the begin() method of the container object c), that is, greater than or equal to c.begin() and less than or equal to c.end(). For a container (such as std::vector, std::set, or std::map) with the at() method, if the corresponding index is out of range or the key-value does not exist, the method throws an exception. If the index of the corresponding operator\[] is out of range, undefined behavior occurs. If the default key-value fails to be constructed when the corresponding key-value does not exist, undefined behavior also occurs. @@ -1688,7 +1795,8 @@ void Foo(size_t n) ## Use valid format strings when calling formatted input/output functions -**\[Description]** +**\[Description]** + When using C-style formatted input/output functions, ensure that the format strings are valid and strictly match the corresponding parameter types. Otherwise, unexpected behavior occurs. In addition to C-style formatted input/output functions, similar functions in C must also use valid format strings, for example, the **std::format()** function in C++20. @@ -1700,7 +1808,8 @@ extern int CustomPrintf(void* obj, const char* format, ...) __attribute__ ((format (printf, 2, 3))); ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, an integer is formatted into the macAddr variable, but macAddr is of the unsigned char type, and %x indicates a parameter of the int type. After the function is executed, out-of-bounds write occurs. ```c @@ -1714,7 +1823,8 @@ int ret = sscanf(macStr, "%x:%x:%x:%x:%x:%x\n", ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, %hhx is used to ensure that the format string strictly matches the parameter type. ```c @@ -1730,12 +1840,14 @@ int ret = sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx\n", Note: It is not advised to use C library functions, such as **sscanf()** and **sprintf()**, in C++. You can use std::istringstream, std::ostringstream, and std::stringstream instead. -**\[Impact]** +**\[Impact]** + An incorrect format string may cause memory damage or abnormal program termination. ## Ensure that the format parameter is not controlled by external data when a formatted input/output function is called -**\[Description]** +**\[Description]** + When a formatted function is called, the **format** parameter provided or concatenated by external data will cause a string formatting vulnerability. Take the formatted output function of the C standard library as an example. When the **format** parameter is externally controllable, an attacker can use the %n converter to write an integer to a specified address, use the %x or %d converter to view the stack or register content, or use the %s converter to cause process crashes or other issues. Common formatted functions are as follows: @@ -1753,7 +1865,8 @@ Box v{MAX_COUNT}; std::cout << std::format("{:#x}", v); ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the **Log()** function is used to directly log external data, which may cause a format string vulnerability. ```c @@ -1777,12 +1890,14 @@ void Foo() } ``` -**\[Impact]** +**\[Impact]** + If the format string is externally controllable, attackers can crash the process, view the stack content, view the memory content, or write data to any memory location, and then execute any code with the permission of the compromised process. ## Do not use external controllable data as parameters for process startup functions or for the loading functions of dlopen/LoadLibrary and other modules -**\[Description]** +**\[Description]** + Process startup functions in this requirement include **system()**, **popen()**, **execl()**, **execlp()**, **execle()**, **execv()**, and **execvp()**. Each of these functions such as **system()** and **popen()** will create a process. If external controllable data is used as the parameters of these functions, injection vulnerabilities may occur. When functions such as **execl()** are used to execute new processes, command injection risks also exist if shell is used to start new processes. The use of **execlp()**, **execvp()**, and **execvpe()** functions depends on the program paths searched using the system environment variable PATH. Consider the risks of external environment variables when using these functions, or avoid using these functions. Therefore, C standard functions are always preferred to implement the required functions. If you need to use these functions, use the trustlist mechanism to ensure that the parameters of these functions are not affected by any external data. @@ -1794,7 +1909,8 @@ The **dlopen()** and **LoadLibrary()** functions load external modules. If exter - After the security of the dynamic library loaded locally is ensured by means of permission and access control, the dynamic library is automatically loaded using a specific directory. - After the security of the local configuration file is ensured by means of permission and access control, the dynamic library specified in the configuration file is automatically loaded. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, external controllable data is directly used as the parameter of the **LoadLibrary()** function, which may implant Trojan horses into the program. ```c @@ -1942,7 +2058,9 @@ The **sizeof** operator yields the size (in bytes) of its operand, which can be Arguments declared as arrays in the argument list will be adjusted to pointers of corresponding types. For example, although the inArray argument in the `void Func(int inArray[LEN])` function is declared as an array, it is actually adjusted to an int pointer, that is, `void Func(int *inArray)`. As a result, `sizeof(inArray)` is equal to `sizeof(int *)` in this function, leading to unexpected result. For example, in the IA-32 architecture, `sizeof(inArray)` is 4, not the inArray size. -**\[Noncompliant Code Example]**In the following code example, the **ArrayInit()** function is used to initialize array elements. This function has a parameter declared as `int inArray[]`. When this function is called, a 256-element integer array **data** is passed to it. The **ArrayInit()** function uses `sizeof(inArray) / sizeof(inArray[0])` to determine the number of elements in the input array. However, **inArray** is a function parameter and therefore has a pointer type. As a result, `sizeof(inArray)` is equal to `sizeof(int *)`. The expression `sizeof(inArray) / sizeof(inArray[0])` evaluates to 1, regardless of the length of the array passed to the **ArrayInit()** function, leading to unexpected behavior. +**\[Noncompliant Code Example]** + +In the following code example, the **ArrayInit()** function is used to initialize array elements. This function has a parameter declared as `int inArray[]`. When this function is called, a 256-element integer array **data** is passed to it. The **ArrayInit()** function uses `sizeof(inArray) / sizeof(inArray[0])` to determine the number of elements in the input array. However, **inArray** is a function parameter and therefore has a pointer type. As a result, `sizeof(inArray)` is equal to `sizeof(int *)`. The expression `sizeof(inArray) / sizeof(inArray[0])` evaluates to 1, regardless of the length of the array passed to the **ArrayInit()** function, leading to unexpected behavior. ```c #define DATA_LEN 256 @@ -1964,7 +2082,8 @@ void FunctionData(void) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, the function definition is modified, an array size parameter is added, and the array size is correctly passed to the function. ```c @@ -1986,7 +2105,8 @@ void FunctionData(void) } ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, `sizeof(inArray)` does not equal `ARRAY_MAX_LEN * sizeof(int)`, because the **sizeof** operator, when applied to a parameter declared to have array type, yields the size of the adjusted (pointer) type even if the parameter declaration specifies a length. In this case, `sizeof(inArray)` is equal to `sizeof(int *)`. ```c @@ -2011,7 +2131,8 @@ int main(void) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, the specified array length is indicated by the **len** argument. ```c @@ -2038,10 +2159,12 @@ int main(void) ## Do not perform the **sizeof** operation on pointer variables to obtain the array size -**\[Description]** +**\[Description]** + Performing the **sizeof** operation on a pointer that is used as an array leads to an unexpected result. For example, in the variable definition `char *p = array` where array is defined as `char array[LEN]`, the result of the expression `sizeof(p)` is the same as that of `sizeof(char *)`, but not the size of the array. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, **buffer** is a pointer while **path** is an array. The programmer wants to clear the two memory segments. However, the programmer mistakenly writes the memory size as `sizeof(buffer)`, leading to an unexpected result. ```c @@ -2056,7 +2179,8 @@ memset(path, 0, sizeof(path)); memset(buffer, 0, sizeof(buffer)); ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, `sizeof(buffer)` is changed to the size of the requested buffer: ```c @@ -2071,7 +2195,8 @@ memset(buffer, 0, SIZE); // Use the requested buffer size. ## Do not directly use external data to concatenate SQL statements -**\[Description]** +**\[Description]** + An SQL injection vulnerability arises when an SQL query is dynamically altered to form an altogether different query. Execution of this altered query may result in information leaks or data tampering. The root cause of SQL injection is the use of external data to concatenate SQL statements. In C/C++, external data is used to concatenate SQL statements in the following scenarios (but not limited to): - Argument for calling **mysql\_query()** and **Execute()** when connecting to MySQL @@ -2087,7 +2212,8 @@ The following methods can be used to prevent SQL injection: - Verify external data (trustlist verification is recommended). - Escape external SQL special characters. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + The following code concatenates user input without checking the input, causing SQL injection risks: ```c @@ -2103,7 +2229,8 @@ ret = mysql_query(&myConnection, sqlStatements); ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + Use prepared statements for parameterized query to defend against SQL injection attacks: ```c @@ -2136,7 +2263,8 @@ If the string of a concatenated SQL statement is externally controllable, attack ## Clear sensitive information from memory immediately after using it -**\[Description]** +**\[Description]** + Sensitive information (such as passwords and keys) in memory must be cleared immediately after being used to prevent it from being obtained by attackers or accidentally disclosed to low-privilege users. Memory includes but is not limited to: - Dynamically allocated memory @@ -2145,7 +2273,8 @@ Sensitive information (such as passwords and keys) in memory must be cleared imm - Memory cache - Disk cache -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + Generally, memory data does not need to be cleared before memory resources are released to prevent extra overheads during running. Therefore, after memory resources are released, the data remains in memory. In this case, sensitive information in the data may be leaked accidentally. To prevent sensitive information leakage, you must clear sensitive information from memory before releasing memory resources. In the following code example, the sensitive information **secret** stored in the referenced dynamic memory is copied to the newly dynamically allocated buffer **newSecret**, and is finally released through **free()**. As data is not cleared before the memory block is released, the memory block may be reallocated to another part of the program, and sensitive information stored in **newSecret** may be accidentally disclosed. ```c @@ -2172,7 +2301,8 @@ if (newSecret == NULL) { ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, to prevent information leakage, clear the dynamic memory that contains sensitive information (by filling the memory space with '\\0') and then release it. ```c @@ -2199,7 +2329,8 @@ if (newSecret == NULL) { ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + The following code is another scenario involving sensitive information clearance. After obtaining the password, the code saves the password to **password** for verification. After the password is used, `memset()` is used to clear the password. ```c @@ -2259,12 +2390,14 @@ Failure to rapidly clear sensitive information may cause information leakage. ## Create files with appropriate access permissions explicitly specified -**\[Description]** +**\[Description]** + If no appropriate access permissions are explicitly specified when a file is created, unauthorized users may access the file, causing information leakage, file data tampering, and malicious code injection into the file. Although file access permissions depend on the file system, many file creation functions (POSIX **open()** functions, etc.) provide mechanisms to set (or influence) file access permissions. Therefore, when these functions are used to create files, appropriate file access permissions must be explicitly specified to prevent unintended access. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + The POSIX **open()** function is used to create a file but the access permission for the file is not specified, which may cause the file to be created with excessive access permissions. This may lead to vulnerabilities (e.g. CVE-2006-1174). ```c @@ -2283,7 +2416,8 @@ void Foo(void) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + Access permissions for the newly created file should be explicitly specified in the third argument to **open()**. Access permissions for a file can be set based on actual applications of the file. ```c @@ -2309,7 +2443,8 @@ Creating files with weak access permissions may cause unauthorized access to th ## Canonicalize and validate file paths before using them -**\[Description]** +**\[Description]** + File paths from external data must be validated. Otherwise, system files may be accessed randomly. However, direct validation is not allowed. The file paths must be canonicalized before validation because a file can be described and referenced by paths in various forms. For example, a file path can be an absolute path or a relative path, and the path name, directory name, or file name may contain characters (for example, "." or "..") that make validation difficult and inaccurate. In addition, the file may also be a symbolic link, which further obscures the actual location or identity of the file, making validation difficult and inaccurate. Therefore, file paths must be canonicalized to make it much easier to validate a path, directory, or file name, thereby improving validation accuracy. Because the canonical form may vary with operating systems and file systems, it is best to use a canonical form consistent with the current system features. @@ -2321,7 +2456,8 @@ Canonicalize file paths coming from external data. Without canonicalization, att For example, an attacker can construct "../../../etc/passwd" to access any file. ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In this noncompliant code example, **inputFilename** contains a file name that originates from a tainted source, and the file is opened for writing. Before this file name is used for file operations, it should be validated to ensure that it references an expected and valid file. Unfortunately, the file name referenced by **inputFilename** may contain special characters, such as directory characters, which make validation difficult or even impossible. In addition, **inputFilename** may contain a symbolic link to any file path. Even if the file name passes validation, it is invalid. In this scenario, even if the file name is directly validated, the expected result cannot be obtained. The call to **fopen()** may result in unintended access to a file. ```c @@ -2338,7 +2474,8 @@ if (fopen(inputFilename, "w") == NULL) { ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + Canonicalizing file names is difficult because it requires an understanding of the underlying file system. The POSIX **realpath()** function can help convert path names to a canonical form. According to Standard for Information Technology—Portable Operating System Interface (POSIX®), Base Specifications, Issue 7 \[IEEE Std 1003.1:2013]: - The **realpath()** function shall derive, from the pathname pointed to by **filename**, an absolute pathname that names the same file, whose resolution does not involve a dot (.), double dots (..), or symbolic links. Further verification, such as ensuring that two consecutive slashes or special files do not appear in the file name, must be performed after canonicalization. For more information about how to perform path name resolution, see section 4.12 "Pathname Resolution" of IEEE Std 1003.1:2013. There are many precautions for using the **realpath()** function. With an understanding of the preceding principles, the following solution can be taken to address the noncompliant code example. @@ -2371,7 +2508,8 @@ realpathRes = NULL; ... ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + Based on the actual scenario, a second solution can also be used. The description is as follows: If `PATH_MAX` is defined as a constant in **limits.h**, it is also safe to call **realpath()** with a non-null `resolved_path` value. In this example, the **realpath()** function expects `resolved_path` to refer to a character array that is large enough to hold the canonicalized path. If **PATH\_MAX** is defined, allocate a buffer of size `PATH_MAX` to hold the result of **realpath()**. The compliant code example is as follows: ```c @@ -2412,7 +2550,8 @@ canonicalFilename = NULL; ... ``` -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + The following code obtains file names from external data, concatenates them into a file path, and directly reads the file content. As a result, attackers can read the content of any file. ```c @@ -2423,7 +2562,8 @@ int ret = sprintf(untrustPath, "/tmp/%s", filename); char *text = ReadFileContent(untrustPath); ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + Canonicalize the file path and then check whether the path is valid in the program. ```c @@ -2465,7 +2605,8 @@ Failure to canonicalize and validate untrusted file paths may cause access to an ## Do not create temporary files in shared directories -**\[Description]** +**\[Description]** + A shared directory refers to a directory that can be accessed by non-privileged users. The temporary files of a program must be exclusively used by the program. If you place the temporary files of the program in the shared directory, other sharing users may obtain additional information about the program, resulting in information leakage. Therefore, do not create temporary files that are used only by a program itself in any shared directory. Temporary files are commonly used for auxiliary storage of data that cannot reside in memory or temporary data and also as a means of inter-process communication (by transmitting data through the file system). For example, one process creates a temporary file with a well-known name or a temporary name in a shared directory. The file can then be used to share information among processes. This practice is dangerous because files in a shared directory can be easily hijacked or manipulated by an attacker. Mitigation strategies include the following: @@ -2486,7 +2627,8 @@ In addition, when two or more users or a group of users have read/write permissi Creating temporary files in a shared directory is vulnerable. For example, code that works for a locally mounted file system may be vulnerable when shared with a remotely mounted file system. The secure solution is not to create temporary files in shared directories. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + The program creates a temporary file with a hard-coded file name in the shared directory **/tmp** to store temporary data. Because the file name is hard-coded and consequently predictable, an attacker only needs to replace the file with a symbolic link. The target file referenced by the link is then opened and new content can be written. ```c @@ -2515,7 +2657,7 @@ int main(void) } ``` -****\[Compliant Code Example]**** +**\[Compliant Code Example]** ```c Do not create temporary files that are used only by a program itself in this directory. @@ -2527,13 +2669,15 @@ Creating temporary files in an insecure manner may cause unauthorized access to ## Do not access shared objects in signal handlers -**\[Description]** +**\[Description]** + Accessing or modifying shared objects in signal handlers can result in race conditions that can leave data in an uncertain state. This rule is not applicable to the following scenarios (see paragraph 5 in section 5.1.2.3 of the C11 standard): - Read/write operations on lock-free atomic object - Read/write operations on objects of the **volatile sig\_atomic\_t** type. An object of the **volatile sig\_atomic\_t** type can be accessed as an atomic entity even in the presence of asynchronous interrupts, and is asynchronous-safe. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the signal handler, the program attempts to use `g_msg` as the shared object and update the shared object when the SIGINT signal is delivered. However, `g_msg` is not a variable of type `volatile sig_atomic_t`, and is not asynchronous-safe. ```c @@ -2562,7 +2706,8 @@ int main(void) } ``` -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, only the `volatile sig_atomic_t` type is used as a shared object in signal handlers. ```c @@ -2598,7 +2743,8 @@ Accessing or modifying shared objects in signal handlers may cause inconsistent ## Do not use rand() to generate pseudorandom numbers for security purposes -**\[Description]** +**\[Description]** + The **rand()** function in the C language standard library generates pseudorandom numbers, which does not ensure the quality of the random sequence produced. In the C11 standard, the range of random numbers generated by the **rand()** function is `[0, RAND_MAX(0x7FFF)]`, which has a relatively short cycle, and the numbers can be predictable. Therefore, do not use the random numbers generated by the **rand()** function for security purposes. Use secure random number generation methods. Typical scenarios for security purposes include but are not limited to the following: @@ -2608,7 +2754,8 @@ Typical scenarios for security purposes include but are not limited to the follo - Generation of random numbers of verification codes; - Generation of random numbers for cryptographic algorithm purposes (for example, generating IVs, salt values, and keys). -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + The programmer wants the code to generate a unique HTTP session ID that is not predictable. However, the ID is a random number produced by calling the **rand()** function, and is predictable and has limited randomness. **\[Impact]** @@ -2617,12 +2764,14 @@ Using the **rand()** function may result in random numbers that are predictable. ## Do not output the address of an object or function in a released version -**\[Description]** +**\[Description]** + Do not output the address of an object or function in a released version. For example, do not output the address of a variable or function to a client, log, or serial port. Before launching an advanced attack, the attacker usually needs to obtain the memory address (such as the variable address and function address) of the target program and then modify the content of the specified memory for attacks. If the program itself outputs the addresses of objects or functions, the attacker can take this advantage and use these addresses and offsets to calculate the addresses of other objects or functions and launch attacks. In addition, the protection function of address space randomization also fails due to memory address leakage. -**\[Noncompliant Code Example]** +**\[Noncompliant Code Example]** + In the following code example, the address to which the pointer points is logged in the %p format. ```c @@ -2636,7 +2785,8 @@ int Encode(unsigned char *in, size_t inSize, unsigned char *out, size_t maxSize) Note: This example uses only the %p format for logging pointers. In scenarios where pointers are converted to integers and then logged, the same risk exists. -**\[Compliant Code Example]** +**\[Compliant Code Example]** + In the following code example, the code for logging the address is deleted. ```c @@ -2648,7 +2798,8 @@ int Encode(unsigned char *in, size_t inSize, unsigned char *out, size_t maxSize) } ``` -**\[Exception]** +**\[Exception]** + When the program crashes and exits, the memory address and other information can be output in the crash exception information. **\[Impact]** @@ -2667,7 +2818,7 @@ The public IP addresses built in open-source or third-party software must meet t **\[Exception]** -- This requirement is not mandatory when public network addresses must be specified as required by standard protocols. For example, an assembled public network URL must be specified for the namespace of functions based on the SOAP protocol. W3.org addresses on HTTP pages are also exceptions. +This requirement is not mandatory when public network addresses must be specified as required by standard protocols. For example, an assembled public network URL must be specified for the namespace of functions based on the SOAP protocol. W3.org addresses on HTTP pages are also exceptions. # Secure Kernel Coding @@ -2675,7 +2826,7 @@ The public IP addresses built in open-source or third-party software must meet t **\[Description]** -**Note:** In the mmap interface of the kernel, the **remap\_pfn\_range()** function is often used to map the physical memory of a device to a user process space. If the parameters (such as the mapping start address) are controlled by the user mode and no validation is performed, the user mode can read and write any kernel address through the mapping. An attacker can even construct arguments to run arbitrary code in the kernel. +In the mmap interface of the kernel, the **remap\_pfn\_range()** function is often used to map the physical memory of a device to a user process space. If the parameters (such as the mapping start address) are controlled by the user mode and no validation is performed, the user mode can read and write any kernel address through the mapping. An attacker can even construct arguments to run arbitrary code in the kernel. **\[Noncompliant Code Example]** @@ -2805,7 +2956,9 @@ ssize_t correct_write(struct file *file, const char __user *user_buf, size_t cou ## Verify the copy length of **copy\_from\_user()** to prevent buffer overflows -**Note:** The **copy\_from\_user()** function is used in kernel mode to copy data from the user mode. If the length of the copied data is not validated or is improperly validated, the kernel buffer overflows, causing kernel panic or privilege escalation. +**\[Description]** + +The **copy\_from\_user()** function is used in kernel mode to copy data from the user mode. If the length of the copied data is not validated or is improperly validated, the kernel buffer overflows, causing kernel panic or privilege escalation. **\[Noncompliant Code Example]** diff --git a/en/device-dev/faqs/faqs-building.md b/en/device-dev/faqs/faqs-building.md index 236765a6f7bf9bce448ba1c8ea243f50c9cb8159..b3cf127ee8c314633ed623fa273fd65974e95620 100644 --- a/en/device-dev/faqs/faqs-building.md +++ b/en/device-dev/faqs/faqs-building.md @@ -4,32 +4,29 @@ ## Mini and Small Systems -### "usr/sbin/ninja: invalid option -- w" Displayed During the Build Process +### "usr/sbin/ninja: invalid option -- w" - **Symptom** - - The compilation fails, and **usr/sbin/ninja: invalid option -- w** is displayed. + The build fails, and **usr/sbin/ninja: invalid option -- w** is displayed. - **Possible Causes** - The Ninja version in the compilation environment is outdated and does not support the --w option. + The Ninja version in use does not support the **--w** option. - **Solution** - - Uninstall Ninja and GN in the environment and reinstall them by following instructions in [Obtaining Tools](../get-code/gettools-ide.md). + Uninstall Ninja and GN, and [install Ninja and GN of the required version](../get-code/gettools-ide.md). -### "/usr/bin/ld: cannot find -lncurses" Displayed During the Build Process + +### "/usr/bin/ld: cannot find -lncurses" - **Symptom** - - The compilation fails, and **/usr/bin/ld: cannot find -lncurses** is displayed. + The build fails, and **/usr/bin/ld: cannot find -lncurses** is displayed. - **Possible Causes** - The ncurses library is not installed. - **Solution** @@ -39,17 +36,15 @@ ``` -### "line 77: mcopy: command not found" Displayed During the Build Process +### "line 77: mcopy: command not found" - **Symptom** - - The compilation fails, and **line 77: mcopy: command not found** is displayed. + The build fails, and **line 77: mcopy: command not found** is displayed. - **Possible Causes** - - Mcopy is not installed. + mcopy is not installed. - **Solution** @@ -58,65 +53,62 @@ ``` -### "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" Displayed During the Build Process +### "riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" - **Symptom** - - The compilation fails, and the following information is displayed: **riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory**. + The build fails, and the following information is displayed:
**riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory** - **Possible Causes** - - Permission is required to access files in the **riscv** compiler path. + You do not have the required permission to access files in the RISC-V compiler directory. - **Solution** - - 1. Run the following command to query the directory where **gcc_riscv32** is located: - - - ``` - which riscv32-unknown-elf-gcc - ``` + + 1. Run the following command to locate **gcc_riscv32**: + + ``` + which riscv32-unknown-elf-gcc + ``` + + 2. Run the **chmod** command to change the directory permission to **755**. -### "No module named 'Crypto'" Displayed During the Build Process +### "No module named 'Crypto'" - **Symptom** - - The compilation fails, and **No module named'Crypto loaded** is displayed. - + + The build fails, and **No module named 'Crypto'** is displayed. + - **Possible Causes** - + Crypto is not installed in Python3. - **Solution** 1. Run the following command to query the Python version: - + ``` python3 --version ``` 2. Ensure that Python 3.7 or later is installed, and then run the following command to install pycryptodome: - + ``` sudo pip3 install pycryptodome ``` -### "xx.sh : xx unexpected operator" Displayed During the Build Process +### "xx.sh: xx unexpected operator" - **Symptom** - - The compilation fails, and **xx.sh [: xx unexpected operator** is displayed. + The build fails, and **xx.sh [: xx unexpected operator** is displayed. - **Possible Causes** - - The compilation environment is shell instead of bash. + The build environment shell is not bash. - **Solution** @@ -126,20 +118,18 @@ ``` -### "Could not find a version that satisfies the requirement six>=1.9.0" Displayed During the Build Process +### "Could not find a version that satisfies the requirement six>=1.9.0" - **Symptom** - - - The following error occurs during compilation and building: + The following information is displayed during the build process: + ``` Could not find a version that satisfies the requirement six>=1.9.0 ``` - **Possible Causes** - **six** is not installed. @@ -149,88 +139,81 @@ Method 2: Install **six** offline. - Download the installation package from [PyPI](https://pypi.org/project/six/#files). - - ![en-us_image_0000001251276115](figures/en-us_image_0000001251276115.png) + 1. Download the installation package from [PyPI](https://pypi.org/project/six/#files). - Save the source code to the Linux server and run the **pip3 install six-1.14.0-py2.py3-none-any.whl** command to install **six**. - -After the preceding installation is complete, rebuild an environment. + + ![](figures/en-us_image_0000001251276115.png) + + 2. Save the source code to the Linux server and run the **pip3 install six-1.14.0-py2.py3-none-any.whl** command to install **six**. + + 3. Start the build again. -### "cannot find -lgcc" Displayed During the Build Process +### "cannot find -lgcc" - **Symptom** - - - The following error occurs during the build process: + The following information is displayed during the build process: + ``` riscv32-unknown-elf-ld: cannot find -lgcc ``` - **Possible Causes** - - - The gcc_riscv32 PATH is incorrect. There is an extra slash (/) after **bin**. + The gcc_riscv32 path is incorrectly set as follows. There is an extra slash (/) after **bin**. + ``` ~/gcc_riscv32/bin/:/data/toolchain/ ``` - **Solution** - - - Modify the PATH as follows: + Modify the gcc_riscv32 path as follows: + ``` ~/gcc_riscv32/bin:/data/toolchain/ ``` -### The Message Indicating Python Cannot Be Found Is Displayed During the Build Process +### Failed to Find Python - **Symptom** - - - The following error occurs during the build process: + The following information is displayed during the build process: + ``` -bash: /usr/bin/python: No such file or directory ``` - **Possible Cause 1** - Python is not installed. - **Solution** - - - Run the following command to install Python (Python 3.8 for example): + Run the following command to install Python. The following uses Python 3.8 as an example. + ``` sudo apt-get install python3.8 ``` - **Possible Cause 2** - - The soft link that points to the Python does not exist in the **usr/bin** directory. + The soft link to Python does not exist in the **usr/bin** directory. - ![en-us_image_0000001243200677](figures/en-us_image_0000001243200677.png) + ![](figures/en-us_image_0000001243200677.png) - **Solution** - - - Run the following commands to add a soft link: + Run the following commands to add the soft link to Python: + ``` # cd /usr/bin/ # which python3 @@ -238,28 +221,26 @@ After the preceding installation is complete, rebuild an environment. # python --version ``` -Example: + Example: - ![en-us_image_0000001243320787](figures/en-us_image_0000001243320787.png) + ![](figures/en-us_image_0000001243320787.png) -### The Message Indicating Python 3 Cannot Be Found Is Displayed During the Build Process +### Failed to Find Python3 - **Symptom** - ![en-us_image_0000001251276255](figures/en-us_image_0000001251276255.png) + ![](figures/en-us_image_0000001251276255.png) - **Possible Causes** - Python 3 is not installed. - **Solution** - Run the following command to install Python 3: - + ``` sudo apt-get install python3.8 ``` diff --git a/en/device-dev/faqs/faqs-overview.md b/en/device-dev/faqs/faqs-overview.md index 164025f20b6f15bcc50902e16905c7ed542cdb20..1f17c8564a85beeeaa4e695ef01a5f102ea7a070 100644 --- a/en/device-dev/faqs/faqs-overview.md +++ b/en/device-dev/faqs/faqs-overview.md @@ -4,26 +4,30 @@ FAQs are used to help developers solve problems frequently encountered during development. They cover a wide range of topics. -## Environment setup +## Environment Setup ### Mini and Small Systems -- [What should I do if garbled characters and segmentation faults occur during hb installation?](../faqs/faqs-environment-setup.md) +- hb installation -- [What should I do if the message "cannot import 'sysconfig' from 'distutils'" is displayed during hb installation?](../faqs/faqs-environment-setup.md) + - [What should I do if garbled characters and segmentation faults occur during hb installation?](../faqs/faqs-environment-setup.md) -- [What should I do if the message "module 'platform' has no attribute 'linux_distribution'" is displayed during hb installation?](../faqs/faqs-environment-setup.md) + - [What should I do if the message "cannot import 'sysconfig' from 'distutils'" is displayed during hb installation?](../faqs/faqs-environment-setup.md) -- [What should I do if the message "Could not find a version that satisfies the requirement ohos-build" is displayed during hb installation?](../faqs/faqs-environment-setup.md) + - [What should I do if the message "module 'platform' has no attribute 'linux_distribution'" is displayed during hb installation?](../faqs/faqs-environment-setup.md) -- [What should I do if the message "configure: error: no acceptable C compiler found in $PATH" is displayed during Python 3 installation?](../faqs/faqs-environment-setup.md) + - [What should I do if the message "Could not find a version that satisfies the requirement ohos-build" is displayed during hb installation?](../faqs/faqs-environment-setup.md) -- [What should I do if the message "-bash: make: command not found" is displayed during Python 3 installation?](../faqs/faqs-environment-setup.md) +- Python3 Installation -- [What should I do if the message "zlib not available" is displayed during Python 3 installation?](../faqs/faqs-environment-setup.md) + - [What should I do if the message "configure: error: no acceptable C compiler found in $PATH" is displayed during Python 3 installation?](../faqs/faqs-environment-setup.md) -- [What should I do if the message "No module named 'Crypto'" is displayed during the build process?](../faqs/faqs-environment-setup.md) + - [What should I do if the message "-bash: make: command not found" is displayed during Python 3 installation?](../faqs/faqs-environment-setup.md) + + - [What should I do if the message "zlib not available" is displayed during Python 3 installation?](../faqs/faqs-environment-setup.md) + + - [What should I do if the message "No module named 'Crypto'" is displayed during the build process?](../faqs/faqs-environment-setup.md) - [What should I do when an error with lsb_release occurs during kconfiglib installation?](../faqs/faqs-environment-setup.md) @@ -35,25 +39,25 @@ FAQs are used to help developers solve problems frequently encountered during de ### Mini and Small Systems -- ["usr/sbin/ninja: invalid option -- w" Displayed During the Build Process](../faqs/faqs-building.md) +- ["usr/sbin/ninja: invalid option -- w"](../faqs/faqs-building.md) -- ["/usr/bin/ld: cannot find -lncurses" Displayed During the Build Process](../faqs/faqs-building.md) +- ["/usr/bin/ld: cannot find -lncurses"](../faqs/faqs-building.md) -- ["line 77: mcopy: command not found" Displayed During the Build Process](../faqs/faqs-building.md) +- ["line 77: mcopy: command not found"](../faqs/faqs-building.md) -- ["riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory" Displayed During the Build Process](../faqs/faqs-building.md) +- ["riscv32-unknown-elf-gcc: error trying to exec 'cc1': execvp: No such file or directory"](../faqs/faqs-building.md) -- ["No module named 'Crypto'" Displayed During the Build Process](../faqs/faqs-building.md) +- ["No module named 'Crypto'"](../faqs/faqs-building.md) -- ["xx.sh : xx unexpected operator" Displayed During the Build Process](../faqs/faqs-building.md) +- ["xx.sh : xx unexpected operator"](../faqs/faqs-building.md) -- ["Could not find a version that satisfies the requirement six>=1.9.0" Displayed During the Build Process](../faqs/faqs-building.md) +- ["Could not find a version that satisfies the requirement six>=1.9.0"](../faqs/faqs-building.md) -- ["cannot find -lgcc" Displayed During the Build Process](../faqs/faqs-building.md) +- ["cannot find -lgcc"](../faqs/faqs-building.md) -- [The Message Indicating Python Cannot Be Found Is Displayed During the Build Process](../faqs/faqs-building.md) +- [Failed to Find Python](../faqs/faqs-building.md) -- [The Message Indicating Python 3 Cannot Be Found Is Displayed During the Build Process](../faqs/faqs-building.md) +- [Failed to Find Python 3](../faqs/faqs-building.md) ## Burning @@ -173,6 +177,6 @@ FAQs are used to help developers solve problems frequently encountered during de ### hdc -- [Why does hdc_std fail to connect to a device?](../faqs/faqs-system-applications.md) +- [hdc_std Failed to Connect to a Device](../faqs/faqs-system-applications.md) -- [hdc_std fail to run](../faqs/faqs-system-applications.md) +- [hdc_std Failed to Run](../faqs/faqs-system-applications.md) diff --git a/en/device-dev/faqs/faqs-system-applications.md b/en/device-dev/faqs/faqs-system-applications.md index b7c3bc6bdda88a16dac535768f306312bb372b99..0c4055683c6ca3d48a5b01d835727bff9dbe92b0 100644 --- a/en/device-dev/faqs/faqs-system-applications.md +++ b/en/device-dev/faqs/faqs-system-applications.md @@ -3,10 +3,10 @@ -## Utils FAQs +## Utils -### Failure in running the KV store on the LiteOS-A kernel (Hi3516 or Hi3518) due to incorrect path setting for the KV store +### Failed to Run a KV Store on LiteOS-A (Hi3516 or Hi3518) **Symptom** @@ -119,9 +119,10 @@ The component added to the **.hml** file cannot be displayed. **Solution** -(1) Check whether the width and height values are set explicitly. +1. Check whether the width and height values are set explicitly. + +2. Check whether the style of the component is set correctly. -(2) Check whether the style of the component is set correctly. ### How do I implement scrolling on a page? @@ -174,27 +175,29 @@ If the total length of child components, except for the first and last ones, is Do not include too many elements in an array. Avoid frequent operations on a large array. -## HDC FAQs +## hdc -### Why does hdc_std fail to connect to a device? +### hdc_std Failed to Connect to a Device - **Symptom** - -After the **hdc_std list targets** command is executed, **[Empty]** is displayed. + After the **hdc_std list targets** command is executed, **[Empty]** is displayed. - **Solution** 1. The device cannot be identified. + Check whether **HDC Device** exists under the **Universal Serial Bus controllers** in the **Device Manager**. If **HDC Device** does not exist, the device cannot be connected. In this case, disconnect and then reconnect the USB connection between the test PC and the OpenHarmony device, or burn the latest image. + 2. hdc_std works improperly. Run the **hdc kill** command to terminate the hdc_std process or run the **hdc start -r** command to restart the hdc service. Then, run the **hdc list targets** command to check whether device information can be obtained. + 3. hdc_std does not match the device. If the latest image is burnt on the device, the latest hdc_std version must be used. -### hdc_std fail to run +### hdc_std Failed to Run - **Symptom** diff --git a/en/device-dev/quick-start/quickstart-lite-env-setup.md b/en/device-dev/quick-start/quickstart-lite-env-setup.md index 931b2c740588c293f27b8bb59e8f0e113ec756fc..791b45375c14375295a1b903dac46d7b8082c613 100644 --- a/en/device-dev/quick-start/quickstart-lite-env-setup.md +++ b/en/device-dev/quick-start/quickstart-lite-env-setup.md @@ -21,7 +21,7 @@ On Ubuntu: 1. Run the following **apt-get** command: ``` - sudo apt-get update && sudo apt-get install binutils binutils-dev git git-lfs gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib gcc-arm-linux-gnueabi libc6-dev-i386 libc6-dev-amd64 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 bc gnutls-bin python3.8 python3-pip ruby genext2fs device-tree-compiler make libffi-dev e2fsprogs pkg-config perl openssl libssl-dev libelf-dev libdwarf-dev u-boot-tools mtd-utils cpio doxygen liblz4-tool openjdk-8-jre gcc g++ texinfo dosfstools mtools default-jre default-jdk libncurses5 apt-utils wget scons python3.8-distutils tar rsync git-core libxml2-dev lib32z-dev grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales + sudo apt-get update && sudo apt-get install binutils binutils-dev git git-lfs gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib gcc-arm-linux-gnueabi libc6-dev-i386 libc6-dev-amd64 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 bc gnutls-bin python3.8 python3-pip ruby genext2fs device-tree-compiler make libffi-dev e2fsprogs pkg-config perl openssl libssl-dev libelf-dev libdwarf-dev u-boot-tools mtd-utils cpio doxygen liblz4-tool openjdk-8-jre gcc g++ texinfo dosfstools mtools default-jre default-jdk libncurses5 apt-utils wget scons python3.8-distutils tar rsync git-core libxml2-dev lib32z-dev grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev ``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** @@ -29,9 +29,8 @@ On Ubuntu: > The preceding command is applicable to Ubuntu 18.04. For other Ubuntu versions, modify the preceding installation command based on the installation package name. Where: > > - Python 3.8 or a later version is required. This section uses Python 3.8 as an example. + > - Java 8 or later is required. This section uses Java 8 as an example. > -> - Java 8 or later is required. This section uses Java 8 as an example. - 2. Set Python 3.8 as the default Python version. Check the location of Python 3.8: @@ -80,19 +79,18 @@ To remotely access the Ubuntu environment through Windows to perform operations > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > - > If Visual Studio Code 1.62 or later has been installed, this step will be skipped. - - ![en-us_image_0000001237801283](figures/en-us_image_0000001237801283.png) - -2. On the displayed **Python select page**, select **Download from Huawei mirror** and click **Next**. + > If Visual Studio Code 1.62 or later has been installed, this step will be skipped. + + ![en-us_image_0000001237801283](figures/en-us_image_0000001237801283.png) + + 2. On the displayed **Python select page**, select **Download from Huawei mirror** and click **Next**. > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > > If Python 3.8 or 3.9 has been installed, select **Use one of compatible on your PC**. - - - ![en-us_image_0000001193983334](figures/en-us_image_0000001193983334.png) - + + ![en-us_image_0000001193983334](figures/en-us_image_0000001193983334.png) + 5. In the dialog box shown below, click **Next**. ![en-us_image_0000001259180828](figures/en-us_image_0000001259180828.png) @@ -112,8 +110,7 @@ To remotely access the Ubuntu environment through Windows to perform operations ### Installing DevEco Device Tool for Ubuntu -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** -> +> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> If the Ubuntu system has not been set up yet, set it up on a virtual machine running Windows. For details, see [Ubuntu Installation Guide](https://developer.huawei.com/consumer/cn/training/course/video/C101639987816176315). Then, [configure the Ubuntu basic environment](https://developer.huawei.com/consumer/cn/training/course/video/C101639988048536240). 1. Make sure the Ubuntu shell environment is **bash**. @@ -176,20 +173,20 @@ To remotely access the Ubuntu environment through Windows to perform operations > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > > If the command fails to be executed and the system displays a message indicating that the openssh-server and openssh-client depend on different versions, install the openssh-client of the required version (for example, **sudo apt-get install openssh-client=1:8.2p1-4**) as prompted on the command-line interface (CLI) and run the command again to install the openssh-server. - - - ``` - sudo apt-get install openssh-server - ``` - -2. Run the following command to start the SSH service: + + ``` + sudo apt-get install openssh-server + ``` + +2. Run the following command to start the SSH service: + ``` sudo systemctl start ssh ``` 3. Run the following command to obtain the IP address of the current user for remote access to the Ubuntu environment from Windows: - + ``` ifconfig ``` @@ -230,11 +227,11 @@ To remotely access the Ubuntu environment through Windows to perform operations > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > -> To eliminate the need for frequently entering the password for logging in to the remote computer, [set an SSH public key](https://device.harmonyos.com/cn/docs/documentation/guide/ide-registering-public-key-0000001247162706). - + > To eliminate the need for frequently entering the password for logging in to the remote computer, [set an SSH public key](https://device.harmonyos.com/cn/docs/documentation/guide/ide-registering-public-key-0000001247162706). + ![en-us_image_0000001215897530](figures/en-us_image_0000001215897530.png) - - After the connection is successful, the plug-in is automatically installed in the .vscode-server folder on the remote computer. After the installation is complete, reload Visual Studio Code in Windows as prompted. Then you can develop, compile, and burn source code in DevEco Device Tool on Windows. + +After the connection is successful, the plug-in is automatically installed in the **.vscode-server** folder on the remote computer. After the installation is complete, reload Visual Studio Code in Windows as prompted. Then you can develop, compile, and burn source code in DevEco Device Tool on Windows. ## Obtaining Source Code @@ -322,7 +319,7 @@ In the Ubuntu environment, perform the following steps to obtain the OpenHarmony ### Running prebuilts - Go to the root directory of the source code and run the following script to install the compiler and binary tool: +Go to the root directory of the source code and run the following script to install the compiler and binary tool: ``` bash build/prebuilts_download.sh @@ -387,9 +384,9 @@ Perform the following steps in Ubuntu: > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
> - Run the following command to uninstall hb: > -> ``` -> pip3 uninstall ohos-build -> ``` +> ``` +> pip3 uninstall ohos-build +> ``` > > - If any issue occurs during the hb installation, see [FAQs](../quick-start/quickstart-lite-faq-hb.md) to troubleshoot. @@ -397,8 +394,9 @@ Perform the following steps in Ubuntu: ### Installing LLVM (Only Required for OpenHarmony_v1.x) > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
+> > When downloading source code under the OpenHarmony_v1.x branches or tags, perform the operation procedure described in this section to install LLVM 12.0.1. -> +> > When downloading source code under the Master or non-OpenHarmony_v1.x branches or tags, skip this section. hb will automatically download the latest version of LLVM. 1. Start a Linux server. diff --git a/en/device-dev/quick-start/quickstart-standard-env-setup.md b/en/device-dev/quick-start/quickstart-standard-env-setup.md index fbff43368a500013b66281c314ca89d1fc97a37b..484d63eaaa9ee23d98650827649fb46f0912bdf5 100644 --- a/en/device-dev/quick-start/quickstart-standard-env-setup.md +++ b/en/device-dev/quick-start/quickstart-standard-env-setup.md @@ -21,7 +21,7 @@ On Ubuntu: 1. Run the following **apt-get** command: ``` - sudo apt-get update && sudo apt-get install binutils binutils-dev git git-lfs gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib gcc-arm-linux-gnueabi libc6-dev-i386 libc6-dev-amd64 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 bc gnutls-bin python3.8 python3-pip ruby genext2fs device-tree-compiler make libffi-dev e2fsprogs pkg-config perl openssl libssl-dev libelf-dev libdwarf-dev u-boot-tools mtd-utils cpio doxygen liblz4-tool openjdk-8-jre gcc g++ texinfo dosfstools mtools default-jre default-jdk libncurses5 apt-utils wget scons python3.8-distutils tar rsync git-core libxml2-dev lib32z-dev grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales + sudo apt-get update && sudo apt-get install binutils binutils-dev git git-lfs gnupg flex bison gperf build-essential zip curl zlib1g-dev gcc-multilib g++-multilib gcc-arm-linux-gnueabi libc6-dev-i386 libc6-dev-amd64 lib32ncurses5-dev x11proto-core-dev libx11-dev lib32z1-dev ccache libgl1-mesa-dev libxml2-utils xsltproc unzip m4 bc gnutls-bin python3.8 python3-pip ruby genext2fs device-tree-compiler make libffi-dev e2fsprogs pkg-config perl openssl libssl-dev libelf-dev libdwarf-dev u-boot-tools mtd-utils cpio doxygen liblz4-tool openjdk-8-jre gcc g++ texinfo dosfstools mtools default-jre default-jdk libncurses5 apt-utils wget scons python3.8-distutils tar rsync git-core libxml2-dev lib32z-dev grsync xxd libglib2.0-dev libpixman-1-dev kmod jfsutils reiserfsprogs xfsprogs squashfs-tools pcmciautils quota ppp libtinfo-dev libtinfo5 libncurses5-dev libncursesw5 libstdc++6 gcc-arm-none-eabi vim ssh locales libxinerama-dev libxcursor-dev libxrandr-dev libxi-dev ``` > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** @@ -29,9 +29,8 @@ On Ubuntu: > The preceding command is applicable to Ubuntu 18.04. For other Ubuntu versions, modify the preceding installation command based on the installation package name. Where: > > - Python 3.8 or a later version is required. This section uses Python 3.8 as an example. + > - Java 8 or later is required. This section uses Java 8 as an example. > -> - Java 8 or later is required. This section uses Java 8 as an example. - 2. Set Python 3.8 as the default Python version. Check the location of Python 3.8: @@ -88,7 +87,7 @@ To remotely access the Ubuntu environment through Windows to perform operations > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > - > If Python 3.8 or 3.9 has been installed, select **Use one of compatible on your PC**. + > If Python 3.8 or 3.9 has been installed, select **Use one of compatible on your PC**. ![en-us_image_0000001193983334](figures/en-us_image_0000001193983334.png) @@ -172,7 +171,7 @@ To remotely access the Ubuntu environment through Windows to perform operations 1. In Ubuntu, open the Terminal tool and run the following command to install the SSH service: - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> > If the command fails to be executed and the system displays a message indicating that the openssh-server and openssh-client depend on different versions, install the openssh-client of the required version (for example, **sudo apt-get install openssh-client=1:8.2p1-4**) as prompted on the command-line interface (CLI) and run the command again to install the openssh-server. @@ -227,7 +226,7 @@ To remotely access the Ubuntu environment through Windows to perform operations 5. In the displayed dialog box, select **Linux**, select **Continue**, and enter the password for logging in to the remote computer. - > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** + > ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
> > To eliminate the need for frequently entering the password for logging in to the remote computer, [set an SSH public key](https://device.harmonyos.com/cn/docs/documentation/guide/ide-registering-public-key-0000001247162706). @@ -321,7 +320,7 @@ In the Ubuntu environment, perform the following steps to obtain the OpenHarmony ### Running prebuilts - Go to the root directory of the source code and run the following script to install the compiler and binary tool: +Go to the root directory of the source code and run the following script to install the compiler and binary tool: ``` bash build/prebuilts_download.sh @@ -384,8 +383,8 @@ hb is a compilation tool of OpenHarmony. To install hb in Ubuntu, perform the fo > ![icon-notice.gif](public_sys-resources/icon-notice.gif) **NOTICE**
> - Run the following command to uninstall hb: > -> ``` -> pip3 uninstall ohos-build -> ``` +> ``` +> pip3 uninstall ohos-build +> ``` > > - If any issue occurs during the hb installation, see [FAQs](../quick-start/quickstart-standard-faq-hb.md) to troubleshoot. diff --git a/en/device-dev/security/security-guidelines-overall.md b/en/device-dev/security/security-guidelines-overall.md index 76dbd5a075069416b1cdae8ca97d76248b9bb8d1..8c551e4d29637b69eb9d81437eb5360e87bad324 100644 --- a/en/device-dev/security/security-guidelines-overall.md +++ b/en/device-dev/security/security-guidelines-overall.md @@ -1,256 +1,213 @@ -# Security Guidelines +# Security Guidelines -## Overview + +## Overview OpenHarmony is an open OS that allows you to easily develop services and applications. It provides an execution environment to ensure security of application data and user data. This environment combines chip security and system security features with upper-layer security services to secure hardware, the system, data, device interconnection, applications, and updates. -**Figure 1** Security assurance framework -![](figure/security-assurance-framework.png "security-assurance-framework") +**Figure 1** Security assurance + +![](figure/security-assurance-framework.png) -## Hardware Security -### Mechanism +## Hardware Security -- Boot root of trust - OpenHarmony devices use the public key infrastructure \(PKI\) to protect software integrity and ensure that the software source is valid and the software is not tampered with. +### Security Mechanism - In the device boot process, software signature verification is performed at each phase to form a secure boot chain. If signature verification fails at any phase, the device boot will be terminated. The hardware or software entity that initially performs signature verification in the secure boot chain is the boot root of trust. It must be valid and should not be tampered with. The boot root of trust can be a built-in code segment in the read-only memory \(ROM\). This code segment is written in the chip during the chip manufacturing and cannot be modified later. When the device is powered on and initialized, this code segment is executed first and used to verify software signatures. +- Boot root of trust + + OpenHarmony devices use the public key infrastructure (PKI) to protect software integrity and ensure that the software source is valid and the software is not tampered with. + + In the device boot process, software signature verification is performed at each phase to form a secure boot chain. If signature verification fails at any phase, the device boot will be terminated. The hardware or software entity that initially performs signature verification in the secure boot chain is the boot root of trust. It must be valid and should not be tampered with. The boot root of trust can be a built-in code segment in the read-only memory (ROM). This code segment is written in the chip during the chip manufacturing and cannot be modified later. When the device is powered on and initialized, this code segment is executed first and used to verify software signatures. + + When you use the code for signature verification, ensure the validity of the PKI public keys. OpenHarmony devices use a storage medium such as eFUSE and one-time password (OTP) to store the public keys (for example, their hash values) and guarantee their validity. A public key is usually programed into the eFuse or OTP of a device during device manufacturing. +- Hardware-isolated trusted environment + + The hardware-isolated trusted environment complies with the design concept of the trusted computing system. There is a clear boundary between the trusted environment and untrusted one. OpenHarmony devices protect core sensitive data in the trusted environment. Even if OS vulnerabilities in the untrusted environment are exploited, sensitive data in the trusted environment is secure. + + The trusted environment of OpenHarmony devices is built based on a hardware security isolation mechanism. The chip isolation mechanism varies slightly on different OpenHarmony devices, and the most common mechanism is Arm TrustZone. On some RISC-V chip platforms, independent security cores may also be used to build a trusted environment. + + A specific, simplified OS iTrustee lite runs in the trusted environment to manage resources and schedule tasks in the environment and provide security services for OpenHarmony devices. Key management and data security are the most common security services in the trusted environment. A device has a unique hardware root key in the eFuse/OTP. Based on this root key and service context, the trusted environment generates multiple keys that provide key management and data encryption/decryption services for applications. During their whole lifecycle, core keys of devices stay in the trusted environment. The trusted environment also provides security services such as identity authentication, system status monitoring, and secure data storage to enhance device security. +- Hardware key engine + + Cryptography is the basis of information security. Data encryption/decryption requires high efficiency and security of computing devices. Hardware encryption/decryption technologies use computer hardware to assist or even replace software to encrypt or decrypt data. Hardware-based encryption/decryption is more efficient and secure than software-based encryption/decryption. + + Since some dedicated hardware resources are used for data encryption/decryption, the CPU can concurrently execute other computing tasks, which greatly improves performance and reduces the CPU load. In addition, a well-designed hardware key engine protects keys from leak even if the software is cracked and even defends against electromagnetic and radiation attacks from physical channels. + + OpenHarmony devices support the hardware key engine, which allows OpenHarmony to perform computing tasks such as data encryption and decryption, certificate signature verification, and hash value calculation. The hardware key engine supports popular algorithms such as Advanced Encryption Standard (AES) and Rivest-Shamir-Adleman (RSA). - When you use the code for signature verification, ensure the validity of the PKI public keys. OpenHarmony devices use a storage medium such as eFUSE and one-time password \(OTP\) to store the public keys \(for example, their hash values\) and guarantee their validity. A public key is usually programed into the eFuse or OTP of a device during device manufacturing. +### Recommended Practices -- Hardware-isolated trusted environment +- The boot root of trust consists of a built-in code segment in the chip and the root key of the device. The root of trust is written into the chip during manufacturing and cannot be modified in the device lifecycle. It is used to verify software certificates in the device boot process. The root key is the public key matching the private key of the device certificate signature. The private key is maintained on the PKI signature server and the public key is written to the device. To prevent attackers from tampering with the public key to bypass signature authentication, you can write the public key to media such as fuses on OpenHarmony devices. Considering that the fuse space is limited, you can store only the hash value of the public key in the fuse and verify the validity of the public key using the boot code. - The hardware-isolated trusted environment complies with the design concept of the trusted computing system. There is a clear boundary between the trusted environment and untrusted one. OpenHarmony devices protect core sensitive data in the trusted environment. Even if OS vulnerabilities in the untrusted environment are exploited, sensitive data in the trusted environment is secure. +- Generally, a trusted execution environment (TEE) is built based on the Arm TrustZone technology, and can also adopt other isolation mechanisms, such as TrustZone-M and independent security cores, depending on the device form. A TEE OS must be deployed in the TEE to manage resources and schedule tasks. OpenHarmony provides iTrustee as the TEE OS. You can develop and deploy security services based on iTrustee. + Not all OpenHarmony devices need to support the TEE, for example, some devices with thin resources that run less sensitive services may not need the TEE. You can choose whether to support the TEE and how to implement the TEE based on service requirements. - The trusted environment of OpenHarmony devices is built based on a hardware security isolation mechanism. The chip isolation mechanism varies slightly on different OpenHarmony devices, and the most common mechanism is Arm TrustZone. On some RISC-V chip platforms, independent security cores may also be used to build a trusted environment. +- The hardware key engine must provide key algorithms related to true random numbers, public keys, symmetric keys, and hash values. By deploying required drivers in OpenHarmony, you can provide unified key management and key algorithms for applications. - A specific, simplified OS iTrustee lite runs in the trusted environment to manage resources and schedule tasks in the environment and provide security services for OpenHarmony devices. Key management and data security are the most common security services in the trusted environment. A device has a unique hardware root key in the eFuse/OTP. Based on this root key and service context, the trusted environment generates multiple keys that provide key management and data encryption/decryption services for applications. During their whole lifecycle, core keys of devices stay in the trusted environment. The trusted environment also provides security services such as identity authentication, system status monitoring, and secure data storage to enhance device security. -- Hardware key engine +## System Security - Cryptography is the basis of information security. Data encryption/decryption requires high efficiency and security of computing devices. Hardware encryption/decryption technologies use computer hardware to assist or even replace software to encrypt or decrypt data. Hardware-based encryption/decryption is more efficient and secure than software-based encryption/decryption. - Since some dedicated hardware resources are used for data encryption/decryption, the CPU can concurrently execute other computing tasks, which greatly improves performance and reduces the CPU load. In addition, a well-designed hardware key engine protects keys from leak even if the software is cracked and even defends against electromagnetic and radiation attacks from physical channels. +### Security Mechanism - OpenHarmony devices support the hardware key engine, which allows OpenHarmony to perform computing tasks such as data encryption and decryption, certificate signature verification, and hash value calculation. The hardware key engine supports popular algorithms such as Advanced Encryption Standard \(AES\) and Rivest-Shamir-Adleman \(RSA\). +For device with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recommended. It provides the following features: +- Process isolation -### Recommended Practices + Process isolation prevents processes from reading and writing memory data of each other. Generally, virtual address space mapping is used for process isolation. The virtual addresses of two processes are mapped to physical address segments using the memory management unit (MMU). In this way, the non-shared memory data that can be accessed by one of the two processes through the virtual address is inaccessible to the other process. -- The boot root of trust consists of a built-in code segment in the chip and the root key of the device. The root of trust is written into the chip during manufacturing and cannot be modified in the device lifecycle. It is used to verify software certificates in the device boot process. The root key is the public key matching the private key of the device certificate signature. The private key is maintained on the PKI signature server and the public key is written to the device. To prevent attackers from tampering with the public key to bypass signature authentication, you can write the public key to media such as fuses on OpenHarmony devices. Considering that the fuse space is limited, you can store only the hash value of the public key in the fuse and verify the validity of the public key using the boot code. -- Generally, a trusted execution environment \(TEE\) is built based on the Arm TrustZone technology, and can also adopt other isolation mechanisms, such as TrustZone-M and independent security cores, depending on the device form. A TEE OS must be deployed in the TEE to manage resources and schedule tasks. OpenHarmony provides iTrustee as the TEE OS. You can develop and deploy security services based on iTrustee. + Due to limited resources, OpenHarmony adopts different mechanisms for kernel-level and user-level processes. All kernel-level processes share the same VMM space, that is, kernel-level processes are not isolated from each other. When the OS is booted, two basic kernel-level processes KProcess and KIdle are created. KProcess is the root process of kernel-level process, and KIdle is the subprocess of KProcess. Each user-level process has its own VMM space that is invisible to other processes, and user-level processes are isolated from each other. - Not all OpenHarmony devices need to support the TEE, for example, some devices with thin resources that run less sensitive services may not need the TEE. You can choose whether to support the TEE and how to implement the TEE based on service requirements. +- DAC -- The hardware key engine must provide key algorithms related to true random numbers, public keys, symmetric keys, and hash values. By deploying required drivers in OpenHarmony, you can provide unified key management and key algorithms for applications. + Discretionary access control (DAC) means that the file owner determines access permissions of other roles. There are three granularities of permission control: user, group, and other (UGO). The file owner can classify any user into one of the three dimensions and adopt a control policy to perform DAC permission verification. -## System Security + DAC depends on the attributes of processes, such as the UID and GID, which are used as feature IDs during file creation and access. When creating a file, the creator writes its UID into the file. When a file is accessed, the UID is used for classifying the file. -### Mechanism + Each application has a UID. When creating a file, an application adds its UID to the metadata of the file and sets permissions of the user, group, and other. When an application tries to access the file, the UID and permissions in the metadata of the file are used to verify the application UID. -For devices with 128 KB to 128 MB of memory, the OpenHarmony lite kernel is recommended. It provides the following features: + The following figure shows how DAC works when a process accesses a file. The DAC first matches the process UID with the file UID, and then the process GID with the file GID. If the UID and GID both fail to match, DAC checks the **other** attribute of the file to determine whether the process is allowed to read, write, or execute the file. In addition, the system supports a privileged capability that is not subject to DAC mechanism (read, write, and execute) and can access files directly. Services with high permissions (such as system services) can manage files of applications with low permissions (such as third-party applications). -- Process isolation +**Figure 2** How DAC works - Process isolation prevents processes from reading and writing memory data of each other. Generally, virtual address space mapping is used for process isolation. The virtual addresses of two processes are mapped to physical address segments using the memory management unit \(MMU\). In this way, the non-shared memory data that can be accessed by one of the two processes through the virtual address is inaccessible to the other process. +![](figure/how-dac-works.png) - Due to limited resources, OpenHarmony adopts different mechanisms for kernel-level and user-level processes. All kernel-level processes share the same VMM space, that is, kernel-level processes are not isolated from each other. When the OS is booted, two basic kernel-level processes KProcess and KIdle are created. KProcess is the root process of kernel-level process, and KIdle is the subprocess of KProcess. Each user-level process has its own VMM space that is invisible to other processes, and user-level processes are isolated from each other. +- Capability mechanism -- Discretionary access control + The capability mechanism is a subdivision of the root permission. A multi-user computer system usually has a special role that has all system permissions, that is, the system administrator with the root permission. OpenHarmony needs to support kernels of the third-party application ecosystem, and privileged access to the system must be controlled. The system needs to restrict privileged system calls made by users to access the kernel. Only some applications with high-level permissions are allowed to perform privileged operations. To be specific, the kernel spawns the first user program INIT that has all privileged permissions. Then INIT starts other application framework services and retains only privileged permissions necessary for each application. When an application requests to call a privileged API, the kernel checks whether the application has the permission to access the API based on the process ID. - Discretionary access control \(DAC\) means that the file owner determines access permissions of other roles. There are three granularities of permission control: user, group, and other \(UGO\). The file owner can classify any user into one of the three dimensions and adopt a control policy to perform DAC permission verification. +- Secure boot - DAC depends on the attributes of processes, such as the UID and GID, which are used as feature IDs during file creation and access. When creating a file, the creator writes its UID into the file. When a file is accessed, the UID is used for classifying the file. + Secure boot is the basis of system security. A digital signature and integrity verification mechanism is used to verify the integrity and validity of software at each layer, starting from the boot root of trust in the chip. This ensures that a correct and valid OS is booted, preventing attackers from tampering with or implanting system software and providing a secure, basic running environment. - Each application has a UID. When creating a file, an application adds its UID to the metadata of the file and sets permissions of the user, group, and other. When an application tries to access the file, the UID and permissions in the metadata of the file are used to verify the application UID. + The chip does not need to be verified after it is powered on because the on-chip ROM code cannot be modified. The on-chip ROM verifies the bootloader based on the public key hash value which is calculated using the asymmetric algorithm in eFuse. The verification is performed based on the hardware trust root and is fully trusted. The bootloader that passes this verification is deemed to be trusted for subsequent use. This is the process of constructing a trust chain. Bootloader initializes the execution environment, including initializing the double data rate (DDR) and reading and writing the flash memory, to prepare for loading modules and executing more complex logic. After the bootloader is initialized, it verifies the integrity of the X.509 certificate and verifies image packages (**kernel.bin**, **teeOS.bin**, and **rootfs.bin**) using the public key of the X.509 certificate. - The following figure shows how DAC works when a process accesses a file. The DAC first matches the process UID with the file UID, and then the process GID with the file GID. If the UID and GID both fail to match, DAC checks the **other** attribute of the file to determine whether the process is allowed to read, write, or execute the file. In addition, the system supports a privileged capability that is not subject to DAC mechanism \(read, write, and execute\) and can access files directly. Services with high permissions \(such as system services\) can manage files of applications with low permissions \(such as third-party applications\). - **Figure 2** How DAC works - ![](figure/how-dac-works.png "how-dac-works") +### Recommended Practices -- Capability mechanism +- DAC and the capability mechanism are used to control who can access resources. It is recommended that the minimum permissions are granted. - The capability mechanism is a subdivision of the root permission. A multi-user computer system usually has a special role that has all system permissions, that is, the system administrator with the root permission. OpenHarmony needs to support kernels of the third-party application ecosystem, and privileged access to the system must be controlled. The system needs to restrict privileged system calls made by users to access the kernel. Only some applications with high-level permissions are allowed to perform privileged operations. To be specific, the kernel spawns the first user program INIT that has all privileged permissions. Then INIT starts other application framework services and retains only privileged permissions necessary for each application. When an application requests to call a privileged API, the kernel checks whether the application has the permission to access the API based on the process ID. +- Secure boot must be enabled, and the trusted root must be in the chip and cannot be modified. In addition, you must consider the impact of secure upgrade (if available) on secure boot, that is, the signature or hash value of an image file must be updated after a secure upgrade. -- Secure boot - Secure boot is the basis of system security. A digital signature and integrity verification mechanism is used to verify the integrity and validity of software at each layer, starting from the boot root of trust in the chip. This ensures that a correct and valid OS is booted, preventing attackers from tampering with or implanting system software and providing a secure, basic running environment. +## Data security - The chip does not need to be verified after it is powered on because the on-chip ROM code cannot be modified. The on-chip ROM verifies the bootloader based on the public key hash value which is calculated using the asymmetric algorithm in eFuse. The verification is performed based on the hardware trust root and is fully trusted. The bootloader that passes this verification is deemed to be trusted for subsequent use. This is the process of constructing a trust chain. Bootloader initializes the execution environment, including initializing the double data rate \(DDR\) and reading and writing the flash memory, to prepare for loading modules and executing more complex logic. After the bootloader is initialized, it verifies the integrity of the X.509 certificate and verifies image packages \(**kernel.bin**, **teeOS.bin**, and **rootfs.bin**\) using the public key of the X.509 certificate. +### Security Mechanism -### Recommended Practices +OpenHarmony Universal KeyStore (HUKS) provides key and certificate management. For OpenHarmony, it mainly provides key management for HiChain (device identity authentication platform). The figure below shows the HUKS functions. -- DAC and the capability mechanism are used to control who can access resources. It is recommended that the minimum permissions are granted. -- Secure boot must be enabled, and the trusted root must be in the chip and cannot be modified. In addition, you must consider the impact of secure upgrade \(if available\) on secure boot, that is, the signature or hash value of an image file must be updated after a secure upgrade. +**Figure 3** HUKS functions -## Data Security +![](figure/huks-functions.png) -### Mechanism +The following algorithms are supported: -OpenHarmony Universal Keystore Service \(HUKS\) provides key and certificate management. For OpenHarmony, it mainly provides key management for HiChain \(the device identity authentication platform\). The following figure shows the functions of HUKS +- Authentication and encryption: AES-128/192/256-GCM -**Figure 3** HUKS functions -![](figure/huks-functions.png "huks-functions") +- Signing and signature verification: ED25519 -The following algorithms are supported: +- Key agreement: X25519 + +- Message authentication: HMAC-SHA-256/HMAC-SHA-256 + +- Data digest: SHA-256/SHA-512 -- Authentication and encryption: AES-128/192/256-GCM -- Signature verification: ED25519 -- Key negotiation: X25519 -- Message authentication: HMAC-SHA256/512 -- Data digest: SHA256/512 HUKS has the following restrictions: -- Secure storage of keys: Keys must be stored in a secure area and cannot be modified. When factory settings are restored, preset keys are not deleted. -- Key access security: OpenHarmony stores different data of an application separately to implement data isolation in the application, and includes the UID and process ID in the parameter structure to implement data isolation between different applications. -- Concurrent access is not supported, that is, multiple applications cannot invoke HUKS simultaneously. As HUKS is a single library, resource exclusion is not a concern. If multiple applications need to use HUKS, each of them needs to connect to a HUKS library and pass a path for storing data. Data is stored in the directory of each application. -### Recommended Practices +- Secure storage of keys + + Keys must be stored in a secure area and cannot be modified. When factory settings are restored, preset keys are not deleted. + +- Key access security + + OpenHarmony stores data of different applications in different locations to isolate data. The parameter structures must contain the UID and process ID to implement data isolation of different applications. + +- Concurrent access + + HUKS is only a library and does not support concurrent access from multiple applications. If multiple applications need to access HUKS, each application must connect to a HUKS library and pass a path for storing data. Data is stored in the directory of each application. + + +### Recommended Practices To use the device certification function, it is recommended that you use HiChain to interconnect with HUKS. HUKS provides applications such as HiChain with key generation, import, export, encryption/decryption, storage, and destruction, certificate import and query, and secret information storage. -## Device Interconnection Security -To transmit user data securely between devices, ensure that the devices are trusted by each other. A trust relationship and a secure data transmission channel must be established between the devices. This section describes how an IoT controller and IoT device establish a trust relationship. The following figure shows how an IoT controller and an IoT device establish a trust relationship. +## Device Interconnection Security + +To ensure secure transmit of user data between devices, a trust relationship and a secure data transmission channel must be established between the devices. The figure below illustrates how an IoT controller and an IoT device establish a trust relationship. + +**Figure 4** Process of establishing a trust relationship between devices + +![](figure/how-an-iot-controller-and-an-iot-device-establish-a-trust-relationship.png) + + +- IoT device interconnection security + + A trust relationship can be established between an IoT device that runs OpenHarmony (such as an AI speaker, smart home device, and wearable) and an IoT controller. Encrypted user data is transmitted between the IoT device and IoT controller through a secure connection. + + +- IoT service identifier of the IoT controller + + An IoT controller generates different identifiers for different IoT device management services to isolate these services. The identifier can be used for authentication and communication between an IoT controller and an IoT device. It is an Ed25519 public/private key pair generated using the elliptic curve cryptography. + + +- IoT device identifier + + An IoT device can generate its own device identifier for communicating with the IoT controller. It is also an Ed25519 public/private key pair generated using elliptic curve cryptography, with the private key stored on the IoT device. Each time the device is restored to factory settings, the public/private key pair will be reset. + + The identifier can be used for secure communication between the IoT controller and IoT device. After the devices exchange the service identifier or device identifier, they can negotiate the key and establish a secure communication channel. + + +- P2P trusted binding between devices + + When an IoT controller and an IoT device establish a trust relationship, they exchange identifiers. + + During this process, the user needs to enter or scan the PIN provided by the IoT device on the IoT controller. PIN is either dynamically generated if the IoT device has a screen, or preset by the manufacturer if it does not have a screen. A PIN can be a number or a QR code. Then the IoT controller and IoT device perform authentication and session key exchange based on password authenticated key exchange (PAKE), and use the session key to encrypt the channel for exchanging identity public keys. + + +- Secure communication between the IoT controller and IoT device + + When an IoT controller and an IoT device communicate with each other after establishing a trust relationship, they authenticate each other by using the locally stored identity public key of the peer. Bidirectional identity authentication and session key exchange are performed using the Station-to-Station (STS) protocol during each communication. The session key is used to encrypt the data transmission channel between the devices. + + +## Application Security -**Figure 4** How an IoT controller and an IoT device establish a trust relationship -![](figure/how-an-iot-controller-and-an-iot-device-establish-a-trust-relationship.png "how-an-iot-controller-and-an-iot-device-establish-a-trust-relationship") -- **IoT device interconnection security** +### Security Mechanism - A trust relationship can be established between an IoT device that runs OpenHarmony \(such as an AI speaker, smart home device, and wearable\) and an IoT controller. Encrypted user data is transmitted between the IoT device and IoT controller through a secure connection. +- Application signature management + + After developing and debugging an OpenHarmony application, sign the application installation package using a private key, which matches a public key. Generally, the OEM generates a public/private key pair, presets the public key in the device, and stores the private key on a local server that is not connected to the Internet to prevent private key leakage. After you finish developing an application, you can use an external device (such as a USB flash drive) to upload the installation package to the server where the private key is stored, calculate the signature, and download the signature to the external device. During application installation, the hash value of the bundle is calculated using the SHA-256 algorithm. The hash value, together with the signature and preset public key, is used for authentication. The application can be installed only after the authentication is successful. + + In addition, the application source must be verified to ensure that the application is from a valid developer. As a developer, you must apply for a development certificate and use it to sign the application you have developed. During application installation, the upper-level certificate stored on the device is used to verify the signature to ensure validity of the developer. +- Application permission control + + OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an application, you need to declare the sensitive permissions that the application may require in the **profile.json** file. The permissions can be static or dynamic. Static permissions need to be registered during application installation, and dynamic permissions can be obtained only upon user authorization. Authorization modes include system settings, manual authorization by applications, and others. In addition, application signature control is used to ensure that the application installation package has been confirmed by the device vendor. -- **IoT service identifier of the IoT controller** + **Table 1** OpenHarmony system permissions - An IoT controller generates different identifiers for different IoT device management services to isolate these services. The identifier can be used for authentication and communication between an IoT controller and an IoT device. It is an Ed25519 public/private key pair generated using the elliptic curve cryptography. +| Permission| **Authorization Mode**| **Description**| +| -------- | -------- | -------- | +| ohos.permission.LISTEN_BUNDLE_CHANGE | system_grant (static permission)| Allows an application to listen for application changes.| +| ohos.permission.GET_BUNDLE_INFO | system_grant (static permission)| Allows an application to obtain information about other applications.| +| ohos.permission.INSTALL_BUNDLE | system_grant (static permission)| Allows an application to install other applications.| +| ohos.permission.CAMERA | user_grant (dynamic permission)| Allows an application to use the camera to take photos and record videos at any time.| +| ohos.permission.MODIFY_AUDIO_SETTINGS | system_grant (static permission)| Allows an application to modify global audio settings, such as the volume and speaker for output.| +| ohos.permission.READ_MEDIA | user_grant (dynamic permission)| Allows an application to read users' favorite videos.| +| ohos.permission.MICROPHONE | user_grant (dynamic permission)| Allows an application to use the microphone for audio recording at any time.| +| ohos.permission.WRITE_MEDIA | user_grant (dynamic permission)| Allows an application to write users' favorite music.| +| ohos.permission.DISTRIBUTED_DATASYNC | user_grant (dynamic permission)| Allows an application to manage distributed data transmission.| +| ohos.permission.DISTRIBUTED_VIRTUALDEVICE | user_grant (dynamic permission)| Allows an application to use distributed virtualization features.| -- **IoT device identifier** - - An IoT device can generate its own device identifier for communicating with the IoT controller. It is also an Ed25519 public/private key pair generated using elliptic curve cryptography, with the private key stored on the IoT device. Each time the device is restored to factory settings, the public/private key pair will be reset. - - The identifier can be used for secure communication between the IoT controller and IoT device. After the devices exchange the service identifier or device identifier, they can negotiate the key and establish a secure communication channel. - - -- **P2P trusted binding between devices** - - When an IoT controller and an IOT device establish a trust relationship, they exchange identifiers. - - During this process, the user needs to enter or scan the PIN provided by the IoT device on the IoT controller. PIN is either dynamically generated if the IoT device has a screen, or preset by the manufacturer if it does not have a screen. A PIN can be a number or a QR code. Then the IoT controller and IoT device perform authentication and session key exchange based on password authenticated key exchange \(PAKE\), and use the session key to encrypt the channel for exchanging identity public keys. - - -- **Secure communication between the IoT controller and IoT device** - - When an IoT controller and an IoT device communicate with each other after establishing a trust relationship, they authenticate each other by using the locally stored identity public key of the peer. Bidirectional identity authentication and session key exchange are performed using the Station-to-Station \(STS\) protocol during each communication. The session key is used to encrypt the data transmission channel between the devices. - - -## Application Security - -### Mechanism - -- Application signature management - - After developing and debugging an OpenHarmony application, sign the application installation package using a private key, which matches a public key. Generally, the OEM generates a public/private key pair, presets the public key in the device, and stores the private key on a local server that is not connected to the Internet to prevent private key leakage. After you finish developing an application, you can use an external device \(such as a USB flash drive\) to upload the installation package to the server where the private key is stored, calculate the signature, and download the signature to the external device. During application installation, the hash value of the bundle is calculated using the SHA-256 algorithm. The hash value, together with the signature and preset public key, is used for authentication. The application can be installed only after the authentication is successful. - - In addition, the application source must be verified to ensure that the application is from a valid developer. As a developer, you must apply for a development certificate and use it to sign the application you have developed. During application installation, the upper-level certificate stored on the device is used to verify the signature to ensure validity of the developer. - -- Application permission control - - OpenHarmony allows users to install third-party applications and controls calls made by third-party applications to sensitive permissions. When developing an application, you need to declare the sensitive permissions that the application may invoke in the **profile.json** file. The permissions include static and dynamic ones. Static permissions need to be registered during application installation, and dynamic permissions can be invoked only upon user authorization. Authorization modes include system settings, manual authorization by applications, and others. In addition, application signature control is used to ensure that the application installation package has been confirmed by the device vendor. - - **Table 1** OpenHarmony system permissions - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

OpenHarmony System Permission

-

Authorization Mode

-

Description

-

ohos.permission.LISTEN_BUNDLE_CHANGE

-

system_grant (static permission)

-

Allows an application to listen for application changes.

-

ohos.permission.GET_BUNDLE_INFO

-

system_grant (static permission)

-

Allows an application to obtain application information.

-

ohos.permission.INSTALL_BUNDLE

-

system_grant (static permission)

-

Allows an application to install applications.

-

ohos.permission.CAMERA

-

user_grant (dynamic permission)

-

Allows an application to use the camera to take photos and record videos at any time.

-

ohos.permission.MODIFY_AUDIO_SETTINGS

-

system_grant (static permission)

-

Allows an application to modify global audio settings, such as the volume and speaker for output.

-

ohos.permission.READ_MEDIA

-

user_grant (dynamic permission)

-

Allows an application to read users' favorite videos.

-

ohos.permission.MICROPHONE

-

user_grant (dynamic permission)

-

Allows an application to use the microphone for audio recording at any time.

-

ohos.permission.WRITE_MEDIA

-

user_grant (dynamic permission)

-

Allows an application to write users' favorite music.

-

ohos.permission.DISTRIBUTED_DATASYNC

-

user_grant (dynamic permission)

-

Allows an application to manage distributed data transmission.

-

ohos.permission.DISTRIBUTED_VIRTUALDEVICE

-

user_grant (dynamic permission)

-

Allows an application to use distributed virtualization features.

-
- - -### Recommended Practices - -When developing an application, determine what permissions your application needs and register the permissions in the **profile.json** file. Sign the application to ensure that the devices on which the application will be installed can verify its integrity and source. +### Recommended Practices +When developing an application, determine the permissions required by your application and register the permissions in the **profile.json** file. Sign the application to ensure that the devices on which the application will be installed can verify its integrity and source. diff --git a/en/device-dev/subsystems/subsys-toolchain-hdc-guide.md b/en/device-dev/subsystems/subsys-toolchain-hdc-guide.md index 42071761d52c4ee442f3ef2b0800ffc5e3998fe1..6a911f7a29b1e21fb73b2c14ed770f32bccb0331 100644 --- a/en/device-dev/subsystems/subsys-toolchain-hdc-guide.md +++ b/en/device-dev/subsystems/subsys-toolchain-hdc-guide.md @@ -1,351 +1,581 @@ -# hdc\_std +# hdc_std -hdc\_std \(OpenHarmony Device Connector\) is a command line tool provided by OpenHarmony for debugging. With this tool, you can interact with real devices or simulators from a Windows or Linux OS. -This section describes how to set up the hdc\_std environment and use its common commands. +OpenHarmony Device Connector (hdc_std) is a command-line tool used for debugging. You can use it on a Windows, Linux, or macOS system to interact with real devices or simulators. -## Preparations -**Obtaining hdc\_std:** +The following describes how to obtain and use hdc_std. -Obtain **hdc\_std** from the **prebuilt** directory at [developtools\_hdc\_standard](https://gitee.com/openharmony/developtools_hdc_standard). -**Example:** +## How to Obtain -To obtain hdc\_std on Windows, obtain the executable file **hdc\_std.exe** from **prebuilt/windows** and place it in a directory on the disk. +Obtain hdc_std from the **toolchains** directory of the OpenHarmony SDK. -## Important Notes +**Example** -- If an exception occurs when you are using hdc\_std, run the **hdc\_std kill** command to kill the hdc\_std service or run the **hdc\_std start -r** command to restart the service process. -- If no device information is obtained after **hdc\_std list targets** is executed, use the task manager to check whether the **hdc.exe** process exists. If it exists, kill the process. +If you use hdc_std on Windows, obtain the SDK for Windows and copy **hdc_std.exe** from **toolchains** to a directory on the disk. -## Option-related Commands -The following commands are available: - -### -h/help -v/version - -Obtains hdc help and version information. - -**Table 1** Command description - - | Return Value | Description | - | -------- | -------- | - | Required information | hdc help or version information. | +## NOTICE -Examples: +- If an exception occurs when you are using hdc_std, run the **hdc_std kill** command to terminate the hdc_std service or run the **hdc_std start -r** command to restart the service process. -hdc\_std -h / hdc\_std help +- If no device information is obtained after **hdc_std list targets** is executed, check whether the hdc_std process exists in the **Task Manager**. If yes, terminate it. -hdc\_std -v / hdc\_std version -### -t key +## Option-related Commands -Connects to a device with a specified key. +The following commands are available: -**Table 2** Command description - | Parameter | Description | +- **-h/help -v/version** + + Displays hdc_std help or version information. + + **Table 1** Command description + | **Return Value**| **Description**| | -------- | -------- | - | key | Key that identifies the device. The value is in the *IP address:Port* format or is a USB serial number. | - | **Return Value** | **Description** | - | 1. error: device '***' not found
2. Nothing to do... | 1. The device does not exist
2. The command appended to **-t key** does not exist. | - -Examples: - -This option must be used together with a specific operation command. The following uses the shell command as an example: - -**hdc\_std list targets** \(obtain device information\) - -**hdc\_std -t _key_ shell** \(replace _key_ with the device information obtained\) - ->![](../public_sys-resources/icon-note.gif) **NOTE**
->You can connect to multiple devices from the device you use for development. Each device has a unique key. The key can be _IP address:Port number_ for a device connected through a network or the serial number for a device connected through USB. - -## Querying the Device List - -The following command is used to query the device list: - -### list targets\[-v\] - -Displays all the connected devices. - -**Table 3** Command description - -| Parameter | Description | -| -------- | -------- | -| -v | Prints detailed device information. | -| **Return Value** | **Description** | -| 1. Device information
2. [Empty] | 1. A list of connected devices.
2. No device information is found. | - -Examples: - -hdc\_std list targets + | Required information| hdc_std help or version information.| + + Example: + + ``` + hdc_std -h / hdc_std help + ``` + + ``` + hdc_std -v / hdc_std version + ``` + + + +- **-l 0-5** + + Sets the levels of the logs generated during the running of the tool. The default value is **LOG_INFO**. + + **Table 2** Command description + + | Parameter| Description| + | -------- | -------- | + | 0 | LOG_OFF | + | 1 | LOG_FATAL| + | 2 | LOG_WARN | + | 3 | LOG_INFO | + | 4 | LOG_DEBUG| + | 5 | LOG_ALL | + + Example: + + ``` + hdc_std -l5 start + ``` + +- **-t key** + + Connects to a device based on the specified key. + + **Table 3** Command description + + | Parameter| Description| + | -------- | -------- | + | key | Key that identifies the device to connect. The value can be in the *IP address:port number* format or be a USB serial number.| + | **Return Value** | **Description** | + | 1. error: device '\*\*\*' not found
2. Nothing to do ..| 1. The device does not exist.
2. The command appended to **-t key** does not exist.| -hdc\_std list targets -v + Example: -## Service Process Commands + **-t key** must be used with a command. The following uses **shell** as an example: -The following commands are available: + **hdc_std list targets** (obtain device information) -### target mount + **hdc_std -t *key* shell** (replace *key* with the device identifier obtained) -Mounts a partition, such as **/system**, with the read and write permissions. + > **NOTE**
+ > You can connect to multiple devices from the device you use for development. Each device has a unique key. The key can be *IP address:port number* for a device to be connected over the network or the serial number for a device to be connected through USB. A specific command must be used with this command. -**Table 4** Command description +- **checkserver** + + Obtains the client and server version information. + + **Table 4** Command description - | Parameter | Description | + | Return Value| Description| | -------- | -------- | - | None | None | - | **Return Value** | **Description** | - | 1. Mount finish
2. Returned information | 1. Information returned when the operation is successful.
2. Information returned when the operation fails. | + | Client version: server version: | Client and server version information.| -Example: - -hdc\_std target mount - -### smode \[off\] + Example: -Grants the root permission to a background service process. The **off** option is used to revoke the granted permission. + ``` + hdc_std checkserver + ``` -Examples: -hdc\_std smode +## Displaying Device Information -hdc\_std smode off +Run the following command to display all connected devices: -### kill \[-r\] -Stops a service process. +``` +list targets[-v] +``` **Table 5** Command description - | Parameter | Description | - | -------- | -------- | - | -r | Triggers the service restart. | - | **Return Value** | **Description** | - | 1. Kill server finish
2. Error information | 1. Information returned when the operation is successful.
2. The operation fails. | - -Example: - -hdc\_std kill +| Parameter| Description| +| -------- | -------- | +| -v | Displays detailed device information.| +| **Return Value** | **Description**| +| 1. Device information
2. [Empty]| 1. A list of connected devices.
2. No device information is found.| -### start \[-r\] -Starts a service process. +Example: -**Table 6** Command description +``` +hdc_std list targets +``` - | Parameter | Description | - | -------- | -------- | - | -r | Restarts the service process if it has started. | - | **Return Value** | **Description** | - | None | None | +``` +hdc_std list targets -v +``` -Examples: -hdc\_std start - -## Network Commands +## Service Process Commands The following commands are available: -### tconn _host_\[:_port_\]\[-remove\] +- **target mount** -Connects to a device with a specified IP address and port number. + Mounts the **/system** partition in read/write mode. -**Table 7** Command description + **Table 6** Command description - | Parameter | Description | + | Parameter| Description| | -------- | -------- | - | host[:port] | IP address and port number of the device to be connected. | - | -remove | Disconnects from the specified device. | - | **Return Value** | **Description** | - | 1. Error information
2. None | 1. The operation fails.
2. The operation is successful. | - -Example: - -hdc\_std tconn 192.168.0.100:8710 - -### tmode usb - -Restarts the daemon process and connects to the device using USB. - -**Table 8** Command description - - | Parameter | Description | + | –| –| + | **Return Value**| **Description**| + | 1. Mount finish
2. Error information| 1. The operation is successful.
2. The operation fails.| + + Example: + + ``` + hdc_std target mount + ``` + + + + +- **target boot** + + Boots the device. + + Example: + + ``` + hdc_std target boot + ``` + + + +- **smode [-r]** + + Grants the **root** permission to the background hdc service. Use **off** to revoke the granted permissions. + + Example: + + ``` + hdc_std smode + ``` + + ``` + hdc_std smode -r + ``` + + + +- **kill [-r]** + + Terminates the hdc process. + + **Table 7** Command description + + | Parameter| Description| | -------- | -------- | - | None | None | - | **Return Value** | **Description** | - | 1. Error information
2. None | 1. The operation fails.
2. The operation is successful. | + | -r | Restarts the hdc process.| + | **Return Value**| **Description**| + | 1. Kill server finish
2. Error information| 1. The operation is successful.
2. The operation fails.| -Example: + Example: -hdc\_std tmode usb + ``` + hdc_std kill + ``` -### tmode port _port-number_ +- **start [-r]** + + Starts the hdc process. + + **Table 8** Command description -Restarts the daemon process and connects to the device over TCP. + | Parameter| Description| + | -------- | -------- | + | -r | Restarts the hdc process if it has started.| + | **Return Value**| **Description**| + | –| –| -**Table 9** Command description + Example: - | Parameter | Description | - | -------- | -------- | - | port-number | Port number used to connect to the device. | - | **Return Value** | **Description** | - | 1. Error information
2. None | 1. The operation fails.
2. The operation is successful. | + ``` + hdc_std start + ``` -Example: -hdc\_std tmode port 8710 ->![](../public_sys-resources/icon-note.gif) **NOTE**
->After this command is executed, the remote daemon process exits and restarts, and the TCP connection is enabled by default. If you do not include **port-number** in this command, a random port will be used to connect to the device. -## File Commands +## Network Commands The following commands are available: -### file send _local remote_ - -Sends a file to a remote device. - -**Table 10** Command description - | Parameter | Description | - | -------- | -------- | - | local | Path of the file to send. | - | remote | Destination path on the remote device. | - | **Return Value** | **Description** | - | 1. Error information
2. File transfer result | 1. The operation fails.
2. The operation is successful. | - -Example: - -hdc\_std file send E:\\a.txt /data/local/tmp/a.txt +- **tconn host[:port][-remove]** -### file recv \[-a\] _remote local_ + Connects to a device with the specified IP address and port number. -Receives a file from a remote device. + **Table 9** Command description -**Table 11** Command description - - | Parameter | Description | + | Parameter| Description| | -------- | -------- | - | -a | File retention timestamp mode. | - | local | Path on the local device to receive the file. | - | remote | File path on the remote device. | - | **Return Value** | **Description** | - | 1. Error information
2. None | 1. The operation fails.
2. The operation is successful. | - -Example: - -hdc\_std file recv /data/local/tmp/a.txt ./a.txt - -## App Commands + | host[:port] | IP address and port number for the device to connect.| + | -remove | Disconnects from the specified device.| + | **Return Value**| **Description**| + | 1. Error information
2. –| 1. The operation fails.
2. The operation is successful.| + + Example: + + ``` + hdc_std tconn 192.168.0.100:8710 + ``` + + + +- **tmode usb** + + Restarts the daemon process and connects to the device using USB preferentially. + + **Table 10** Command description + + | Parameter| Description| + | -------- | -------- | + | –| –| + | **Return Value**| **Description**| + | 1. Error information
2. –| 1. The operation fails.
2. The operation is successful.| + + Example: + + ``` + hdc_std tmode usb + ``` + + + +- **tmode port port-number** + + Restarts the daemon process and connects to the device over TCP preferentially. If the TCP connection fails, a USB connection will be initiated. + + **Table 11** Command description + + | Parameter| Description| + | -------- | -------- | + | port-number | Port used to connect to the device.| + | **Return Value**| **Description**| + | 1. Error information
2. –| 1. The operation fails.
2. The operation is successful.| + + Example: + + ``` + hdc_std tmode port 8710 + ``` + + + + > **NOTE**
+ > After this command is executed, the remote daemon process exits and restarts, and a TCP connection is set up by default. If the port number is not specified in the command, a random port will be used to connect to the device. + +- **fport localnode remotenode** + + Forwards data from a host port to a device port. + + Example: + + ``` + hdc_std fport tcp:1234 tcp:1080 + ``` + + + +- **rport remotenode localnode** + + Forwards data from a device port to a host port. + + Example: + + ``` + hdc_std rport tcp:2080 tcp:2345 + ``` + + + +- **fport ls** + + Lists all port forwarding tasks. + + **Table 12** Command description + + | Parameter| Description| + | -------- | -------- | + | –| –| + | **Return Value**| **Description**| + | 'tcp:1234 tcp:1080' [Forward] | Forward port forwarding task.| + | 'tcp:2080 tcp:2345' [Reverse] | Reverse port forwarding task.| + + Example: + + ``` + hdc_std fport ls + ``` + + + +- **fport rm** + + Deletes a port forwarding task. + + Example: + + ``` + hdc_std fport rm tcp:1234 tcp:1080 + ``` + + + + +## File Commands The following commands are available: -### install \[-r/-d/-g\] _package_ - -Installs the OpenHarmony application. -**Table 12** Command description +- **file send local remote** + + Sends a file to a remote device. + + **Table 13** Command description - | Parameter | Description | + | Parameter| Description| | -------- | -------- | - | package | OpenHarmony application installation package. | - | -r | Replaces an existing application. | - | -d | Allows downgraded installation. | - | -g | Grants permission dynamically. | - | **Return Value** | **Description** | - | 1. Error information
2. None | 1. The operation fails.
2. The operation is successful. | + | local | Path of the file to send.| + | remote | Destination path on the remote device.| + | **Return Value**| **Description**| + | 1. Error information
2. File transfer result| 1. The operation fails.
2. The operation is successful.| + + Example: + + ``` + hdc_std file send E:\a.txt /data/local/tmp/a.txt + ``` + + + +- **file recv [-a] remote local** + + Receives a file from a remote device. + + **Table 14** Command description + + | Parameter| Description| + | -------- | -------- | + | -a | Retains the file timestamp.| + | local | Destination path on the local device.| + | remote | File path on the remote device.| + | **Return Value**| **Description**| + | 1. Error information
2. –| 1. The operation fails.
2. The operation is successful.| -Example: + Example: + + ``` + hdc_std file recv /data/local/tmp/a.txt ./a.txt + ``` + + -hdc\_std install _hwadmin.hap_ -### uninstall \[-k\] _package_ +## App Commands -Uninstalls the OpenHarmony application. +The following commands are available: -**Table 13** Command description - | Parameter | Description | +- **install [-r/-d/-g]** *package* + + Installs an OpenHarmony app. + + **Table 15** Command description + | Parameter| Description| | -------- | -------- | - | package | OpenHarmony application installation package. | - | -k | Retains **/data/cache**. | - | **Return Value** | **Description** | - | 1. Error information
2. None | 1. The operation fails.
2. The operation is successful. | + | package | OpenHarmony app installation package.| + | -r | Replaces the existing app.| + | -d | Allows downgrade installation.| + | -g | Grants permissions dynamically.| + | **Return Value**| **Description**| + | 1. Error information
2. –| 1. The operation fails.
2. The operation is successful.| + + Example: + + ``` + hdc_std install hwadmin.hap + ``` + + + +- **uninstall [-k] package** + + Uninstalls an OpenHarmony app. + + **Table 16** Command description + + | Parameter| Description| + | -------- | -------- | + | package | OpenHarmony app installation package.| + | -k | Retains **/data/cache**.| + | **Return Value**| **Description**| + | 1. Error information
2. –| 1. The operation fails.
2. The operation is successful.| -Example: + Example: + + ``` + hdc_std uninstall package + ``` + + -hdc\_std uninstall _package_ -## Debugging Commands +## Debugging Commands The following commands are available: -### hilog -Obtains logs for debugging. +- **hilog** -**Table 14** Command description + Obtains logs for debugging. - | Parameter | Description | - | -------- | -------- | - | None | None | - | **Return Value** | **Description** | - | Returned information | Obtained logs. | + **Table 17** Command description -Example: - -hdc\_std hilog + | Parameter| Description| + | -------- | -------- | + | –| –| + | **Return Value**| **Description**| + | Log obtained| Log information obtained.| + + Example: Obtain log information. + + ``` + hdc_std hilog + ``` + + Clear the cached logs. + + ``` + hdc_std shell "hilog -r" + ``` + + ​ + +- **shell** [*command*] + + Executes a command remotely or enters an interactive command environment. + + **Table 18** Command description + + | Parameter| Description| + | -------- | -------- | + | command | Command to execute.| + | **Return Value**| **Description**| + | Returned information| Command execution result.| -### shell \[_command_\] + Example: + + ``` + hdc_std shell + ``` + + -Executes a command remotely or enters an interactive command environment. +- **jpid** + + Obtains the list of processes that can be debugged. + + Example: + + ``` + hdc_std jpid + ``` + + -**Table 15** Command description - | Parameter | Description | - | -------- | -------- | - | command | Command to be executed. | - | **Return Value** | **Description** | - | Returned information | Execution result of the command. | +## FAQs -Examples: -hdc\_std shell +### Failed to Connect to a Device from hdc_std -## Troubleshooting +- **Symptom** + + After the **hdc_std list targets** command is executed, **[Empty]** is displayed. -### hdc\_std Fails to Connect to a Device +- **Solution** + + - The device cannot be identified. + + Check whether **HDC Device** exists under the **Universal Serial Bus controllers** in the **Device Manager**. If **HDC Device** does not exist, the device cannot be connected. In this case, disconnect and then reconnect the USB connection between the test PC and the OpenHarmony device, or burn the latest image. + + - hdc_std works improperly. + + Run the **hdc kill** command to terminate the hdc_std process or run the **hdc start -r** command to restart the hdc service. Then, run the **hdc list targets** command to check whether device information can be obtained. + + - hdc_std does not match the device. + + If the latest image is burnt on the device, the latest hdc_std version must be used. -- **Symptom** - **\[Empty\]** is displayed in the output after the **hdc\_std list targets** command is executed. +### hdc_std Fails to Run -- **Solutions** - 1. The device cannot be identified. +- **Symptom** + + After you click **hdc_std.exe**, the file fails to execute. + +- **Solution** + + **hdc_std.exe** requires no installation. You can use it after placing it to a local directory or adding the tool path to environment variables. Run the **cmd** command and then run the **hdc_std** command to start the tool. - Check whether **HDC Device** exists in the universal serial bus device of the device manager. If **HDC Device** does not exist, the device cannot be connected. In this case, remove and then insert the device or burn the latest image for the device. - 2. hdc\_std works improperly. - Run the **hdc kill** or **hdc start -r** command to kill or restart the hdc service. Then, run the **hdc list targets** command to check whether device information can be obtained. +### Accessing a Server from the Client - 3. hdc\_std does not match the device. +1. Run the **kill** command to stop the local server. - If the latest image is burnt on the device, the latest hdc\_std version must be used. As hdc\_std is updated continuously, obtain hdc\_std of the latest version from the **developtools\_hdc\_standard** repository in the **prebuilt** directory. +2. Run the **-s [ip:]port -m** command to start the remote server. + Example: + ``` + hdc_std -s severIP:8710 -m + ``` -## hdc\_std Fails to Run + -- **Symptom** +3. Run **-s [ip:]port** *command* to execute a command on the remote server. - The **hdc\_std.exe** file does not run after being clicked. + Example: -- **Solutions** + ``` + hdc_std -s severIP:8710 list targets + ``` - **hdc\_std.exe** requires no installation. It can be directly used on a disk or added to environment variables. Open the cmd window and run the **hdc\_std** command to use **hdc\_std.exe**. + diff --git a/en/readme/ARK-Runtime-Subsystem.md b/en/readme/ARK-Runtime-Subsystem.md index 020694b57b8d27850bba5a3517f86893cbb40a7b..d9349e7305c8b4203ea62faf005b116e59607f71 100644 --- a/en/readme/ARK-Runtime-Subsystem.md +++ b/en/readme/ARK-Runtime-Subsystem.md @@ -6,13 +6,13 @@ ArkCompiler is a built-in componentized and configurable multi-language compilat ArkCompiler JS Runtime consists of two parts: JS compiler toolchain and JS runtime. The JS compiler toolchain compiles JS source code into ArkCompiler bytecodes. The JS runtime executes the generated ArkCompiler bytecodes. Unless otherwise specified, bytecodes refer to ArkCompiler bytecodes in this document. -Figure 1 Architecture of the JS compiler toolchain +**Figure 1** Architecture of the JS compiler toolchain ![](figures/en-us_image_ark_frontend.png) The source code compiler of ArkCompiler JS Runtime receives JS source code, based on which ts2abc generates an abc file. -Figure 2 Architecture of ArkCompiler JS Runtime +**Figure 2** Architecture of ArkCompiler JS Runtime ![](figures/en-us_image_ark-js-arch.png) @@ -63,19 +63,19 @@ ArkCompiler JS Runtime consists of four subsystems: ``` /ark -├── js_runtime # JS runtime module -├── runtime_core # Runtime core subsystem -└── ts2abc # JS frontend tool +├── ets_runtime # JS runtime module +├── runtime_core # Runtime core subsystem +└── ets_frontend # JS frontend tool ``` -## Usage Guideline +## Usage [Ark Runtime User Guide](https://gitee.com/openharmony/ark_js_runtime/blob/master/docs/ARK-Runtime-Usage-Guide.md) ## Repositories Involved -[ark\_runtime\_core](https://gitee.com/openharmony/ark_runtime_core) +[arkcompiler\_runtime\_core](https://gitee.com/openharmony/arkcompiler_runtime_core) -[ark\_js\_runtime](https://gitee.com/openharmony/ark_js_runtime) +[arkcompiler\_ets\_runtime](https://gitee.com/openharmony/arkcompiler_ets_runtime) -[ark\_ts2abc](https://gitee.com/openharmony/ark_ts2abc) +[arkcompiler\_ets\_frontend](https://gitee.com/openharmony/arkcompiler_ets_frontend) diff --git a/en/readme/SAMGR.md b/en/readme/SAMGR.md index 63a09944e4a8595c1644cbab4fd4214b13604b7d..55adbfac5bad3eff550bb8644ebd97fbc60b0a5a 100644 --- a/en/readme/SAMGR.md +++ b/en/readme/SAMGR.md @@ -1,28 +1,47 @@ -# System Ability Manager +# System Ability Manager -## Introduction +## Introduction -The System Ability Manager (SAMGR) subsystem implements the system service framework. It provides the functions of starting, registering, and querying system services, and querying cross-device distributed system services. +The System Ability Manager (SAMGR) subsystem provides APIs for starting, registering, and querying system abilities, and querying distributed system abilities. +## System Architecture -## System Architecture +The figure below shows the SAMGR architecture. -**Figure 1** SAMGR architecture +**Figure 1** SAMGR architecture ![](figures/samgr-architecture.png) -## Directory Structure +The SAMGR subsystem consists of the following modules: + +- safwk + + The **safwk** module defines how to implement system abilities in OpenHarmony and provides APIs to start and register system abilities. + +- samgr + + The **samgr** module provides APIs to start, register, and query OpenHarmony system abilities. + +- safwk_lite + + The **safwk_lite** module implements the lightweight foundation process, which provides an empty process for running basic abilities. + +- samgr_lite + + The **samgr_lite** module provides APIs for registering and discovering abilities of the mini system. + +## Directory Structure ``` /foundation/systemabilitymgr ├── safwk # System ability framework ├── samgr # System ability manager ├── safwk_lite # Lightweight foundation process -└── samgr_lite # Lightweight system ability manager +├── samgr_lite # Lightweight system ability manager ``` -## Repositories Involved +## Repositories Involved **SAMGR** diff --git a/en/readme/arkui.md b/en/readme/arkui.md new file mode 100644 index 0000000000000000000000000000000000000000..b4c8f0ef37ae2c3d86d30eb68284f53f73ca1472 --- /dev/null +++ b/en/readme/arkui.md @@ -0,0 +1,33 @@ +# ArkUI + +## Introduction + +ArkUI is a UI development framework that provides what you'll need to develop application UIs in OpenHarmony, including UI components, animations, drawing, interaction events, and JavaScript API extension mechanisms. ArkUI comes with two development paradigms: eTS-based declarative development paradigm (declarative development paradigm for short) and JavaScript-compatible web-like development paradigm (web-like development paradigm for short). + +**Framework Structure** + +![en-us_image_0000001267647869](../application-dev/ui/figures/en-us_image_0000001267647869.png) + +As shown above, the two development paradigms share the UI backend engine and language runtime. The UI backend engine implements the six basic capabilities of ArkUI. The declarative development paradigm does not require the JS Framework for managing the page DOM. As such, it has more streamlined rendering and update links and less memory usage. This makes the declarative development paradigm a better choice for building application UIs. + + +## Directory Structure + +The ArkUI source code is stored in **/foundation/arkui**. The following shows the directory structure. + +``` +/foundation/arkui +├── ace_engine # ArkUI +├── ace_engine_lite # Lite ArkUI +└── napi # JS APIs for extending the native development module +``` + +## Repositories Involved + +**ArkUI** + +[arkui\_ace\_engine](https://gitee.com/openharmony/arkui_ace_engine) + +[arkui\_ace\_engine\_lite](https://gitee.com/openharmony/arkui_ace_engine_lite) + +[arkui\_napi](https://gitee.com/openharmony/arkui_napi) diff --git a/en/readme/distributed-data-management.md b/en/readme/distributed-data-management.md index 052d68b7385ac608ce9c683649e44eba193b6c60..ef0edbcf9a426b7a59a1eb0f60caa6940bf65a77 100644 --- a/en/readme/distributed-data-management.md +++ b/en/readme/distributed-data-management.md @@ -1,99 +1,84 @@ -# Distributed Data Management +# Distributed Data Management -## Introduction -The Distributed Data Management subsystem can persistently store various structured data of a single device and also supports data synchronization and sharing across devices. In this regard, you can seamlessly integrate distributed application data among different devices, ensuring consistent user experience in the same application across these devices. +## Introduction -- Local data management +**Distributed Data Management Subsystem** - This module allows you to store and access structured data on a single device. It uses the SQLite engine to provide the relational database \(RDB\) and preferences database. With these databases, you can persistently store and access app data using different models. +The Distributed Data Management subsystem can persistently store various structured data of a single device and also supports data synchronization and sharing across devices. With the Distributed Data Management subsystem, application data can be seamlessly processed across different devices, ensuring consistent user experience for the same application across devices. -- Distributed data service +**Subsystem Architecture** - This service can synchronize data across devices, so that users can access consistent data on different devices. DDS isolates data based on a triplet of the account, app, and database. DDS synchronizes data between trusted devices to provide the cross-device data access capability. +**Figure 1** Architecture -## Architecture +![](figures/Distributed_data_management_architecture.png) -**Figure 1** Architecture of the Distributed Data Management subsystem +## Directory Structure - -![](figures/en-us_image_0000001115748088.png) - -## Directory Structure - -Level 1 and 2 directories of the distributed data management subsystem are as follows: +Level 1 and 2 directories of the distributed data management subsystem: ``` -distributeddatamgr/ # Distributed data management -├── appdatamgr # Local data management -└── distributeddatamgr # Distributed Data Service +distributeddatamgr/ # Distributed Data Management subsystem +├── data_object # Distributed data object +└── data_share # DataShare +└── datamgr_service # Data service +└── kv_store # Key-value (KV) store +└── preferences # Preferences +└── relational_store # Relational database (RDB) store third_party/ # Open-source software -├── flatbuffers # flatbuffers code +├── flatbuffers # FlatBuffers code └── sqlite # SQLite code ``` -## Usage - -### Local Data Management - -- Relational database \(RDB\) - - Some basic concepts are as follows: +## Module Description - - **RDB** +### Distributed Data Object - A database created on the basis of relational models. The RDB stores data in rows and columns. +The distributed data object management framework is an object-oriented in-memory data management framework. It provides APIs for basic data object management, such as creating, querying, deleting, modifying, and subscribing to in-memory objects. Moreover, it provides distributed capabilities to implement data object collaboration for the same application between multiple devices that form a Super Device. - - **Result set** +The **Distributed Data Object** module provides JS APIs to help you use distributed data objects like using local data objects. The distributed data objects support basic data types, such as number, string, and Boolean, as well as complex data types, such as array and nested basic types. - A set of query results used to access data. You can access the required data in a result set in flexible modes. +### DataShare - - **SQLite database** +The **DataShare** module allows an application to manage its own data and share data with other applications. Currently, data can be shared only between applications on the same device. - A lightweight RDB in compliance with the atomicity, consistency, isolation, and durability \(ACID\) properties. It is an open-source database. +### DDS +The Distributed Data Service (DDS) implements distributed database collaboration across devices for applications. The DDS isolates data based on a triplet of the account, application, and database. The DDS synchronizes data between trusted devices to provide users with consistent data access experience on different devices. -- Preferences database +### Preferences - Some basic concepts are as follows: +The **Preferences** module allows quick access to data in KV pairs and storage of a small amount of data for local applications. The data is stored in local files and loaded in memory, which allows faster access and higher processing efficiency. Preferences provide non-relational data storage and are not suitable for storing a large amount of data. - - **Key-value database** +1. The **Preferences** module provides APIs for **preferences** operations. +2. You can use **getPreferences()** to load the content of a specified file to a **Preferences** instance. Each file has only one **Preferences** instance. The system stores the instance data in memory through a static container until the app removes the instance from the memory or deletes the file. +3. After obtaining a **Preferences** instance, the app can call the APIs in **Preferences** to read data from or write data to the **Preferences** instance, and call **flush()** to save the instance data to a file. - A database that stores data in key-value pairs. The **key** indicates keyword, and **value** indicates the corresponding value. +### RDB Store - - **Non-relational database** +The RDB manages data based on relational models. The OpenHarmony RDB module provides a complete mechanism for managing local databases based on the underlying SQLite. - A database not in compliance with the atomicity, consistency, isolation, and durability \(ACID\) database management properties of relational data transactions. Instead, the data in a non-relational database is independent and scalable. +With the SQLite as the persistence engine, the RDB module supports all SQLite features, including transactions, indexes, views, triggers, foreign keys, parameterized queries, prepared SQL statements, and more. - - **Preference** **data** - A type of data that is frequently accessed and used. +## Repositories Involved +Distributed Data Management Subsystem -### Distributed Data Service +[distributeddatamgr\_data_object](https://gitee.com/openharmony/distributeddatamgr_data_object) -DDS provides apps with the capability to store data in the databases of different devices. It uses the KV data model. +[distributeddatamgr\_data_share](https://gitee.com/openharmony/distributeddatamgr_data_share) -- **KV data model** +[distributeddatamgr\_preferences](https://gitee.com/openharmony/distributeddatamgr_preferences) - KV is short for key-value. The KV database is a type of NoSQL database. Data in this type of database is organized, indexed, and stored in the form of key-value pairs. +[distributeddatamgr\_relational_store](https://gitee.com/openharmony/distributeddatamgr_relational_store) - The KV data model is suitable for storing service data that does not involve too many data or service relationships. It provides better read and write performance than the SQL database. The KV data model is widely used in distributed scenarios because it handles conflict more easily in database version compatibility and data synchronization. The distributed database is based on the KV data model and provides KV-based access interfaces. - - -## Repositories Involved - -Distributed Data Management subsystem - -[distributeddatamgr\_appdatamgr](https://gitee.com/openharmony/distributeddatamgr_appdatamgr) - -[distributeddatamgr\_distributeddatamgr](https://gitee.com/openharmony/distributeddatamgr_datamgr) +[distributeddatamgr\_kv_store](https://gitee.com/openharmony/distributeddatamgr_kv_store) [third\_party\_sqlite](https://gitee.com/openharmony/third_party_sqlite) [third\_party\_flatbuffers](https://gitee.com/openharmony/third_party_flatbuffers) - diff --git a/en/readme/figures/Distributed_data_management_architecture.png b/en/readme/figures/Distributed_data_management_architecture.png new file mode 100644 index 0000000000000000000000000000000000000000..e0c551c9fd35cbfdfce4b9f1936a29f537fdde8d Binary files /dev/null and b/en/readme/figures/Distributed_data_management_architecture.png differ diff --git a/en/readme/figures/en-us_image_0000001115748088.png b/en/readme/figures/en-us_image_0000001115748088.png deleted file mode 100644 index 450e1fd449945553559a9b9e45b0967d7c629f66..0000000000000000000000000000000000000000 Binary files a/en/readme/figures/en-us_image_0000001115748088.png and /dev/null differ diff --git a/en/readme/figures/samgr-architecture.png b/en/readme/figures/samgr-architecture.png index 826d579fdce32aa57080e14141153f7dda7035f7..dff7311e2ed3576ce10d14d9d49269d8649a53f2 100644 Binary files a/en/readme/figures/samgr-architecture.png and b/en/readme/figures/samgr-architecture.png differ diff --git a/en/readme/js-ui-framework.md b/en/readme/js-ui-framework.md deleted file mode 100644 index ae54562dc451846835bbf37aef62c945a018a1c9..0000000000000000000000000000000000000000 --- a/en/readme/js-ui-framework.md +++ /dev/null @@ -1,115 +0,0 @@ -# JS UI Framework - -## Introduction - -The OpenHarmony JS UI framework provides basic, container, and canvas UI components and standard CSS animation capabilities. It supports the web-development-like programming paradigm. - -- **Web-development-like paradigm** - - The JS UI framework supports languages that are similar to those for web development, such as HTML and CSS. You can use them to describe the page layout and style, and use JavaScript \(conforming to the ECMAScript specification\) for page behavior. This paradigm allows you to avoid code for UI state switching. The view configuration information is intuitive. - - -**Figure 1** JS UI framework - - -![](figures/en-us_image_0000001077953992.png) - -The JS UI framework consists of the application, framework, engine, and porting layers. - -- **Application** - - Contains applications with Feature Abilities \(FAs\) developed with the JS UI framework. The FA application in this document refers to the application with FAs developed using JavaScript. - -- **Framework** - - Parses UI pages and provides the Model-View-ViewModel \(MVVM\), page routing, custom components and more for front end development. - -- **Engine** - - Accomplishes animation parsing, Document Object Model \(DOM\) building, layout computing, rendering command–based building and drawing, and event management. - -- **Porting Layer** - - Abstracts the platform layer to provide interfaces for the interconnection with the OS. For example, interconnections of events, rendering pipelines, and lifecycles. - - -## Directory Structure - -The source code of the framework is stored in **/foundation/ace**. The following shows the directory structure. - -``` -/foundation/ace -├── ace_engine # JS UI framework -├── ace_engine_lite # JS UI framework for the mini system and above -└── napi # JS APIs for extending the native development module -``` - -## Usage - -- JavaScript FA development directory - -After a project is created, its **js** directory is displayed. - -**Figure 2** Development directory -![](figures/development-directory.png "development-directory") - -The **i18n** directory stores JSON files for various locales. A **pages** subfolder contains multiple pages and each consists of **.hml**, **.css**, and **.js** files. - -- **main \> js \> default \> i18n \> en-US.json**: defines the variables displayed on pages in English. Similarly, **zh-CN.json** defines the page content in Chinese. - - ``` - { - "strings": { - "hello": "Hello", - "world": "World" - } - } - ``` - -- **main \> js \> default \> pages \> index \> index.hml**: describes the layout of the **index** page, components used on the page, and the hierarchy of these components. For example, there is a text component for displaying **Hello World**. - - ``` -
- - {{ $t('strings.hello') }} {{title}} - -
- ``` - -- **main \> js \> default \> pages \> index \> index.css**: defines the style of the **index** page. For example, the following **index.css** code snippet describes how **container** and **title** will be displayed on the page: - - ``` - .container { - flex-direction: column; - justify-content: center; - align-items: center; - } - .title { - font-size: 100px; - } - ``` - -- **main \> js \> default \> pages \> index \> index.js**: defines the service logic on the **index** page, such as data binding and event processing. In this example, the string **World** is assigned to **title**. - - ``` - export default { - data: { - title: '', - }, - onInit() { - this.title = this.$t('strings.world'); - }, - } - ``` - - -## Repositories Involved - -JS UI framework - -[arkui\_ace\_engine](https://gitee.com/openharmony/arkui_ace_engine) - -[arkui\_ace\_engine\_lite](https://gitee.com/openharmony/arkui_ace_engine_lite) - -[ace\_napi](https://gitee.com/openharmony/ace_napi) - diff --git a/en/readme/netwowk-management.md b/en/readme/netwowk-management.md deleted file mode 100644 index 8186e61d5c9519abc1c832c90e71b0fe4ab27aa8..0000000000000000000000000000000000000000 --- a/en/readme/netwowk-management.md +++ /dev/null @@ -1,127 +0,0 @@ -# Network Management - - -## Introduction - -As a mandatory component for device networking, the network management subsystem manages different types of network connections in a unified manner and provides network protocol stack capabilities. An application can call APIs to obtain connection information of a data network, query and subscribe to connection status, and transfer data by using the network protocol stack. - -The network management subsystem consists of the following components: - -- Basic network connection management component: provides basic network connection management and corresponding JavaScript and native APIs to implement functions, such as managing network connection priorities, querying network connection information, observing network connection status changes, performing DNS resolution, and managing physical networks. -- Network protocol stack component: provides basic network protocol stacks including HTTP, HTTPS, TCP, and UDP stacks, and corresponding JavaScript APIs. - -**Figure 1** System architecture - -![](figures/en_architecture-of-netmanager-subsystem.png) - -## Directory Structure - -``` -foundation/communication/ -├── netmanager_base # Basic network connection management -└── netstack # Network protocol stacks -``` - -## Usage - -### Receiving Network Status Change Notifications - -1. Import the **connection** namespace from **@ohos.net.connection.d.ts**. - -2. Call **createNetConnection()** to create a **NetConnection** object. You can specify the network capability, network type, and timeout interval. - -3. Call the **on()** method of the object to subscribe to concerned events by specifying **type** and **callback**. - -4. Call the **register()** method of the object to subscribe to status changes of the specified network. - -5. When the network is available, the callback will be invoked to return the **netAvailable** event. - -6. Call the **unregister()** method of the object to unsubscribe from the status changes if required. - - ``` - // Import the package name. - import connection from '@ohos.net.connection' - - let netCap = { - // Set the network type to cellular network. - bearerTypes: [connection.NetBearType.BEARER_CELLULAR], - // Set the network capability to Internet. - networkCap: [connection.NetCap.NET_CAPABILITY_INTERNET], - }; - let netSpec = { - netCapabilities: netCap, - }; - // Set the timeout interval to 10s. - let timeout = 10 * 1000; - // Create a NetConnection object. - let conn = connection.createNetConnection(netSpec, timeout); - // Subscribe to on_netAvailable events. - conn.on('netAvailable', (data=> { - console.log("net is available, netId is " + data.netId); - })); - // Register a listener for network status changes. - conn.register((err, data) => {}); - // When the network is not used, call the unregister method to cancel the subscription. - conn.unregister((err, data) => {}); - ``` - - -### Sending a Network Request - -1. Import the **http** namespace from **@ohos.net.http.d.ts**. -2. Call the **createHttp** method to create an **HttpRequest** object. -3. Call the **on()** method of the object to subscribe to the HTTP response header. This method returns a response earlier than the request. You can subscribe to HTTP response header events based on service requirements. -4. Call the **request()** method of the object with the URL and optional parameters of the HTTP request to initiate a network request. -5. Parse the returned result based on service requirements. -6. Call the **destroy()** method to destroy the request. - -``` -// Import the package name. -import http from '@ohos.net.http'; - -// Each httpRequest corresponds to an HttpRequestTask object and cannot be reused. -let httpRequest = http.createHttp(); -// Subscribe to the HTTP response header, which is returned earlier than httpRequest. You can subscribe to HTTP response header events based on service requirements. -httpRequest.on('headersReceive', (data) => { - console.info('header: ' + data.header); -}); -httpRequest.request( - // Set the URL of the HTTP request. You need to define the URL. Set the parameters of the GET request in extraData. - "EXAMPLE_URL", - { - method: 'POST', // Optional. The default value is GET. - // You can add the header field based on service requirements. - header: { - 'Content-Type': 'application/json' - }, - // This field is used to transfer data when the POST request is used. - extraData: { - "data": "data to send", - }, - connectTimeout: 60000, // Optional. The default value is 60 seconds. - readTimeout: 60000, // Optional. The default value is 60 seconds. - },(err, data) => { - if (!err) { - // data.result contains 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. - console.info('header:' + data.header); - console.info('header:' + data.cookies); - } else { - console.info('error:' + err); - } - // Call the destroy() method to release resources after the call is complete. - httpRequest.destroy(); - } -); -``` - - -## Repositories Involved - -**Network Management Subsystem** - -[communication_netmanager_base](https://gitee.com/openharmony/communication_netmanager_base) - -[communication_netstack](https://gitee.com/openharmony/communication_netstack) diff --git a/en/release-notes/api-change/v3.2-beta2/readme.md b/en/release-notes/api-change/v3.2-beta2/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..21548e70cc7276031e010cd063888682d7d79cb9 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta2/readme.md @@ -0,0 +1,35 @@ +# Readme + +This directory records the API changes in OpenHarmony 3.2 Beta2 over OpenHarmony 3.2 Beta1, including new, updated, deprecated, and deleted APIs. + +- JS API Differences + - [Ability framework](js-apidiff-ability.md) + - [Accessibility subsystem](js-apidiff-accessibility.md) + - [Account subsystem](js-apidiff-account.md) + - [ArkUI development framework](js-apidiff-arkui.md) + - [Bundle management framework](js-apidiff-bundle.md) + - [Communication subsystem](js-apidiff-communicate.md) + - [Utils subsystem](js-apidiff-compiler-and-runtime.md) + - [DFX subsystem](js-apidiff-dfx.md) + - [Distributed data management subsystem](js-apidiff-distributed-data.md) + - [Common event and notification subsystem](js-apidiff-event-and-notification.md) + - [File management subsystem](js-apidiff-file-management.md) + - [Location subsystem](js-apidiff-geolocation.md) + - [Globalization subsystem](js-apidiff-global.md) + - [Graphics subsystem](js-apidiff-graphic.md) + - [Misc services subsystem](js-apidiff-misc.md) + - [Multimodal input subsystem](js-apidiff-multi-modal-input.md) + - [Multimedia subsystem](js-apidiff-multimedia.md) + - [Resource scheduler subsystem](js-apidiff-resource-scheduler.md) + - [Security subsystem](js-apidiff-security.md) + - [Pan-sensor subsystem](js-apidiff-sensor.md) + - [DSoftBus subsystem](js-apidiff-soft-bus.md) + - [Test subsystem](js-apidiff-unitest.md) + - [Update subsystem](js-apidiff-update.md) + - [USB subsystem](js-apidiff-usb.md) + - [User IAM subsystem](js-apidiff-user-authentication.md) + - [Web subsystem](js-apidiff-web.md) + - [Window manager subsystem](js-apidiff-window.md) +- ChangeLog + - [Updates Between OpenHarmony 3.2 Beta2 and OpenHarmony 3.2 Beta1](changelog-v3.2-beta2.md) + - [Adaptation Guide for the Application Sandbox](application-sandbox-adaptation-guide.md) diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-ability.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-ability.md new file mode 100644 index 0000000000000000000000000000000000000000..7e5d3e2295707770da05bbe228701d10844e6943 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-ability.md @@ -0,0 +1,106 @@ +# JS API Changes of the Ability Framework + +The table below lists the APIs changes of the ability framework in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| abilityDelegator | AbilityDelegator | waitAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout: number, callback: AsyncCallback\): void;
waitAbilityStageMonitor(monitor: AbilityStageMonitor, timeout?: number): Promise\; | Added| +| abilityDelegator | AbilityDelegator | removeAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
removeAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; | Added| +| abilityDelegator | AbilityDelegator | addAbilityStageMonitor(monitor: AbilityStageMonitor, callback: AsyncCallback\): void;
addAbilityStageMonitor(monitor: AbilityStageMonitor): Promise\; | Added| +| abilityStageMonitor | AbilityStageMonitor | srcEntrance: string; | Added| +| abilityStageMonitor | AbilityStageMonitor | moduleName: string; | Added| +| applicationInfo | ApplicationInfo | readonly iconIndex: number; | Added| +| applicationInfo | ApplicationInfo | readonly labelIndex: number; | Added| +| ApplicationStateObserver | ApplicationStateObserver | onProcessStateChanged(processData: ProcessData): void; | Added| +| context | Context | getExternalCacheDir(callback: AsyncCallback\): void
getExternalCacheDir(): Promise\; | Added| +| lifecycle | LifecycleForm | onShare?(formId: string): {[key: string]: any}; | Added| +| MissionListener | MissionListener | onMissionClosed(mission: number): void; | Added| +| ohos.ability.wantConstant | Action | DLP_PARAMS_INDEX = "ohos.dlp.params.index" | Added| +| ohos.ability.wantConstant | Action | DLP_PARAMS_ABILITY_NAME = "ohos.dlp.params.abilityName" | Added| +| ohos.ability.wantConstant | Action | DLP_PARAMS_MODULE_NAME = "ohos.dlp.params.moduleName" | Added| +| ohos.ability.wantConstant | Action | DLP_PARAMS_BUNDLE_NAME = "ohos.dlp.params.bundleName" | Added| +| ohos.ability.wantConstant | Action | DLP_PARAMS_SANDBOX = "ohos.dlp.params.sandbox" | Added| +| ohos.ability.wantConstant | Action | ACTION_MARKET_CROWDTEST = "ohos.want.action.marketCrowdTest" | Added| +| ohos.ability.wantConstant | Action | ACTION_MARKET_DOWNLOAD = "ohos.want.action.marketDownload" | Added| +| ohos.abilityAccessCtrl | PermissionStateChangeInfo | permissionName: string; | Added| +| ohos.abilityAccessCtrl | PermissionStateChangeInfo | tokenID: number; | Added| +| ohos.abilityAccessCtrl | PermissionStateChangeInfo | change: PermissionStateChangeType; | Added| +| ohos.abilityAccessCtrl | PermissionStateChangeType | PERMISSION_GRANTED_OPER = 1 | Added| +| ohos.abilityAccessCtrl | PermissionStateChangeType | PERMISSION_REVOKED_OPER = 0 | Added| +| ohos.abilityAccessCtrl | AtManager | off(type: 'permissionStateChange', tokenIDList: Array\, permissionNameList: Array\, callback?: Callback\): void; | Added| +| ohos.abilityAccessCtrl | AtManager | on(type: 'permissionStateChange', tokenIDList: Array\, permissionNameList: Array\, callback: Callback\): void; | Added| +| ohos.abilityAccessCtrl | AtManager | getVersion(): Promise\; | Added| +| ohos.application.Ability | Ability | onMemoryLevel(level: AbilityConstant.MemoryLevel): void; | Added| +| ohos.application.AbilityConstant | WindowMode | WINDOW_MODE_FLOATING = 102 | Added| +| ohos.application.AbilityConstant | WindowMode | WINDOW_MODE_SPLIT_SECONDARY = 101 | Added| +| ohos.application.AbilityConstant | WindowMode | WINDOW_MODE_SPLIT_PRIMARY = 100 | Added| +| ohos.application.AbilityConstant | WindowMode | WINDOW_MODE_FULLSCREEN = 1 | Added| +| ohos.application.AbilityConstant | WindowMode | WINDOW_MODE_UNDEFINED = 0 | Added| +| ohos.application.AbilityConstant | MemoryLevel | MEMORY_LEVEL_CRITICAL = 2 | Added| +| ohos.application.AbilityConstant | MemoryLevel | MEMORY_LEVEL_LOW = 1 | Added| +| ohos.application.AbilityConstant | MemoryLevel | MEMORY_LEVEL_MODERATE = 0 | Added| +| ohos.application.AbilityLifecycleCallback | AbilityLifecycleCallback | onWindowStageDestroy(ability: Ability, windowStage: window.WindowStage): void; | Added| +| ohos.application.AbilityLifecycleCallback | AbilityLifecycleCallback | onWindowStageInactive(ability: Ability, windowStage: window.WindowStage): void; | Added| +| ohos.application.AbilityLifecycleCallback | AbilityLifecycleCallback | onWindowStageActive(ability: Ability, windowStage: window.WindowStage): void; | Added| +| ohos.application.AbilityLifecycleCallback | AbilityLifecycleCallback | onWindowStageCreate(ability: Ability, windowStage: window.WindowStage): void; | Added| +| ohos.application.AbilityStage | AbilityStage | onMemoryLevel(level: AbilityConstant.MemoryLevel): void; | Added| +| ohos.application.appManager | ProcessState | STATE_DESTROY | Added| +| ohos.application.appManager | ProcessState | STATE_BACKGROUND | Added| +| ohos.application.appManager | ProcessState | STATE_ACTIVE | Added| +| ohos.application.appManager | ProcessState | STATE_FOREGROUND | Added| +| ohos.application.appManager | ProcessState | STATE_CREATE | Added| +| ohos.application.appManager | ApplicationState | STATE_DESTROY | Added| +| ohos.application.appManager | ApplicationState | STATE_BACKGROUND | Added| +| ohos.application.appManager | ApplicationState | STATE_ACTIVE | Added| +| ohos.application.appManager | ApplicationState | STATE_FOREGROUND | Added| +| ohos.application.appManager | ApplicationState | STATE_CREATE | Added| +| ohos.application.Configuration | Configuration | hasPointerDevice?: boolean; | Added| +| ohos.application.context | AreaMode | EL2 = 1 | Added| +| ohos.application.context | AreaMode | EL1 = 0 | Added| +| ohos.application.formError | FormError | ERR_DISTRIBUTED_SCHEDULE_FAILED = 37 | Added| +| ohos.application.FormExtension | FormExtension | onShare?(formId: string): {[key: string]: any}; | Added| +| ohos.application.formHost | formHost | function shareForm(formId: string, deviceId: string, callback: AsyncCallback\): void;
function shareForm(formId: string, deviceId: string): Promise\; | Added| +| ohos.application.formInfo | VisibilityType | FORM_INVISIBLE: number | Added| +| ohos.application.formInfo | VisibilityType | FORM_VISIBLE: number, | Added| +| ohos.application.formInfo | FormDimension | Dimension_2_1 | Added| +| ohos.application.formInfo | FormDimension | Dimension_4_4 | Added| +| ohos.application.formInfo | FormDimension | Dimension_2_4 | Added| +| ohos.application.formInfo | FormDimension | Dimension_2_2 | Added| +| ohos.application.formInfo | FormDimension | Dimension_1_2 = 1 | Added| +| ohos.application.formInfo | FormParam | DEVICE_ID_KEY = "ohos.extra.param.key.device_id" | Added| +| ohos.application.formInfo | FormParam | ABILITY_NAME_KEY = "ohos.extra.param.key.ability_name" | Added| +| ohos.application.formInfo | FormParam | BUNDLE_NAME_KEY = "ohos.extra.param.key.bundle_name" | Added| +| ohos.application.quickFixManager | quickFixManager | function getApplicationQuickFixInfo(bundleName: string, callback: AsyncCallback\): void;
function getApplicationQuickFixInfo(bundleName: string): Promise\; | Added| +| ohos.application.quickFixManager | quickFixManager | function applyQuickFix(hapModuleQuickFixFiles: Array\, callback: AsyncCallback\): void;
function applyQuickFix(hapModuleQuickFixFiles: Array\): Promise\; | Added| +| ohos.application.quickFixManager | ApplicationQuickFixInfo | readonly hapModuleQuickFixInfo: Array\; | Added| +| ohos.application.quickFixManager | ApplicationQuickFixInfo | readonly quickFixVersionName: string; | Added| +| ohos.application.quickFixManager | ApplicationQuickFixInfo | readonly quickFixVersionCode: number; | Added| +| ohos.application.quickFixManager | ApplicationQuickFixInfo | readonly bundleVersionName: string; | Added| +| ohos.application.quickFixManager | ApplicationQuickFixInfo | readonly bundleVersionCode: number; | Added| +| ohos.application.quickFixManager | ApplicationQuickFixInfo | readonly bundleName: string; | Added| +| ohos.application.quickFixManager | HapModuleQuickFixInfo | readonly quickFixFilePath: string; | Added| +| ohos.application.quickFixManager | HapModuleQuickFixInfo | readonly originHapHash: string; | Added| +| ohos.application.quickFixManager | HapModuleQuickFixInfo | readonly moduleName: string; | Added| +| ProcessData | ProcessData | isKeepAlive: boolean; | Added| +| ProcessData | ProcessData | isContinuousTask: boolean; | Added| +| ProcessData | ProcessData | state: number; | Added| +| ServiceExtensionContext | ServiceExtensionContext | startAbilityByCall(want: Want): Promise\; | Added| +| ohos.ability.wantConstant | Action | ACTION_MARKER_DOWNLOAD = "ohos.want.action.marketDownload" | Deleted| +| ohos.application.AbilityLifecycleCallback | AbilityLifecycleCallback | onAbilityWindowStageDestroy(ability: Ability): void; | Deleted| +| ohos.application.AbilityLifecycleCallback | AbilityLifecycleCallback | onAbilityWindowStageCreate(ability: Ability): void; | Deleted| +| ohos.application.DataShareExtensionAbility | DataShareExtensionAbility | getType?(uri: string, callback: AsyncCallback\): void; | Deleted| +| ohos.application.DataShareExtensionAbility | DataShareExtensionAbility | openFile?(uri: string, mode: string, callback: AsyncCallback\): void; | Deleted| +| ohos.application.DataShareExtensionAbility | DataShareExtensionAbility | getFileTypes?(uri: string, mimeTypeFilter: string, callback: AsyncCallback\>): void; | Deleted| +| applicationInfo | ApplicationInfo | readonly iconId: string; | Deprecated| +| applicationInfo | ApplicationInfo | readonly labelId: string; | Deprecated| +| want | Want | entities?: Array\; | Deprecated| +| want | Want | parameters?: {[key: string]: any}; | Deprecated| +| want | Want | action?: string; | Deprecated| +| want | Want | flags?: number; | Deprecated| +| want | Want | type?: string; | Deprecated| +| want | Want | uri?: string; | Deprecated| +| want | Want | abilityName?: string; | Deprecated| +| want | Want | bundleName?: string; | Deprecated| +| want | Want | deviceId?: string; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-accessibility.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-accessibility.md new file mode 100644 index 0000000000000000000000000000000000000000..2bf959002cf182a4805c20978722921fa050d19b --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-accessibility.md @@ -0,0 +1,31 @@ +# JS API Changes of the Accessibility Subsystem + +The table below lists the APIs changes of the accessibility subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| AccessibilityExtensionContext | AccessibilityExtensionContext | injectGesture(gesturePath: GesturePath): Promise\;
injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void; | Added| +| ohos.accessibility.config | Config | off(callback?: Callback\): void; | Added| +| ohos.accessibility.config | Config | on(callback: Callback\): void; | Added| +| ohos.accessibility.config | Config | get(): Promise\;
get(callback: AsyncCallback\): void; | Added| +| ohos.accessibility.config | Config | set(value: T): Promise\;
set(value: T, callback: AsyncCallback\): void; | Added| +| ohos.accessibility.config | config | function off(type: 'enableAbilityListsStateChanged', callback?: Callback\): void; | Added| +| ohos.accessibility.config | config | function on(type: 'enableAbilityListsStateChanged', callback: Callback\): void; | Added| +| ohos.accessibility.config | config | function disableAbility(name: string): Promise\;
function disableAbility(name: string, callback: AsyncCallback\): void; | Added| +| ohos.accessibility.config | config | function enableAbility(name: string, capability: Array\): Promise\;
function enableAbility(name: string, capability: Array\, callback: AsyncCallback\): void; | Added| +| ohos.accessibility.config | config | var captionsStyle: Config\; | Added| +| ohos.accessibility.config | config | var captions: Config\; | Added| +| ohos.accessibility.config | config | var shortkeyTarget: Config\; | Added| +| ohos.accessibility.config | config | var shortkey: Config\; | Added| +| ohos.accessibility.config | config | var mouseAutoClick: Config\; | Added| +| ohos.accessibility.config | config | var mouseKey: Config\; | Added| +| ohos.accessibility.config | config | var brightnessDiscount: Config\; | Added| +| ohos.accessibility.config | config | var animationOff: Config\; | Added| +| ohos.accessibility.config | config | var contentTimeout: Config\; | Added| +| ohos.accessibility.config | config | var daltonizationColorFilter: Config\; | Added| +| ohos.accessibility.config | config | var invertColor: Config\; | Added| +| ohos.accessibility.config | config | var highContrastText: Config\; | Added| +| AccessibilityExtensionContext | AccessibilityExtensionContext | gestureInject(gesturePath: GesturePath, listener: Callback\): Promise\;
gestureInject(gesturePath: GesturePath, listener: Callback\, callback: AsyncCallback\): void; | Deleted| +| AccessibilityExtensionContext | AccessibilityExtensionContext | setEventTypeFilter(type: Array\): Promise\;
setEventTypeFilter(type: Array\, callback: AsyncCallback\): boolean; | Deleted| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-account.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-account.md new file mode 100644 index 0000000000000000000000000000000000000000..8d75ba6f49b0e3a018f905c583f1a28ae5b7a56f --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-account.md @@ -0,0 +1,9 @@ +# JS API Changes of the Account Subsystem + +The table below lists the APIs changes of the account subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.account.appAccount | AppAccountManager | getAssociatedDataSync(name: string, key: string): string; | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-arkui.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-arkui.md new file mode 100644 index 0000000000000000000000000000000000000000..8b0381f0e6951df08d55beb7b8e92579d35ae0f6 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-arkui.md @@ -0,0 +1,131 @@ +# JS API Changes of the ArkUI Development Framework + +The table below lists the APIs changes of the ArkUI development framework in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ArkUI | WebAttribute | onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\, issuers : Array\}) => void): WebAttribute; | Added | +| ArkUI | WebAttribute | onSslErrorEventReceive(callback: (event: { handler: SslErrorHandler, error: SslError }) => void): WebAttribute; | Added| +| ArkUI | WebAttribute | onScroll(callback: (event: {xOffset: number, yOffset: number}) => void): WebAttribute; | Added| +| ArkUI | WebAttribute | onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute | Added| +| ArkUI | WebAttribute | mediaPlayGestureAccess(access: boolean): WebAttribute; | Added| +| ArkUI | WebAttribute | onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean): WebAttribute; | Added| +| ArkUI | WebAttribute | onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void): WebAttribute; | Added| +| ArkUI | WebAttribute | textZoomRatio(textZoomRatio: number): WebAttribute; | Added| +| ArkUI | WebController | clearClientAuthenticationCache(): void; | Added| +| ArkUI | WebController | clearSslCache(): void; | Added| +| ArkUI | WebController | searchNext(forward: boolean): void; | Added| +| ArkUI | WebController | clearMatches(): void; | Added| +| ArkUI | WebController | searchAllAsync(searchString: string): void; | Added| +| ArkUI | WebController | postMessage(options: { message: WebMessageEvent, uri: string}): void; | Added| +| ArkUI | WebController | createWebMessagePorts(): Array\; | Added| +| ArkUI | WebContextMenuResult | copyImage(): void; | Added| +| ArkUI | WebContextMenuResult | closeContextMenu(): void; | Added| +| ArkUI | WebContextMenuResult | constructor(); | Added| +| ArkUI | WebContextMenuParam | existsImageContents(): boolean; | Added| +| ArkUI | WebContextMenuParam | getSourceUrl(): string; | Added| +| ArkUI | WebContextMenuParam | getUnfilterendLinkUrl(): string; | Added| +| ArkUI | WebContextMenuParam | getLinkUrl(): string; | Added| +| ArkUI | WebContextMenuParam | y(): number; | Added| +| ArkUI | WebContextMenuParam | x(): number; | Added| +| ArkUI | WebContextMenuParam | constructor(); | Added| +| ArkUI | PermissionRequest | grant(resources: Array\): void; | Added| +| ArkUI | PermissionRequest | getAccessibleResource(): Array\; | Added| +| ArkUI | PermissionRequest | getOrigin(): string; | Added| +| ArkUI | PermissionRequest | deny(): void; | Added| +| ArkUI | PermissionRequest | constructor(); | Added| +| ArkUI | ProtectedResourceType | MidiSysex = "TYPE_MIDI_SYSEX" | Added| +| ArkUI | ClientAuthenticationHandler | ignore(): void; | Added| +| ArkUI | ClientAuthenticationHandler | cancel(): void; | Added| +| ArkUI | ClientAuthenticationHandler | confirm(priKeyFile : string, certChainFile : string): void; | Added| +| ArkUI | ClientAuthenticationHandler | constructor(); | Added| +| ArkUI | SslErrorHandler | handleCancel(): void; | Added| +| ArkUI | SslErrorHandler | handleConfirm(): void; | Added| +| ArkUI | SslErrorHandler | constructor(); | Added| +| ArkUI | SslError | Untrusted | Added| +| ArkUI | SslError | DateInvalid | Added| +| ArkUI | SslError | HostMismatch | Added| +| ArkUI | SslError | Invalid | Added| +| ArkUI | WebMessageEvent | setPorts(ports: Array\): void; | Added| +| ArkUI | WebMessageEvent | getPorts(): Array\; | Added| +| ArkUI | WebMessageEvent | setData(data: string): void; | Added| +| ArkUI | WebMessageEvent | getData(): string; | Added| +| ArkUI | WebMessageEvent | constructor(); | Added| +| ArkUI | WebMessagePort | onMessageEvent(callback: (result: string) => void): void; | Added| +| ArkUI | WebMessagePort | postMessageEvent(message: WebMessageEvent): void; | Added| +| ArkUI | WebMessagePort | close(): void; | Added| +| ArkUI | WebMessagePort | constructor(); | Added| +| ArkUI | ColorFilter | constructor(value: number[]); | Added| +| ArkUI | TextInputAttribute | style(value: TextInputStyle): TextInputAttribute; | Added| +| ArkUI | TextInputStyle | Inline | Added| +| ArkUI | TextInputStyle | Default | Added| +| ArkUI | TabsAttribute | barPosition(value: BarPosition): TabsAttribute; | Added| +| ArkUI | SideBarContainerAttribute | sideBarPosition(value: SideBarPosition): SideBarContainerAttribute; | Added| +| ArkUI | SideBarPosition | End | Added| +| ArkUI | SideBarPosition | Start | Added| +| ArkUI | WindowAnimationTarget | readonly missionId: number; | Added| +| ArkUI | PanelAttribute | onHeightChange(callback: (value: number) => void): PanelAttribute; | Added| +| ArkUI | PanelAttribute | backgroundMask(color: ResourceColor): PanelAttribute; | Added| +| ArkUI | ListItemGroupAttribute | divider(value: {strokeWidth: Length;color?: ResourceColor;startMargin?: Length;endMargin?: Length;} \| null,): ListItemGroupAttribute; | Added | +| ArkUI | ListItemGroupInterface | (options?: ListItemGroupOptions): ListItemGroupAttribute; | Added| +| ArkUI | ListItemGroupOptions | space?: number \| string; | Added| +| ArkUI | ListItemGroupOptions | footer?: CustomBuilder; | Added| +| ArkUI | ListItemGroupOptions | header?: CustomBuilder; | Added| +| ArkUI | ListItemAttribute | swipeAction(value: SwipeActionOptions): ListItemAttribute; | Added| +| ArkUI | SwipeActionOptions | edgeEffect?: SwipeEdgeEffect; | Added| +| ArkUI | SwipeActionOptions | end?: CustomBuilder; | Added| +| ArkUI | SwipeActionOptions | start?: CustomBuilder; | Added| +| ArkUI | SwipeEdgeEffect | None | Added| +| ArkUI | SwipeEdgeEffect | Spring | Added| +| ArkUI | ListAttribute | sticky(value: StickyStyle): ListAttribute; | Added| +| ArkUI | StickyStyle | Footer = 2 | Added| +| ArkUI | StickyStyle | Header = 1 | Added| +| ArkUI | StickyStyle | None = 0 | Added| +| ArkUI | ImageAttribute | copyOption(value: CopyOptions): ImageAttribute; | Added| +| ArkUI | ImageAttribute | colorFilter(value: ColorFilter): ImageAttribute; | Added| +| ArkUI | GutterOption | y?: Length \| GridRowSizeOption | Added| +| ArkUI | GutterOption | x?: Length \| GridRowSizeOption, | Added| +| ArkUI | FormDimension | Dimension_2_1 | Added| +| ArkUI | HitTestMode | None | Added| +| ArkUI | HitTestMode | Transparent | Added| +| ArkUI | HitTestMode | Block | Added| +| ArkUI | HitTestMode | Default | Added| +| ArkUI | CopyOptions | LocalDevice = 2 | Added| +| ArkUI | CopyOptions | InApp = 1 | Added| +| ArkUI | CopyOptions | None = 0 | Added| +| ArkUI | Color | Transparent | Added| +| ArkUI | CommonMethod | focusOnTouch(value: boolean): T; | Added| +| ArkUI | CommonMethod | groupDefaultFocus(value: boolean): T; | Added| +| ArkUI | CommonMethod | defaultFocus(value: boolean): T; | Added| +| ArkUI | CommonMethod | hitTestBehavior(value: HitTestMode): T; | Added| +| ArkUI | CustomPopupOptions | arrowOffset?: Length; | Added| +| ArkUI | PopupOptions | arrowOffset?: Length; | Added| +| ArkUI | focusControl | function requestFocus(value: string): boolean; | Added| +| basic | BusinessError | data?: T; | Added| +| canvaspattern | CanvasPattern | setTransform(transform?: Matrix2D): void; | Added| +| canvaspattern | Matrix2D | scaleX?: number; | Added| +| canvaspattern | Matrix2D | rotateY?: number; | Added| +| canvaspattern | Matrix2D | rotateX?: number; | Added| +| canvaspattern | Matrix2D | scaleY?: number; | Added| +| canvaspattern | Matrix2D | translateX?: number; | Added| +| canvaspattern | Matrix2D | translateY?: number; | Added| +| canvaspattern | Matrix2D | identity(): Matrix2D; | Added| +| canvaspattern | Matrix2D | invert(): Matrix2D; | Added| +| canvaspattern | Matrix2D | multiply(other?: Matrix2D): Matrix2D; | Added| +| canvaspattern | Matrix2D | rotate(rx?: number, ry?: number): Matrix2D; | Added| +| canvaspattern | Matrix2D | translate(tx?: number, ty?: number): Matrix2D; | Added| +| canvaspattern | Matrix2D | scale(sx?: number, sy?: number): Matrix2D; | Added| +| canvaspattern | Matrix2D | constructor(); | Added| +| ohos.curves | curves | function responsiveSpringMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve; | Added| +| ohos.curves | curves | function springMotion(response?: number, dampingFraction?: number, overlapDuration?: number): ICurve; | Added| +| ArkUI | CanvasPattern | setTransform(transform?: Matrix2D): void; | Deleted| +| ArkUI | GetterOption | y?: Length \| GridRowSizeOption | Deleted| +| ArkUI | GetterOption | x?: Length \| GridRowSizeOption, | Deleted| +| ArkUI | CopyOption | CrossDevice = 2 | Deleted| +| ArkUI | CopyOption | LocalDevice = 1 | Deleted| +| ArkUI | CopyOption | InApp = 0 | Deleted| +| ArkUI | WebAttribute | textZoomAtio(textZoomAtio: number): WebAttribute; | Deprecated| +| ArkUI | CommonMethod | touchable(value: boolean): T; | Deprecated| +| system.app | App | static requestFullWindow(options?: RequestFullWindowOptions): void; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md new file mode 100644 index 0000000000000000000000000000000000000000..ba467eb35900e0cf7336e77bffaed9bc45f140a1 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-battery.md @@ -0,0 +1,39 @@ +# JS API Changes of the Power Management Subsystem + +The table below lists the APIs changes of the power management subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| system.battery | Battery | static getStatus(options?: GetStatusOptions): void; | Deprecated| +| system.battery | GetStatusOptions | complete?: () => void; | Deprecated| +| system.battery | GetStatusOptions | fail?: (data: string, code: number) => void; | Deprecated| +| system.battery | GetStatusOptions | success?: (data: BatteryResponse) => void; | Deprecated| +| system.battery | BatteryResponse | level: number; | Deprecated| +| system.battery | BatteryResponse | charging: boolean; | Deprecated| +| system.brightness | Brightness | static setKeepScreenOn(options?: SetKeepScreenOnOptions): void; | Deprecated| +| system.brightness | Brightness | static setMode(options?: SetBrightnessModeOptions): void; | Deprecated| +| system.brightness | Brightness | static getMode(options?: GetBrightnessModeOptions): void; | Deprecated| +| system.brightness | Brightness | static setValue(options?: SetBrightnessOptions): void; | Deprecated| +| system.brightness | Brightness | static getValue(options?: GetBrightnessOptions): void; | Deprecated| +| system.brightness | SetKeepScreenOnOptions | complete?: () => void | Deprecated| +| system.brightness | SetKeepScreenOnOptions | fail?: (data: string, code: number) => void; | Deprecated| +| system.brightness | SetKeepScreenOnOptions | success?: () => void; | Deprecated| +| system.brightness | SetKeepScreenOnOptions | keepScreenOn: boolean; | Deprecated| +| system.brightness | SetBrightnessModeOptions | complete?: () => void | Deprecated| +| system.brightness | SetBrightnessModeOptions | fail?: (data: string, code: number) => void; | Deprecated| +| system.brightness | SetBrightnessModeOptions | success?: () => void; | Deprecated| +| system.brightness | SetBrightnessModeOptions | mode: number; | Deprecated| +| system.brightness | GetBrightnessModeOptions | complete?: () => void; | Deprecated| +| system.brightness | GetBrightnessModeOptions | fail?: (data: string, code: number) => void; | Deprecated| +| system.brightness | GetBrightnessModeOptions | success?: (data: BrightnessModeResponse) => void; | Deprecated| +| system.brightness | BrightnessModeResponse | mode: number; | Deprecated| +| system.brightness | SetBrightnessOptions | complete?: () => void | Deprecated| +| system.brightness | SetBrightnessOptions | fail?: (data: string, code: number) => void; | Deprecated| +| system.brightness | SetBrightnessOptions | success?: () => void; | Deprecated| +| system.brightness | SetBrightnessOptions | value: number; | Deprecated| +| system.brightness | GetBrightnessOptions | complete?: () => void; | Deprecated| +| system.brightness | GetBrightnessOptions | fail?: (data: string, code: number) => void; | Deprecated| +| system.brightness | GetBrightnessOptions | success?: (data: BrightnessResponse) => void; | Deprecated| +| system.brightness | BrightnessResponse | value: number; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-bundle.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-bundle.md new file mode 100644 index 0000000000000000000000000000000000000000..4649e2b56b4b854b04b661775c62fde3125757a2 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-bundle.md @@ -0,0 +1,14 @@ +# JS API Changes of the Bundle Management Framework + +The table below lists the APIs changes of the bundle management framework in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| dispatchInfo | DispatchInfo | readonly version: string; | Added| +| ohos.bundle | bundle | function getBundleInfoSync(bundleName: string, bundleFlags: number, options: BundleOptions): BundleInfo;
function getBundleInfoSync(bundleName: string, bundleFlags: number): BundleInfo; | Added| +| ohos.bundle | bundle | function getApplicationInfoSync(bundleName: string, bundleFlags: number, userId: number) : ApplicationInfo;
function getApplicationInfoSync(bundleName: string, bundleFlags: number) : ApplicationInfo; | Added| +| ohos.bundle | ExtensionAbilityType | PREVIEW = 14 | Added| +| ohos.bundle | ExtensionAbilityType | THUMBNAIL = 13 | Added| +| dispatchInfo | DispatchInfo | readonly verison: string; | Deleted| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-communicate.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-communicate.md new file mode 100644 index 0000000000000000000000000000000000000000..ee60c2bc88ebf528239cca46470a034612dac11e --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-communicate.md @@ -0,0 +1,12 @@ +# JS API Changes of the Communication Subsystem + +The table below lists the APIs changes of the communication subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.wifi | wifi | function off(type: "deviceConfigChange", callback?: Callback\): void; | Added| +| ohos.wifi | wifi | function on(type: "deviceConfigChange", callback: Callback\): void; | Added| +| ohos.wifi | wifi | function removeUntrustedConfig(config: WifiDeviceConfig): Promise\;
function removeUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback\): void; | Deprecated| +| ohos.wifi | wifi | function addUntrustedConfig(config: WifiDeviceConfig): Promise\;
function addUntrustedConfig(config: WifiDeviceConfig, callback: AsyncCallback\): void; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-compiler-and-runtime.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-compiler-and-runtime.md new file mode 100644 index 0000000000000000000000000000000000000000..3c1957aff039872d58115413ad1b216a9ff77424 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-compiler-and-runtime.md @@ -0,0 +1,93 @@ +# JS API Changes of the Utils Subsystem + +The table below lists the APIs changes of the Utils subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.buffer | Blob | text(): Promise\; | Added| +| ohos.buffer | Blob | slice(start?: number, end?: number, type?: string): Blob; | Added| +| ohos.buffer | Blob | arrayBuffer(): Promise\; | Added| +| ohos.buffer | Blob | type: string; | Added| +| ohos.buffer | Blob | size: number; | Added| +| ohos.buffer | Blob | constructor(sources: string[] \| ArrayBuffer[] \| TypedArray[] \| DataView[] \| Blob[] , options?: Object); | Added| +| ohos.buffer | Buffer | writeUIntLE(value: number, offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | writeUIntBE(value: number, offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | writeUInt32LE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeUInt32BE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeUInt16LE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeUInt16BE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeUInt8(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeIntLE(value : number, offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | writeIntBE(value: number, offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | writeInt32LE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeInt32BE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeInt16LE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeInt16BE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeInt8(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeFloatLE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeFloatBE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeDoubleLE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeDoubleBE(value: number, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeBigUInt64LE(value: bigint, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeBigUInt64BE(value: bigint, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeBigInt64LE(value: bigint, offset?: number): number; | Added| +| ohos.buffer | Buffer | writeBigInt64BE(value: bigint, offset?: number): number; | Added| +| ohos.buffer | Buffer | write(str: string, offset?: number, length?: number, encoding?: string): number; | Added| +| ohos.buffer | Buffer | toString(encoding?: string, start?: number, end?: number): string; | Added| +| ohos.buffer | Buffer | toJSON(): Object; | Added| +| ohos.buffer | Buffer | swap64(): Buffer; | Added| +| ohos.buffer | Buffer | swap32(): Buffer; | Added| +| ohos.buffer | Buffer | swap16(): Buffer; | Added| +| ohos.buffer | Buffer | subarray(start?: number, end?: number): Buffer; | Added| +| ohos.buffer | Buffer | readUIntLE(offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | readUIntBE(offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | readUInt32LE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readUInt32BE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readUInt16LE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readUInt16BE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readUInt8(offset?: number): number; | Added| +| ohos.buffer | Buffer | readIntLE(offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | readIntBE(offset: number, byteLength: number): number; | Added| +| ohos.buffer | Buffer | readInt32LE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readInt32BE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readInt16LE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readInt16BE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readInt8(offset?: number): number; | Added| +| ohos.buffer | Buffer | readFloatLE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readFloatBE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readDoubleLE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readDoubleBE(offset?: number): number; | Added| +| ohos.buffer | Buffer | readBigUInt64LE(offset?: number): bigint; | Added| +| ohos.buffer | Buffer | readBigUInt64BE(offset?: number): bigint; | Added| +| ohos.buffer | Buffer | readBigInt64LE(offset?: number): bigint; | Added| +| ohos.buffer | Buffer | readBigInt64BE(offset?: number): bigint; | Added| +| ohos.buffer | Buffer | lastIndexOf(value: string \| number \| Buffer \| Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; | Added| +| ohos.buffer | Buffer | entries(): IterableIterator\<[number, number]>; | Added| +| ohos.buffer | Buffer | values(): IterableIterator\; | Added| +| ohos.buffer | Buffer | keys(): IterableIterator\; | Added| +| ohos.buffer | Buffer | indexOf(value: string \| number \| Buffer \| Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; | Added| +| ohos.buffer | Buffer | includes(value: string \| number \| Buffer \| Uint8Array, byteOffset?: number, encoding?: BufferEncoding): boolean; | Added| +| ohos.buffer | Buffer | equals(otherBuffer: Uint8Array \| Buffer): boolean; | Added| +| ohos.buffer | Buffer | copy(target: Buffer \| Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; | Added| +| ohos.buffer | Buffer | compare(target: Buffer \| Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 \| 0 \| 1; | Added| +| ohos.buffer | Buffer | fill(value: string \| Buffer \| Uint8Array \| number, offset?: number, end?: number, encoding?: BufferEncoding): Buffer; | Added| +| ohos.buffer | Buffer | byteOffset: number; | Added| +| ohos.buffer | Buffer | buffer: ArrayBuffer; | Added| +| ohos.buffer | Buffer | length: number; | Added| +| ohos.buffer | buffer | function transcode(source: Buffer \| Uint8Array, fromEnc: string, toEnc: string): Buffer; | Added| +| ohos.buffer | buffer | function compare(buf1: Buffer \| Uint8Array, buf2: Buffer \| Uint8Array): -1 \| 0 \| 1; | Added| +| ohos.buffer | buffer | function isEncoding(encoding: string):boolean; | Added| +| ohos.buffer | buffer | function isBuffer(obj: Object): boolean; | Added| +| ohos.buffer | buffer | function from(array: number[]): Buffer;
function from(arrayBuffer: ArrayBuffer \| SharedArrayBuffer, byteOffset?: number, length?: number): Buffer;
function from(buffer: Buffer \| Uint8Array): Buffer;
function from(object: Object, offsetOrEncoding: number \| string, length: number): Buffer;
function from(string: String, encoding?: BufferEncoding): Buffer; | Added| +| ohos.buffer | buffer | function concat(list: Buffer[] \| Uint8Array[], totalLength?: number): Buffer; | Added| +| ohos.buffer | buffer | function byteLength(string: string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer, encoding?: BufferEncoding): number; | Added| +| ohos.buffer | buffer | function allocUninitialized(size: number): Buffer; | Added| +| ohos.buffer | buffer | function allocUninitializedFromPool(size: number): Buffer; | Added| +| ohos.buffer | buffer | function alloc(size: number, fill?: string \| Buffer \| number, encoding?: BufferEncoding): Buffer; | Added| +| ohos.util | TextDecoder | decodeWithStream(input: Uint8Array, options?: { stream?: boolean }): string; | Added| +| ohos.util | util | function parseUUID(uuid: string): Uint8Array; | Added| +| ohos.util | util | function randomBinaryUUID(entropyCache?: boolean): Uint8Array; | Added| +| ohos.util | util | function randomUUID(entropyCache?: boolean): string; | Added| +| ohos.worker | DedicatedWorkerGlobalScope | postMessage(messageObject: Object, transfer: Transferable[]): void;
postMessage(messageObject: Object, options?: PostMessageOptions): void;
postMessage(messageObject: Object, transfer: ArrayBuffer[]): void; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-dfx.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-dfx.md new file mode 100644 index 0000000000000000000000000000000000000000..f00c53d0604c4aa07d8af472f48055e12e2734ef --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-dfx.md @@ -0,0 +1,32 @@ +# JS API Changes of the DFX Subsystem + +The table below lists the APIs changes of the DFX subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.hiAppEvent | hiAppEvent | function clearData(): void; | Added| +| ohos.hiAppEvent | hiAppEvent | function removeWatcher(watcher: Watcher): void; | Added| +| ohos.hiAppEvent | hiAppEvent | function addWatcher(watcher: Watcher): AppEventPackageHolder; | Added| +| ohos.hiAppEvent | Watcher | onTrigger?: (curRow: number, curSize:number, holder:AppEventPackageHolder) => void; | Added| +| ohos.hiAppEvent | Watcher | appEventFilters?: AppEventFilter[]; | Added| +| ohos.hiAppEvent | Watcher | triggerCondition?: TriggerCondition; | Added| +| ohos.hiAppEvent | Watcher | name: string; | Added| +| ohos.hiAppEvent | AppEventFilter | eventTypes?: EventType[]; | Added| +| ohos.hiAppEvent | AppEventFilter | domain: string; | Added| +| ohos.hiAppEvent | TriggerCondition | timeOut?: number; | Added| +| ohos.hiAppEvent | TriggerCondition | size?: number; | Added| +| ohos.hiAppEvent | TriggerCondition | row?: number; | Added| +| ohos.hiAppEvent | AppEventPackageHolder | takeNext(): AppEventPackage; | Added| +| ohos.hiAppEvent | AppEventPackageHolder | setSize(size: number): void; | Added| +| ohos.hiAppEvent | AppEventPackageHolder | constructor(watcherName: string); | Added| +| ohos.hiAppEvent | AppEventPackage | data: string[]; | Added| +| ohos.hiAppEvent | AppEventPackage | size: number; | Added| +| ohos.hiAppEvent | AppEventPackage | row: number; | Added| +| ohos.hiAppEvent | AppEventPackage | packageId: number; | Added| +| ohos.hiAppEvent | AppEventInfo | params: object; | Added| +| ohos.hiAppEvent | AppEventInfo | eventType: EventType; | Added| +| ohos.hiAppEvent | AppEventInfo | name: string; | Added| +| ohos.hiAppEvent | AppEventInfo | domain: string; | Added| +| ohos.hiAppEvent | hiAppEvent | function write(eventName: string, eventType: EventType, keyValues: object): Promise\;
function write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback\): void;
function write(info: AppEventInfo): Promise\;
function write(info: AppEventInfo, callback: AsyncCallback\): void; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-distributed-data.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-distributed-data.md new file mode 100644 index 0000000000000000000000000000000000000000..acf2a5ac5c9eb35b5563c9d077dc39523841c348 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-distributed-data.md @@ -0,0 +1,17 @@ +# JS API Changes of the Distributed Data Management Subsystem + +The table below lists the APIs changes of the distributed data management subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.data.distributedData | KVStore | deleteBackup(files:Array\, callback: AsyncCallback\>):void;
deleteBackup(files:Array\): Promise\>; | Added| +| ohos.data.distributedData | KVStore | restore(file:string, callback: AsyncCallback\):void;
restore(file:string): Promise\; | Added| +| ohos.data.distributedData | KVStore | backup(file:string, callback: AsyncCallback\):void;
backup(file:string): Promise\; | Added| +| ohos.data.rdb | StoreConfig | encrypt?: boolean; | Added| +| ohos.data.rdb | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array\, callback: AsyncCallback\): void;
remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array\): Promise\; | Added| +| ohos.data.rdb | RdbStore | batchInsert(table: string, values: Array\, callback: AsyncCallback\): void;
batchInsert(table: string, values: Array\): Promise\; | Added| +| ohos.data.dataShare | DataShareHelper | getFileTypes(uri: string, mimeTypeFilter:string, callback: AsyncCallback\>): void;
getFileTypes(uri: string, mimeTypeFilter: string): Promise\>; | Deleted| +| ohos.data.dataShare | DataShareHelper | getType(uri: string, callback: AsyncCallback\): void;
getType(uri: string): Promise\; | Deleted| +| ohos.data.dataShare | DataShareHelper | openFile(uri: string, mode: string, callback: AsyncCallback\): void;
openFile(uri: string, mode: string): Promise\; | Deleted| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-distributed-hardware.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-distributed-hardware.md new file mode 100644 index 0000000000000000000000000000000000000000..3cd622c79daf8e4abe6134fa6c5f479aac50eac8 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-distributed-hardware.md @@ -0,0 +1,19 @@ +# JS API Changes of the Distributed Hardware Subsystem + +The table below lists the APIs changes of the distributed hardware subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.distributedHardware.deviceManager | DeviceManager | off(type: 'publishFail', callback?: Callback<{ publishId: number, reason: number }>): void; | Added| +| ohos.distributedHardware.deviceManager | DeviceManager | on(type: 'publishFail', callback: Callback<{ publishId: number, reason: number }>): void; | Added| +| ohos.distributedHardware.deviceManager | DeviceManager | off(type: 'publishSuccess', callback?: Callback<{ publishId: number }>): void; | Added| +| ohos.distributedHardware.deviceManager | DeviceManager | on(type: 'publishSuccess', callback: Callback<{ publishId: number }>): void; | Added| +| ohos.distributedHardware.deviceManager | DeviceManager | unPublishDeviceDiscovery(publishId: number): void; | Added| +| ohos.distributedHardware.deviceManager | DeviceManager | publishDeviceDiscovery(publishInfo: PublishInfo): void; | Added| +| ohos.distributedHardware.deviceManager | PublishInfo | ranging : boolean; | Added| +| ohos.distributedHardware.deviceManager | PublishInfo | freq: ExchangeFreq; | Added| +| ohos.distributedHardware.deviceManager | PublishInfo | mode: DiscoverMode; | Added| +| ohos.distributedHardware.deviceManager | PublishInfo | publishId: number; | Added| +| ohos.distributedHardware.deviceManager | DeviceInfo | range: number; | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-event-and-notification.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-event-and-notification.md new file mode 100644 index 0000000000000000000000000000000000000000..64164c3dd157532ce0915d9915c357425b50ee9a --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-event-and-notification.md @@ -0,0 +1,18 @@ +# JS API Changes of the Common Event and Notification Subsystem + +The table below lists the APIs changes of the common event and notification subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.commonEvent | Support | COMMON_EVENT_QUICK_FIX_APPLY_RESULT = "usual.event.QUICK_FIX_APPLY_RESULT" | Added| +| ohos.commonEvent | Support | COMMON_EVENT_USB_PORT_CHANGED = "usual.event.hardware.usb.action.USB_PORT_CHANGED" | Added| +| ohos.commonEvent | Support | COMMON_EVENT_USB_STATE = "usual.event.hardware.usb.action.USB_STATE" | Added| +| ohos.commonEvent | Support | COMMON_EVENT_PACKAGE_CACHE_CLEARED = "usual.event.PACKAGE_CACHE_CLEARED" | Added| +| ohos.notification | RemoveReason | CANCEL_REASON_REMOVE = 2 | Added| +| ohos.notification | RemoveReason | CLICK_REASON_REMOVE = 1 | Added| +| ohos.notification | notification | function getSyncNotificationEnabledWithoutApp(userId: number, callback: AsyncCallback\): void;
function getSyncNotificationEnabledWithoutApp(userId: number): Promise\; | Added| +| ohos.notification | notification | function setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean, callback: AsyncCallback\): void;
function setSyncNotificationEnabledWithoutApp(userId: number, enable: boolean): Promise\; | Added| +| ohos.notification | notification | function getSyncNotificationEnabledForUninstallApp(userId: number, callback: AsyncCallback\): void;
function getSyncNotificationEnabledForUninstallApp(userId: number): Promise\; | Deleted| +| ohos.notification | notification | function setSyncNotificationEnabledForUninstallApp(userId: number, enable: boolean, callback: AsyncCallback\): void;
function setSyncNotificationEnabledForUninstallApp(userId: number, enable: boolean): Promise\; | Deleted| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-file-management.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-file-management.md new file mode 100644 index 0000000000000000000000000000000000000000..995692963ad249eacbfc8515c344feb2600c1f72 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-file-management.md @@ -0,0 +1,153 @@ +# JS API Changes of the File Management Subsystem + +The table below lists the APIs changes of the file management subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.data.fileAccess | FileAccessHelper | getRoots(): Promise\;
getRoots(callback:AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | FileAccessHelper | access(sourceFileUri: string) : Promise\;
access(sourceFileUri: string, callback: AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | FileAccessHelper | rename(uri: string, displayName: string) : Promise\;
rename(uri: string, displayName: string, callback: AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | FileAccessHelper | move(sourceFile: string, destFile: string) : Promise\;
move(sourceFile: string, destFile: string, callback: AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | FileAccessHelper | delete(uri: string) : Promise\;
delete(uri: string, callback: AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | FileAccessHelper | mkDir(parentUri: string, displayName: string) : Promise\;
mkDir(parentUri: string, displayName: string, callback: AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | FileAccessHelper | createFile(uri: string, displayName: string) : Promise\;
createFile(uri: string, displayName: string, callback: AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | FileAccessHelper | openFile(uri: string, flags: OPENFLAGS) : Promise\;
openFile(uri: string, flags: OPENFLAGS, callback: AsyncCallback\) : void; | Added| +| ohos.data.fileAccess | OPENFLAGS | WRITE_READ = 0o2 | Added| +| ohos.data.fileAccess | OPENFLAGS | WRITE = 0o1 | Added| +| ohos.data.fileAccess | OPENFLAGS | READ = 0o0 | Added| +| ohos.data.fileAccess | RootIterator | next(): {value: RootInfo, done: boolean} | Added| +| ohos.data.fileAccess | RootInfo | scanFile(filter?: Filter): FileIterator; | Added| +| ohos.data.fileAccess | RootInfo | listFile(filter?: Filter): FileIterator; | Added| +| ohos.data.fileAccess | RootInfo | deviceFlags: number; | Added| +| ohos.data.fileAccess | RootInfo | displayName: string; | Added| +| ohos.data.fileAccess | RootInfo | uri: string; | Added| +| ohos.data.fileAccess | RootInfo | deviceType: number; | Added| +| ohos.data.fileAccess | FileIterator | next(): {value: FileInfo, done: boolean} | Added| +| ohos.data.fileAccess | FileInfo | scanFile(filter?: Filter): FileIterator; | Added| +| ohos.data.fileAccess | FileInfo | listFile(filter?: Filter): FileIterator; | Added| +| ohos.data.fileAccess | FileInfo | mimeType: string; | Added| +| ohos.data.fileAccess | FileInfo | mtime: number; | Added| +| ohos.data.fileAccess | FileInfo | size: number; | Added| +| ohos.data.fileAccess | FileInfo | mode: number; | Added| +| ohos.data.fileAccess | FileInfo | fileName: string; | Added| +| ohos.data.fileAccess | FileInfo | uri: string; | Added| +| ohos.data.fileAccess | fileAccess | createFileAccessHelper(context: Context): FileAccessHelper;
createFileAccessHelper(context: Context, wants: Array\): FileAccessHelper; | Added| +| ohos.data.fileAccess | fileAccess | getFileAccessAbilityInfo(callback: AsyncCallback\>): void;
getFileAccessAbilityInfo(): Promise\>; | Added| +| ohos.fileExtensionInfo | DocumentFlag | const SUPPORTS_WRITE = 0b1000; | Added| +| ohos.fileExtensionInfo | DocumentFlag | const SUPPORTS_READ = 0b100; | Added| +| ohos.fileExtensionInfo | DocumentFlag | const REPRESENTS_DIR = 0b10; | Added| +| ohos.fileExtensionInfo | DocumentFlag | const REPRESENTS_FILE = 0b1; | Added| +| ohos.fileExtensionInfo | DeviceFlag | const SUPPORTS_WRITE = 0b10; | Added| +| ohos.fileExtensionInfo | DeviceFlag | const SUPPORTS_READ = 0b1; | Added| +| ohos.fileExtensionInfo | DeviceType | DEVICE_EXTERNAL_CLOUD | Added| +| ohos.fileExtensionInfo | DeviceType | DEVICE_EXTERNAL_USB | Added| +| ohos.fileExtensionInfo | DeviceType | DEVICE_EXTERNAL_MTP | Added| +| ohos.fileExtensionInfo | DeviceType | DEVICE_NETWORK_NEIGHBORHOODS | Added| +| ohos.fileExtensionInfo | DeviceType | DEVICE_SHARED_TERMINAL | Added| +| ohos.fileExtensionInfo | DeviceType | DEVICE_SHARED_DISK | Added| +| ohos.fileExtensionInfo | DeviceType | DEVICE_LOCAL_DISK = 1 | Added| +| ohos.filemanagement.userfile_manager | VirtualAlbum | getFileAssets(type: Array\, options: MediaFetchOptions, callback: AsyncCallback\): void;
getFileAssets(type: Array\, options: MediaFetchOptions): Promise\; | Added| +| ohos.filemanagement.userfile_manager | VirtualAlbumType | TYPE_TRASH | Added| +| ohos.filemanagement.userfile_manager | VirtualAlbumType | TYPE_FAVORITE | Added| +| ohos.filemanagement.userfile_manager | PeerInfo | readonly isOnline: boolean; | Added| +| ohos.filemanagement.userfile_manager | PeerInfo | readonly networkId: string; | Added| +| ohos.filemanagement.userfile_manager | PeerInfo | readonly deviceName: string; | Added| +| ohos.filemanagement.userfile_manager | Size | height: number; | Added| +| ohos.filemanagement.userfile_manager | Size | width: number; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | release(callback: AsyncCallback\): void;
release(): Promise\; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | getAllPeers(callback: AsyncCallback\>): void;
getAllPeers(): Promise\>; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | getActivePeers(callback: AsyncCallback\>): void;
getActivePeers(): Promise\>; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | getPrivateAlbum(type: VirtualAlbumType, callback: AsyncCallback\>): void;
getPrivateAlbum(type: VirtualAlbumType): Promise\>; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | getAlbums(type: Array\, options: MediaFetchOptions, callback: AsyncCallback\>): void;
getAlbums(type: Array\, options: MediaFetchOptions): Promise\>; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | deleteAsset(uri: string, callback: AsyncCallback\): void;
deleteAsset(uri: string): Promise\; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback\): void;
createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise\; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | getFileAssets(type: Array\, options: MediaFetchOptions, callback: AsyncCallback\): void;
getFileAssets(type: Array\, options: MediaFetchOptions): Promise\; | Added| +| ohos.filemanagement.userfile_manager | UserFileManager | getPublicDirectory(type: DirectoryType, callback: AsyncCallback\): void;
getPublicDirectory(type: DirectoryType): Promise\; | Added| +| ohos.filemanagement.userfile_manager | DirectoryType | DIR_DOWNLOAD | Added| +| ohos.filemanagement.userfile_manager | DirectoryType | DIR_DOCUMENTS | Added| +| ohos.filemanagement.userfile_manager | DirectoryType | DIR_AUDIO | Added| +| ohos.filemanagement.userfile_manager | DirectoryType | DIR_IMAGE | Added| +| ohos.filemanagement.userfile_manager | DirectoryType | DIR_VIDEO | Added| +| ohos.filemanagement.userfile_manager | DirectoryType | DIR_CAMERA = 0 | Added| +| ohos.filemanagement.userfile_manager | Album | getFileAssets(type: Array\, callback: AsyncCallback\): void;
getFileAssets(type: Array\, options: MediaFetchOptions, callback: AsyncCallback\): void;
getFileAssets(type: Array\, options?: MediaFetchOptions): Promise\; | Added| +| ohos.filemanagement.userfile_manager | Album | commitModify(callback: AsyncCallback\): void;
commitModify(): Promise\; | Added| +| ohos.filemanagement.userfile_manager | Album | readonly coverUri: string; | Added| +| ohos.filemanagement.userfile_manager | Album | readonly relativePath: string; | Added| +| ohos.filemanagement.userfile_manager | Album | readonly count: number; | Added| +| ohos.filemanagement.userfile_manager | Album | readonly dateModified: number; | Added| +| ohos.filemanagement.userfile_manager | Album | readonly albumUri: string; | Added| +| ohos.filemanagement.userfile_manager | Album | albumName: string; | Added| +| ohos.filemanagement.userfile_manager | FetchFileResult | getPositionObject(index: number, callback: AsyncCallback\): void;
getPositionObject(index: number): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FetchFileResult | getLastObject(callback: AsyncCallback\): void;
getLastObject(): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FetchFileResult | getNextObject(callback: AsyncCallback\): void;
getNextObject(): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FetchFileResult | getFirstObject(callback: AsyncCallback\): void;
getFirstObject(): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FetchFileResult | close(): void; | Added| +| ohos.filemanagement.userfile_manager | FetchFileResult | isAfterLast(): boolean; | Added| +| ohos.filemanagement.userfile_manager | FetchFileResult | getCount(): number; | Added| +| ohos.filemanagement.userfile_manager | MediaFetchOptions | selectionArgs: Array\; | Added| +| ohos.filemanagement.userfile_manager | MediaFetchOptions | selections: string; | Added| +| ohos.filemanagement.userfile_manager | AlbumKey | DATE_MODIFIED = "date_modified" | Added| +| ohos.filemanagement.userfile_manager | AlbumKey | DATE_ADDED = "date_added" | Added| +| ohos.filemanagement.userfile_manager | AlbumKey | DISPLAY_NAME = "display_name" | Added| +| ohos.filemanagement.userfile_manager | AlbumKey | RELATIVE_PATH = "relative_path" | Added| +| ohos.filemanagement.userfile_manager | AlbumKey | URI = "uri" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | DATE_TAKEN = "date_taken" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | HEIGHT = "height" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | WIDTH = "width" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | DURATION = "duration" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | TITLE = "title" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | DATE_MODIFIED = "date_modified" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | DATE_ADDED = "date_added" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | DISPLAY_NAME = "display_name" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | RELATIVE_PATH = "relative_path" | Added| +| ohos.filemanagement.userfile_manager | ImageVideoKey | URI = "uri" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | DURATION = "duration" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | AUDIOALBUM = "audio_album" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | ARTIST = "artist" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | TITLE = "title" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | DATE_MODIFIED = "date_modified" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | DATE_ADDED = "date_added" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | DISPLAY_NAME = "display_name" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | RELATIVE_PATH = "relative_path" | Added| +| ohos.filemanagement.userfile_manager | AudioKey | URI = "uri" | Added| +| ohos.filemanagement.userfile_manager | FileKey | TITLE = "title" | Added| +| ohos.filemanagement.userfile_manager | FileKey | DATE_MODIFIED = "date_modified" | Added| +| ohos.filemanagement.userfile_manager | FileKey | DATE_ADDED = "date_added" | Added| +| ohos.filemanagement.userfile_manager | FileKey | DISPLAY_NAME = "display_name" | Added| +| ohos.filemanagement.userfile_manager | FileKey | RELATIVE_PATH = "relative_path" | Added| +| ohos.filemanagement.userfile_manager | FileKey | URI = "uri" | Added| +| ohos.filemanagement.userfile_manager | FileAsset | isTrash(callback: AsyncCallback\): void;
isTrash():Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | trash(isTrash: boolean, callback: AsyncCallback\): void;
trash(isTrash: boolean): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | isFavorite(callback: AsyncCallback\): void;
isFavorite():Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | favorite(isFavorite: boolean, callback: AsyncCallback\): void;
favorite(isFavorite: boolean): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | getThumbnail(callback: AsyncCallback\): void;
getThumbnail(size: Size, callback: AsyncCallback\): void;
getThumbnail(size?: Size): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | close(fd: number, callback: AsyncCallback\): void;
close(fd: number): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | open(mode: string, callback: AsyncCallback\): void;
open(mode: string): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | commitModify(callback: AsyncCallback\): void;
commitModify(): Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | isDirectory(callback: AsyncCallback\): void;
isDirectory():Promise\; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | displayName: string; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | readonly mediaType: MediaType; | Added| +| ohos.filemanagement.userfile_manager | FileAsset | readonly uri: string; | Added| +| ohos.filemanagement.userfile_manager | MediaType | AUDIO | Added| +| ohos.filemanagement.userfile_manager | MediaType | VIDEO | Added| +| ohos.filemanagement.userfile_manager | MediaType | IMAGE | Added| +| ohos.filemanagement.userfile_manager | MediaType | FILE = 0 | Added| +| ohos.filemanagement.userfile_manager | userfile_manager | getUserFileMgr(): UserFileManager;
getUserFileMgr(context: Context): UserFileManager; | Added| +| ohos.document | document | show(uri: string, type: string): Promise\;
show(uri: string, type: string, callback: AsyncCallback\): void; | Deprecated| +| ohos.document | document | choose(types?: string[]): Promise\;
choose(callback: AsyncCallback\): void;
choose(types: string[], callback: AsyncCallback\): void; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-global.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-global.md new file mode 100644 index 0000000000000000000000000000000000000000..3ca428157d60b36b5185c9ed33ee1690acabf0e6 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-global.md @@ -0,0 +1,30 @@ +# JS API Changes of the Globalization Subsystem + +The table below lists the APIs changes of the globalization subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.i18n | Unicode | static getType(char: string): string; | Added| +| ohos.i18n | Unicode | static isUpperCase(char: string): boolean; | Added| +| ohos.i18n | Unicode | static isLowerCase(char: string): boolean; | Added| +| ohos.i18n | Unicode | static isLetter(char: string): boolean; | Added| +| ohos.i18n | Unicode | static isIdeograph(char: string): boolean; | Added| +| ohos.i18n | Unicode | static isRTL(char: string): boolean; | Added| +| ohos.i18n | Unicode | static isWhitespace(char: string): boolean; | Added| +| ohos.i18n | Unicode | static isSpaceChar(char: string): boolean; | Added| +| ohos.i18n | Unicode | static isDigit(char: string): boolean; | Added| +| ohos.i18n | I18NUtil | static getDateOrder(locale: string): string; | Added| +| ohos.i18n | I18NUtil | static unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string; | Added| +| ohos.i18n | Util | getDateOrder(locale: string): string; | Deleted| +| ohos.i18n | Character | getType(char: string): string; | Deprecated| +| ohos.i18n | Character | isUpperCase(char: string): boolean; | Deprecated| +| ohos.i18n | Character | isLowerCase(char: string): boolean; | Deprecated| +| ohos.i18n | Character | isLetter(char: string): boolean; | Deprecated| +| ohos.i18n | Character | isIdeograph(char: string): boolean; | Deprecated| +| ohos.i18n | Character | isRTL(char: string): boolean; | Deprecated| +| ohos.i18n | Character | isWhitespace(char: string): boolean; | Deprecated| +| ohos.i18n | Character | isSpaceChar(char: string): boolean; | Deprecated| +| ohos.i18n | Character | isDigit(char: string): boolean; | Deprecated| +| ohos.i18n | Util | unitConvert(fromUnit: UnitInfo, toUnit: UnitInfo, value: number, locale: string, style?: string): string; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-graphic.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-graphic.md new file mode 100644 index 0000000000000000000000000000000000000000..25b05accf7b5b384560b189f05a2dbd6316d2af8 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-graphic.md @@ -0,0 +1,26 @@ +# JS API Changes of the Graphics Subsystem + +The table below lists the APIs changes of the graphics subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.graphics.colorSpaceManager | colorSpaceManager | function create(colorSpaceName: ColorSpace): ColorSpaceManager;
function create(primaries: ColorSpacePrimaries, gamma: number): ColorSpaceManager; | Added| +| ohos.graphics.colorSpaceManager | ColorSpaceManager | getGamma(): number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpaceManager | getWhitePoint(): Array\; | Added| +| ohos.graphics.colorSpaceManager | ColorSpaceManager | getColorSpaceName(): ColorSpace; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | whitePointY: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | whitePointX: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | blueY: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | blueX: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | greenY: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | greenX: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | redY: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpacePrimaries | redX: number; | Added| +| ohos.graphics.colorSpaceManager | ColorSpace | CUSTOM = 5 | Added| +| ohos.graphics.colorSpaceManager | ColorSpace | SRGB = 4 | Added| +| ohos.graphics.colorSpaceManager | ColorSpace | DISPLAY_P3 = 3 | Added| +| ohos.graphics.colorSpaceManager | ColorSpace | DCI_P3 = 2 | Added| +| ohos.graphics.colorSpaceManager | ColorSpace | ADOBE_RGB_1998 = 1 | Added| +| ohos.graphics.colorSpaceManager | ColorSpace | UNKNOWN = 0 | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-misc.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-misc.md new file mode 100644 index 0000000000000000000000000000000000000000..988537f0b74ee8995461dae573876691aa56f0e0 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-misc.md @@ -0,0 +1,76 @@ +# JS API Changes of the Misc Services Subsystem + +The table below lists the APIs changes of the Misc services subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Method/Event| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.inputmethod | InputMethodController | hideSoftKeyboard(callback: AsyncCallback\): void;
hideSoftKeyboard():Promise\; | Added| +| ohos.inputmethod | InputMethodController | showSoftKeyboard(callback: AsyncCallback\): void;
showSoftKeyboard():Promise\; | Added| +| ohos.inputmethod | inputMethod | getCurrentInputMethod(): InputMethodProperty; | Added| +| ohos.inputmethodengine | TextInputClient | moveCursor(direction: number, callback: AsyncCallback\): void;
moveCursor(direction: number): Promise\; | Added| +| ohos.inputmethodengine | InputMethodEngine | off(type: 'setCallingWindow', callback: (wid:number) => void): void; | Added| +| ohos.inputmethodengine | InputMethodEngine | on(type: 'setCallingWindow', callback: (wid:number) => void): void; | Added| +| ohos.inputmethodengine | InputMethodEngine | off(type: 'inputStop', callback: () => void): void; | Added| +| ohos.inputmethodengine | InputMethodEngine | on(type: 'inputStop', callback: () => void): void; | Added| +| ohos.inputmethodengine | inputMethodEngine | const WINDOW_TYPE_INPUT_METHOD_FLOAT: number; | Added| +| ohos.inputmethodengine | inputMethodEngine | const CURSOR_RIGHT: number; | Added| +| ohos.inputmethodengine | inputMethodEngine | const CURSOR_LEFT: number; | Added| +| ohos.inputmethodengine | inputMethodEngine | const CURSOR_DOWN: number; | Added| +| ohos.inputmethodengine | inputMethodEngine | const CURSOR_UP: number; | Added| +| ohos.inputmethodextensionability | InputMethodExtensionAbility | onDestroy(): void; | Added| +| ohos.inputmethodextensionability | InputMethodExtensionAbility | onCreate(want: Want): void; | Added| +| ohos.inputmethodextensionability | InputMethodExtensionAbility | context: InputMethodExtensionContext; | Added| +| ohos.inputmethodextensioncontext | InputMethodExtensionContext | terminateSelf(callback: AsyncCallback\): void;
terminateSelf(): Promise\; | Added| +| ohos.inputmethodextensioncontext | InputMethodExtensionContext | startAbility(want: Want, callback: AsyncCallback\): void;
startAbility(want: Want, options: StartOptions, callback: AsyncCallback\): void;
startAbility(want: Want, options?: StartOptions): Promise\; | Added| +| ohos.pasteboard | PasteData | setProperty(property: PasteDataProperty): void; | Added| +| ohos.pasteboard | PasteData | getPrimaryPixelMap(): image.PixelMap; | Added| +| ohos.pasteboard | PasteData | addPixelMapRecord(pixelMap: image.PixelMap): void; | Added| +| ohos.pasteboard | PasteDataRecord | data: { [mimeType: string]: ArrayBuffer } | Added | +| ohos.pasteboard | PasteDataRecord | pixelMap: image.PixelMap; | Added| +| ohos.pasteboard | PasteDataProperty | shareOption: ShareOption; | Added| +| ohos.pasteboard | ShareOption | CrossDevice | Added| +| ohos.pasteboard | ShareOption | LocalDevice | Added| +| ohos.pasteboard | ShareOption | InApp | Added| +| ohos.pasteboard | pasteboard | createRecord(mimeType: string, value: ArrayBuffer):PasteDataRecord; | Added| +| ohos.pasteboard | pasteboard | createPixelMapRecord(pixelMap: image.PixelMap):PasteDataRecord; | Added| +| ohos.pasteboard | pasteboard | createData(mimeType: string, value: ArrayBuffer): PasteData; | Added| +| ohos.pasteboard | pasteboard | createPixelMapData(pixelMap: image.PixelMap): PasteData; | Added| +| ohos.pasteboard | pasteboard | const MIMETYPE_PIXELMAP: string; | Added| +| ohos.request | UploadTask | off(type:'complete' \| 'fail', callback?: Callback\>): void; | Added| +| ohos.request | UploadTask | off(type:'complete' \| 'fail', callback?: Callback\>): void; | Added| +| ohos.request | UploadTask | on(type:'complete' \| 'fail', callback: Callback\>): void; | Added| +| ohos.request | UploadTask | on(type:'complete' \| 'fail', callback: Callback\>): void; | Added| +| ohos.request | TaskState | message: string; | Added| +| ohos.request | TaskState | responseCode: number; | Added| +| ohos.request | TaskState | path: string; | Added| +| ohos.request | DownloadConfig | background?: boolean; | Added| +| ohos.screenLock | screenLock | onSystemEvent(callback: Callback\): boolean; | Added| +| ohos.screenLock | SystemEvent | params: string | Added| +| ohos.screenLock | SystemEvent | eventType: EventType, | Added| +| ohos.screenLock | screenLock | lockScreen(callback: AsyncCallback\): void;
lockScreen():Promise\; | Added| +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | off(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation' \| 'screenlockEnabled' \| 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted | +| ohos.screenLock | screenLock | on(type: 'screenlockEnabled', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginSleep' \| 'endSleep' \| 'changeUser', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| +| ohos.screenLock | screenLock | on(type: 'beginWakeUp' \| 'endWakeUp' \| 'beginScreenOn' \| 'endScreenOn' \| 'beginScreenOff' \| 'endScreenOff' \| 'unlockScreen' \| 'beginExitAnimation', callback: Callback\): void; | Deleted| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-multi-modal-input.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-multi-modal-input.md new file mode 100644 index 0000000000000000000000000000000000000000..f530fe5c33411dd8f74ea286d868bb942220d84a --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-multi-modal-input.md @@ -0,0 +1,64 @@ +# JS API Changes of the Multimodal Input Subsystem + +The table below lists the APIs changes of the multimodal input subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.multimodalInput.inputDeviceCooperate | inputDeviceCooperate | off(type: 'cooperation', callback?: AsyncCallback\): void; | Added| +| ohos.multimodalInput.inputDeviceCooperate | inputDeviceCooperate | on(type: 'cooperation', callback: AsyncCallback\<{ deviceDescriptor: string, eventMsg: EventMsg }>): void; | Added| +| ohos.multimodalInput.inputDeviceCooperate | inputDeviceCooperate | getState(deviceDescriptor: string, callback: AsyncCallback\<{ state: boolean }>): void;
getState(deviceDescriptor: string): Promise\<{ state: boolean }>; | Added| +| ohos.multimodalInput.inputDeviceCooperate | inputDeviceCooperate | stop(callback: AsyncCallback\): void;
stop(): Promise\; | Added| +| ohos.multimodalInput.inputDeviceCooperate | inputDeviceCooperate | start(sinkDeviceDescriptor: string, srcInputDeviceId: number, callback: AsyncCallback\): void;
start(sinkDeviceDescriptor: string, srcInputDeviceId: number): Promise\; | Added| +| ohos.multimodalInput.inputDeviceCooperate | inputDeviceCooperate | enable(enable: boolean, callback: AsyncCallback\): void;
enable(enable: boolean): Promise\; | Added| +| ohos.multimodalInput.inputDeviceCooperate | EventMsg | MSG_COOPERATE_STATE_OFF = 501 | Added| +| ohos.multimodalInput.inputDeviceCooperate | EventMsg | MSG_COOPERATE_STATE_ON = 500 | Added| +| ohos.multimodalInput.inputDeviceCooperate | EventMsg | MSG_COOPERATE_INFO_FAIL = 202 | Added| +| ohos.multimodalInput.inputDeviceCooperate | EventMsg | MSG_COOPERATE_INFO_SUCCESS = 201 | Added| +| ohos.multimodalInput.inputDeviceCooperate | EventMsg | MSG_COOPERATE_INFO_START = 200 | Added| +| ohos.multimodalInput.pointer | pointer | isPointerVisible(callback: AsyncCallback\): void;
isPointerVisible(): Promise\; | Added| +| ohos.multimodalInput.pointer | pointer | setPointerVisible(visible: boolean, callback: AsyncCallback\): void;
setPointerVisible(visible: boolean): Promise\; | Added| +| ohos.multimodalInput.pointer | pointer | getPointerStyle(windowId: number, callback: AsyncCallback\): void;
getPointerStyle(windowId: number): Promise\; | Added| +| ohos.multimodalInput.pointer | pointer | setPointerStyle(windowId: number, pointerStyle: PointerStyle, callback: AsyncCallback\): void;
setPointerStyle(windowId: number, pointerStyle: PointerStyle): Promise\; | Added| +| ohos.multimodalInput.pointer | pointer | getPointerSpeed(callback: AsyncCallback\): void;
getPointerSpeed(): Promise\; | Added| +| ohos.multimodalInput.pointer | pointer | setPointerSpeed(speed: number, callback: AsyncCallback\): void;
setPointerSpeed(speed: number): Promise\; | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_NORTH_SOUTH_WEST_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_SOUTH_WEST | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_SOUTH_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_NORTH_WEST | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_NORTH_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_NORTH_SOUTH | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_NORTH | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_SOUTH | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_WEST | Added| +| ohos.multimodalInput.pointer | PointerStyle | MIDDLE_BTN_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | ZOOM_OUT | Added| +| ohos.multimodalInput.pointer | PointerStyle | ZOOM_IN | Added| +| ohos.multimodalInput.pointer | PointerStyle | TEXT_CURSOR | Added| +| ohos.multimodalInput.pointer | PointerStyle | SCREENSHOT_CURSOR | Added| +| ohos.multimodalInput.pointer | PointerStyle | SCREENSHOT_CHOOSE | Added| +| ohos.multimodalInput.pointer | PointerStyle | RESIZE_UP_DOWN | Added| +| ohos.multimodalInput.pointer | PointerStyle | RESIZE_LEFT_RIGHT | Added| +| ohos.multimodalInput.pointer | PointerStyle | MOVE | Added| +| ohos.multimodalInput.pointer | PointerStyle | HELP | Added| +| ohos.multimodalInput.pointer | PointerStyle | HAND_POINTING | Added| +| ohos.multimodalInput.pointer | PointerStyle | HAND_OPEN | Added| +| ohos.multimodalInput.pointer | PointerStyle | HAND_GRABBING | Added| +| ohos.multimodalInput.pointer | PointerStyle | COLOR_SUCKER | Added| +| ohos.multimodalInput.pointer | PointerStyle | CURSOR_FORBID | Added| +| ohos.multimodalInput.pointer | PointerStyle | CURSOR_COPY | Added| +| ohos.multimodalInput.pointer | PointerStyle | CROSS | Added| +| ohos.multimodalInput.pointer | PointerStyle | NORTH_WEST_SOUTH_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | NORTH_EAST_SOUTH_WEST | Added| +| ohos.multimodalInput.pointer | PointerStyle | SOUTH_WEST | Added| +| ohos.multimodalInput.pointer | PointerStyle | SOUTH_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | NORTH_WEST | Added| +| ohos.multimodalInput.pointer | PointerStyle | NORTH_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | NORTH_SOUTH | Added| +| ohos.multimodalInput.pointer | PointerStyle | WEST_EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | NORTH | Added| +| ohos.multimodalInput.pointer | PointerStyle | SOUTH | Added| +| ohos.multimodalInput.pointer | PointerStyle | WEST | Added| +| ohos.multimodalInput.pointer | PointerStyle | EAST | Added| +| ohos.multimodalInput.pointer | PointerStyle | DEFAULT | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-multimedia.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-multimedia.md new file mode 100644 index 0000000000000000000000000000000000000000..920377c9394ca7cd3c1b5c138c1ec7dae4a33b58 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-multimedia.md @@ -0,0 +1,164 @@ +# JS API Changes of the Multimedia Subsystem + +The table below lists the APIs changes of the multimedia subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.multimedia.audio | VolumeEvent | networkId: string; | Added| +| ohos.multimedia.audio | VolumeEvent | volumeGroupId: number; | Added| +| ohos.multimedia.audio | AudioDeviceDescriptor | readonly volumeGroupId: number; | Added| +| ohos.multimedia.audio | AudioDeviceDescriptor | readonly interruptGroupId: number; | Added| +| ohos.multimedia.audio | AudioDeviceDescriptor | readonly networkId: string; | Added| +| ohos.multimedia.audio | VolumeGroupInfo | readonly type: ConnectType; | Added| +| ohos.multimedia.audio | VolumeGroupInfo | readonly groupName: string; | Added| +| ohos.multimedia.audio | VolumeGroupInfo | readonly mappingId: number; | Added| +| ohos.multimedia.audio | VolumeGroupInfo | readonly groupId: number; | Added| +| ohos.multimedia.audio | VolumeGroupInfo | readonly networkId: string; | Added| +| ohos.multimedia.audio | ConnectType | CONNECT_TYPE_DISTRIBUTED = 2 | Added| +| ohos.multimedia.audio | ConnectType | CONNECT_TYPE_LOCAL = 1 | Added| +| ohos.multimedia.audio | AudioGroupManager | isMute(volumeType: AudioVolumeType, callback: AsyncCallback\): void;
isMute(volumeType: AudioVolumeType): Promise\; | Added| +| ohos.multimedia.audio | AudioGroupManager | mute(volumeType: AudioVolumeType, mute: boolean, callback: AsyncCallback\): void;
mute(volumeType: AudioVolumeType, mute: boolean): Promise\; | Added| +| ohos.multimedia.audio | AudioGroupManager | getMaxVolume(volumeType: AudioVolumeType, callback: AsyncCallback\): void;
getMaxVolume(volumeType: AudioVolumeType): Promise\; | Added| +| ohos.multimedia.audio | AudioGroupManager | getMinVolume(volumeType: AudioVolumeType, callback: AsyncCallback\): void;
getMinVolume(volumeType: AudioVolumeType): Promise\; | Added| +| ohos.multimedia.audio | AudioGroupManager | getVolume(volumeType: AudioVolumeType, callback: AsyncCallback\): void;
getVolume(volumeType: AudioVolumeType): Promise\; | Added| +| ohos.multimedia.audio | AudioGroupManager | setVolume(volumeType: AudioVolumeType, volume: number, callback: AsyncCallback\): void;
setVolume(volumeType: AudioVolumeType, volume: number): Promise\; | Added| +| ohos.multimedia.audio | AudioRoutingManager | selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback\): void;
selectOutputDeviceByFilter(filter: AudioRendererFilter, outputAudioDevices: AudioDeviceDescriptors): Promise\; | Added| +| ohos.multimedia.audio | AudioRoutingManager | selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors, callback: AsyncCallback\): void;
selectOutputDevice(outputAudioDevices: AudioDeviceDescriptors): Promise\; | Added| +| ohos.multimedia.audio | AudioRoutingManager | off(type: 'deviceChange', callback?: Callback\): void; | Added| +| ohos.multimedia.audio | AudioRoutingManager | on(type: 'deviceChange', deviceFlag: DeviceFlag, callback: Callback\): void; | Added| +| ohos.multimedia.audio | AudioRoutingManager | getDevices(deviceFlag: DeviceFlag, callback: AsyncCallback\): void;
getDevices(deviceFlag: DeviceFlag): Promise\; | Added| +| ohos.multimedia.audio | AudioManager | getRoutingManager(callback: AsyncCallback\): void;
getRoutingManager(): Promise\; | Added| +| ohos.multimedia.audio | AudioManager | getGroupManager(groupId: number, callback: AsyncCallback\): void;
getGroupManager(groupId: number): Promise\; | Added| +| ohos.multimedia.audio | AudioManager | getVolumeGroups(networkId: string, callback: AsyncCallback\): void;
getVolumeGroups(networkId: string): Promise\; | Added| +| ohos.multimedia.audio | AudioRendererFilter | rendererId?: number; | Added| +| ohos.multimedia.audio | AudioRendererFilter | rendererInfo?: AudioRendererInfo; | Added| +| ohos.multimedia.audio | AudioRendererFilter | uid: number; | Added| +| ohos.multimedia.audio | DeviceType | DEFAULT = 1000 | Added| +| ohos.multimedia.audio | DeviceFlag | ALL_DISTRIBUTED_DEVICES_FLAG = 12 | Added| +| ohos.multimedia.audio | DeviceFlag | DISTRIBUTED_INPUT_DEVICES_FLAG = 8 | Added| +| ohos.multimedia.audio | DeviceFlag | DISTRIBUTED_OUTPUT_DEVICES_FLAG = 4 | Added| +| ohos.multimedia.audio | DeviceFlag | NONE_DEVICES_FLAG = 0 | Added| +| ohos.multimedia.audio | audio | const LOCAL_NETWORK_ID: string; | Added| +| ohos.multimedia.image | PixelMapFormat | BGRA_8888 = 4 | Added| +| ohos.multimedia.media | VideoPlayer | on(type: 'availableBitratesCollect', callback: (bitrates: Array\) => void): void; | Added| +| ohos.multimedia.media | VideoPlayer | on(type: 'availableBitratesCollected', callback: (bitrates: Array\) => void): void | Deleted| +| ohos.multimedia.mediaLibrary | DeviceType | TYPE_TV | Deprecated| +| ohos.multimedia.mediaLibrary | DeviceType | TYPE_CAR | Deprecated| +| ohos.multimedia.mediaLibrary | DeviceType | TYPE_WATCH | Deprecated| +| ohos.multimedia.mediaLibrary | DeviceType | TYPE_TABLET | Deprecated| +| ohos.multimedia.mediaLibrary | DeviceType | TYPE_PHONE | Deprecated| +| ohos.multimedia.mediaLibrary | DeviceType | TYPE_LAPTOP | Deprecated| +| ohos.multimedia.mediaLibrary | DeviceType | TYPE_UNKNOWN = 0 | Deprecated| +| ohos.multimedia.mediaLibrary | PeerInfo | readonly isOnline: boolean; | Deprecated| +| ohos.multimedia.mediaLibrary | PeerInfo | readonly deviceType: DeviceType; | Deprecated| +| ohos.multimedia.mediaLibrary | PeerInfo | readonly networkId: string; | Deprecated| +| ohos.multimedia.mediaLibrary | PeerInfo | readonly deviceName: string; | Deprecated| +| ohos.multimedia.mediaLibrary | Size | height: number; | Deprecated| +| ohos.multimedia.mediaLibrary | Size | width: number; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | release(callback: AsyncCallback\): void;
release(): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | getAllPeers(callback: AsyncCallback\>): void;
getAllPeers(): Promise\>; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | getActivePeers(callback: AsyncCallback\>): void;
getActivePeers(): Promise\>; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | getAlbums(options: MediaFetchOptions, callback: AsyncCallback\>): void;
getAlbums(options: MediaFetchOptions): Promise\>; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | deleteAsset(uri: string, callback: AsyncCallback\): void;
deleteAsset(uri: string): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | createAsset(mediaType: MediaType, displayName: string, relativePath: string, callback: AsyncCallback\): void;
createAsset(mediaType: MediaType, displayName: string, relativePath: string): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | off(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback?: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | on(type: 'deviceChange'\|'albumChange'\|'imageChange'\|'audioChange'\|'videoChange'\|'fileChange'\|'remoteFileChange', callback: Callback\): void; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | getFileAssets(options: MediaFetchOptions, callback: AsyncCallback\): void;
getFileAssets(options: MediaFetchOptions): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaLibrary | getPublicDirectory(type: DirectoryType, callback: AsyncCallback\): void;
getPublicDirectory(type: DirectoryType): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | DirectoryType | DIR_DOWNLOAD | Deprecated| +| ohos.multimedia.mediaLibrary | DirectoryType | DIR_DOCUMENTS | Deprecated| +| ohos.multimedia.mediaLibrary | DirectoryType | DIR_AUDIO | Deprecated| +| ohos.multimedia.mediaLibrary | DirectoryType | DIR_IMAGE | Deprecated| +| ohos.multimedia.mediaLibrary | DirectoryType | DIR_VIDEO | Deprecated| +| ohos.multimedia.mediaLibrary | DirectoryType | DIR_CAMERA = 0 | Deprecated| +| ohos.multimedia.mediaLibrary | Album | getFileAssets(callback: AsyncCallback\): void;
getFileAssets(options: MediaFetchOptions, callback: AsyncCallback\): void;
getFileAssets(options?: MediaFetchOptions): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | commitModify(callback: AsyncCallback\): void;
commitModify(): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | readonly coverUri: string; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | readonly relativePath: string; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | readonly count: number; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | readonly dateModified: number; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | readonly albumUri: string; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | albumName: string; | Deprecated| +| ohos.multimedia.mediaLibrary | Album | readonly albumId: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | getAllObject(callback: AsyncCallback\>): void;
getAllObject(): Promise\>; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | getPositionObject(index: number, callback: AsyncCallback\): void;
getPositionObject(index: number): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | getLastObject(callback: AsyncCallback\): void;
getLastObject(): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | getNextObject(callback: AsyncCallback\): void;
getNextObject(): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | getFirstObject(callback: AsyncCallback\): void;
getFirstObject(): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | close(): void; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | isAfterLast(): boolean; | Deprecated| +| ohos.multimedia.mediaLibrary | FetchFileResult | getCount(): number; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaFetchOptions | extendArgs?: string; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaFetchOptions | networkId?: string; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaFetchOptions | uri?: string; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaFetchOptions | order?: string; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaFetchOptions | selectionArgs: Array\; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaFetchOptions | selections: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | ALBUM_NAME = "bucket_display_name" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | ALBUM_ID = "bucket_id" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | ORIENTATION = "orientation" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | HEIGHT = "height" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | WIDTH = "width" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | DURATION = "duration" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | AUDIOALBUM = "audio_album" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | ARTIST = "artist" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | TITLE = "title" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | DATE_TAKEN = "date_taken" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | DATE_MODIFIED = "date_modified" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | DATE_ADDED = "date_added" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | SIZE = "size" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | MEDIA_TYPE = "media_type" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | MIME_TYPE = "mime_type" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | PARENT = "parent" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | DISPLAY_NAME = "display_name" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | RELATIVE_PATH = "relative_path" | Deprecated| +| ohos.multimedia.mediaLibrary | FileKey | ID = "file_id" | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | isTrash(callback: AsyncCallback\): void;
isTrash():Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | trash(isTrash: boolean, callback: AsyncCallback\): void;
trash(isTrash: boolean): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | isFavorite(callback: AsyncCallback\): void;
isFavorite():Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | favorite(isFavorite: boolean, callback: AsyncCallback\): void;
favorite(isFavorite: boolean): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | getThumbnail(callback: AsyncCallback\): void;
getThumbnail(size: Size, callback: AsyncCallback\): void;
getThumbnail(size?: Size): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | close(fd: number, callback: AsyncCallback\): void;
close(fd: number): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | open(mode: string, callback: AsyncCallback\): void;
open(mode: string): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | commitModify(callback: AsyncCallback\): void;
commitModify(): Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | isDirectory(callback: AsyncCallback\): void;
isDirectory():Promise\; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly albumName: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly albumUri: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly albumId: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly duration: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | orientation: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly height: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly width: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly audioAlbum: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly artist: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly dateTaken: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly dateModified: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly dateAdded: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly size: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly parent: number; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | relativePath: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | title: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | displayName: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly mediaType: MediaType; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly mimeType: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly uri: string; | Deprecated| +| ohos.multimedia.mediaLibrary | FileAsset | readonly id: number; | Deprecated| +| ohos.multimedia.mediaLibrary | MediaType | AUDIO | Deprecated| +| ohos.multimedia.mediaLibrary | MediaType | VIDEO | Deprecated| +| ohos.multimedia.mediaLibrary | MediaType | IMAGE | Deprecated| +| ohos.multimedia.mediaLibrary | MediaType | FILE = 0 | Deprecated| +| ohos.multimedia.mediaLibrary | mediaLibrary | getMediaLibrary(): MediaLibrary;
getMediaLibrary(context: Context): MediaLibrary; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-resource-scheduler.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-resource-scheduler.md new file mode 100644 index 0000000000000000000000000000000000000000..7b4510f9c5688b404598f363989c2dfbc3e5e988 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-resource-scheduler.md @@ -0,0 +1,24 @@ +# JS API Changes of the Resource Scheduler Subsystem + +The table below lists the APIs changes of the resource scheduler subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.backgroundTaskManager | EfficiencyResourcesRequest | reason: string; | Added| +| ohos.backgroundTaskManager | EfficiencyResourcesRequest | isProcess?: boolean; | Added| +| ohos.backgroundTaskManager | EfficiencyResourcesRequest | isPersist?: boolean; | Added| +| ohos.backgroundTaskManager | EfficiencyResourcesRequest | timeOut: number; | Added| +| ohos.backgroundTaskManager | EfficiencyResourcesRequest | isApply: boolean; | Added| +| ohos.backgroundTaskManager | EfficiencyResourcesRequest | resourceTypes: number; | Added| +| ohos.backgroundTaskManager | ResourceType | AUDIO = 1 << 6 | Added| +| ohos.backgroundTaskManager | ResourceType | GPS = 1 << 5 | Added| +| ohos.backgroundTaskManager | ResourceType | BLUETOOTH = 1 << 4 | Added| +| ohos.backgroundTaskManager | ResourceType | WORK_SCHEDULER = 1 << 3 | Added| +| ohos.backgroundTaskManager | ResourceType | TIMER = 1 << 2 | Added| +| ohos.backgroundTaskManager | ResourceType | COMMON_EVENT = 1 << 1 | Added| +| ohos.backgroundTaskManager | ResourceType | CPU = 1 | Added| +| ohos.backgroundTaskManager | backgroundTaskManager | resetAllEfficiencyResources(): void; | Added| +| ohos.backgroundTaskManager | backgroundTaskManager | applyEfficiencyResources(request: EfficiencyResourcesRequest): boolean; | Added| +| ohos.workScheduler | WorkInfo | parameters?: {[key: string]: any}; | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-security.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-security.md new file mode 100644 index 0000000000000000000000000000000000000000..5eab2fdf3de8c8642f92ef2e49ee3e5f1cef43ce --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-security.md @@ -0,0 +1,163 @@ +# JS API Changes of the Security Subsystem + +The table below lists the APIs changes of the security subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.privacyManager | ActiveChangeResponse | activeStatus: PermissionActiveStatus; | Added| +| ohos.privacyManager | ActiveChangeResponse | deviceId: string; | Added| +| ohos.privacyManager | ActiveChangeResponse | permissionName: string; | Added| +| ohos.privacyManager | ActiveChangeResponse | tokenId: number; | Added| +| ohos.privacyManager | PermissionActiveStatus | PERM_ACTIVE_IN_BACKGROUND = 2 | Added| +| ohos.privacyManager | PermissionActiveStatus | PERM_ACTIVE_IN_FOREGROUND = 1 | Added| +| ohos.privacyManager | PermissionActiveStatus | PERM_INACTIVE = 0 | Added| +| ohos.privacyManager | privacyManager | off(type: 'activeStateChange', permissionNameList: Array\, callback?: Callback\): void; | Added| +| ohos.privacyManager | privacyManager | on(type: 'activeStateChange', permissionNameList: Array\, callback: Callback\): void; | Added| +| ohos.privacyManager | privacyManager | stopUsingPermission(tokenID: number, permissionName: string): Promise\;
stopUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback\): void; | Added| +| ohos.privacyManager | privacyManager | startUsingPermission(tokenID: number, permissionName: string): Promise\;
startUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback\): void; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createCertChainValidator(algorithm :string) : CertChainValidator; | Added| +| ohos.security.cryptoFramework | CertChainValidator | readonly algorithm : string; | Added| +| ohos.security.cryptoFramework | CertChainValidator | validate(certChain : CertChainData, callback : AsyncCallback\) : void;
validate(certChain : CertChainData) : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void;
createX509Crl(inStream : EncodingBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | X509Crl | getSignatureAlgParams() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Crl | getSignatureAlgOid() : string; | Added| +| ohos.security.cryptoFramework | X509Crl | getSignatureAlgName() : string; | Added| +| ohos.security.cryptoFramework | X509Crl | getSignature() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Crl | getTbsInfo(callback : AsyncCallback\) : void;
getTbsInfo() : Promise\; | Added| +| ohos.security.cryptoFramework | X509Crl | getRevokedCerts(callback : AsyncCallback\>) : void;
getRevokedCerts() : Promise\>; | Added| +| ohos.security.cryptoFramework | X509Crl | getRevokedCertWithCert(cert : X509Cert, callback : AsyncCallback\) : void;
getRevokedCertWithCert(cert : X509Cert) : Promise\; | Added| +| ohos.security.cryptoFramework | X509Crl | getRevokedCert(serialNumber : number, callback : AsyncCallback\) : void;
getRevokedCert(serialNumber : number) : Promise\; | Added| +| ohos.security.cryptoFramework | X509Crl | getNextUpdate() : string; | Added| +| ohos.security.cryptoFramework | X509Crl | getLastUpdate() : string; | Added| +| ohos.security.cryptoFramework | X509Crl | getIssuerName() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Crl | getVersion() : number; | Added| +| ohos.security.cryptoFramework | X509Crl | verify(key : PubKey, callback : AsyncCallback\) : void;
verify(key : PubKey) : Promise\; | Added| +| ohos.security.cryptoFramework | X509Crl | getEncoded(callback : AsyncCallback\) : void;
getEncoded() : Promise\; | Added| +| ohos.security.cryptoFramework | X509Crl | getType() : string; | Added| +| ohos.security.cryptoFramework | X509Crl | isRevoked(cert : X509Cert, callback : AsyncCallback\) : void;
isRevoked(cert : X509Cert) : Promise\; | Added| +| ohos.security.cryptoFramework | X509CrlEntry | getRevocationDate(callback : AsyncCallback\) : void;
getRevocationDate() : Promise\; | Added| +| ohos.security.cryptoFramework | X509CrlEntry | getCertIssuer(callback : AsyncCallback\) : void;
getCertIssuer() : Promise\; | Added| +| ohos.security.cryptoFramework | X509CrlEntry | getSerialNumber() : number; | Added| +| ohos.security.cryptoFramework | X509CrlEntry | getEncoded(callback : AsyncCallback\) : void;
getEncoded() : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void;
createX509Cert(inStream : EncodingBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | X509Cert | getIssuerAltNames() : DataArray; | Added| +| ohos.security.cryptoFramework | X509Cert | getSubjectAltNames() : DataArray; | Added| +| ohos.security.cryptoFramework | X509Cert | getBasicConstraints() : number; | Added| +| ohos.security.cryptoFramework | X509Cert | getExtKeyUsage() : DataArray; | Added| +| ohos.security.cryptoFramework | X509Cert | getKeyUsage() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Cert | getSignatureAlgParams() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Cert | getSignatureAlgOid() : string; | Added| +| ohos.security.cryptoFramework | X509Cert | getSignatureAlgName() : string; | Added| +| ohos.security.cryptoFramework | X509Cert | getSignature() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Cert | getNotAfterTime() : string; | Added| +| ohos.security.cryptoFramework | X509Cert | getNotBeforeTime() : string; | Added| +| ohos.security.cryptoFramework | X509Cert | getSubjectName() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Cert | getIssuerName() : DataBlob; | Added| +| ohos.security.cryptoFramework | X509Cert | getSerialNumber() : number; | Added| +| ohos.security.cryptoFramework | X509Cert | getVersion() : number; | Added| +| ohos.security.cryptoFramework | X509Cert | checkValidityWithDate(date: string, callback : AsyncCallback\) : void;
checkValidityWithDate(date: string) : Promise\; | Added| +| ohos.security.cryptoFramework | X509Cert | getPublicKey(callback : AsyncCallback\) : void;
getPublicKey() : Promise\; | Added| +| ohos.security.cryptoFramework | X509Cert | getEncoded(callback : AsyncCallback\) : void;
getEncoded() : Promise\; | Added| +| ohos.security.cryptoFramework | X509Cert | verify(key : PubKey, callback : AsyncCallback\) : void;
verify(key : PubKey) : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createKeyAgreement(algName : string) : KeyAgreement; | Added| +| ohos.security.cryptoFramework | KeyAgreement | readonly algName : string; | Added| +| ohos.security.cryptoFramework | KeyAgreement | generateSecret(priKey : PriKey, pubKey : PubKey, callback : AsyncCallback\) : void;
generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createVerify(algName : string) : Verify; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createSign(algName : string) : Sign; | Added| +| ohos.security.cryptoFramework | Verify | readonly algName : string; | Added| +| ohos.security.cryptoFramework | Verify | verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void;
verify(data : DataBlob, signatureData : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Verify | update(data : DataBlob, callback : AsyncCallback\) : void;
update(data : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Verify | init(pubKey : PubKey, callback : AsyncCallback\) : void;
init(pubKey : PubKey) : Promise\; | Added| +| ohos.security.cryptoFramework | Sign | readonly algName : string; | Added| +| ohos.security.cryptoFramework | Sign | sign(data : DataBlob, callback : AsyncCallback\) : void;
sign(data : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Sign | update(data : DataBlob, callback : AsyncCallback\) : void;
update(data : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Sign | init(priKey : PriKey, callback : AsyncCallback\) : void;
init(priKey : PriKey) : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createCipher(transformation : string) : Cipher; | Added| +| ohos.security.cryptoFramework | Cipher | readonly algName : string; | Added| +| ohos.security.cryptoFramework | Cipher | doFinal(data : DataBlob, callback : AsyncCallback\) : void;
doFinal(data : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Cipher | update(data : DataBlob, callback : AsyncCallback\) : void;
update(data : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Cipher | init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void;
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createMd(algName : string) : Md; | Added| +| ohos.security.cryptoFramework | Md | readonly algName : string; | Added| +| ohos.security.cryptoFramework | Md | getMdLength() : number; | Added| +| ohos.security.cryptoFramework | Md | digest(callback : AsyncCallback\) : void;
digest() : Promise\; | Added| +| ohos.security.cryptoFramework | Md | update(input : DataBlob, callback : AsyncCallback\) : void;
update(input : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createMac(algName : string) : Mac; | Added| +| ohos.security.cryptoFramework | Mac | readonly algName : string; | Added| +| ohos.security.cryptoFramework | Mac | getMacLength() : number; | Added| +| ohos.security.cryptoFramework | Mac | doFinal(callback : AsyncCallback\) : void;
doFinal() : Promise\; | Added| +| ohos.security.cryptoFramework | Mac | update(input : DataBlob, callback : AsyncCallback\) : void;
update(input : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Mac | init(key : SymKey, callback : AsyncCallback\) : void;
init(key : SymKey) : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createSymKeyGenerator(algName : string) : SymKeyGenerator; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createAsyKeyGenerator(algName : string) : AsyKeyGenerator; | Added| +| ohos.security.cryptoFramework | SymKeyGenerator | readonly algName : string; | Added| +| ohos.security.cryptoFramework | SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void;
convertKey(key : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | SymKeyGenerator | generateSymKey(callback : AsyncCallback\) : void;
generateSymKey() : Promise\; | Added| +| ohos.security.cryptoFramework | AsyKeyGenerator | readonly algName : string; | Added| +| ohos.security.cryptoFramework | AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void;
convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | AsyKeyGenerator | generateKeyPair(callback : AsyncCallback\) : void;
generateKeyPair() : Promise\; | Added| +| ohos.security.cryptoFramework | cryptoFramework | createRandom() : Random; | Added| +| ohos.security.cryptoFramework | Random | setSeed(seed : DataBlob, callback : AsyncCallback\) : void;
setSeed(seed : DataBlob) : Promise\; | Added| +| ohos.security.cryptoFramework | Random | generateRandom(len : number, callback: AsyncCallback\) : void;
generateRandom(len : number) : Promise\; | Added| +| ohos.security.cryptoFramework | KeyPair | readonly pubKey : PubKey; | Added| +| ohos.security.cryptoFramework | KeyPair | readonly priKey : PriKey; | Added| +| ohos.security.cryptoFramework | PriKey | clearMem() : void; | Added| +| ohos.security.cryptoFramework | SymKey | clearMem() : void; | Added| +| ohos.security.cryptoFramework | Key | readonly algName : string; | Added| +| ohos.security.cryptoFramework | Key | readonly format : string; | Added| +| ohos.security.cryptoFramework | Key | getEncoded() : DataBlob; | Added| +| ohos.security.cryptoFramework | CryptoMode | DECRYPT_MODE = 1 | Added| +| ohos.security.cryptoFramework | CryptoMode | ENCRYPT_MODE = 0 | Added| +| ohos.security.cryptoFramework | CcmParamsSpec | authTag : DataBlob; | Added| +| ohos.security.cryptoFramework | CcmParamsSpec | aad : DataBlob; | Added| +| ohos.security.cryptoFramework | CcmParamsSpec | iv : DataBlob; | Added| +| ohos.security.cryptoFramework | GcmParamsSpec | authTag : DataBlob; | Added| +| ohos.security.cryptoFramework | GcmParamsSpec | aad : DataBlob; | Added| +| ohos.security.cryptoFramework | GcmParamsSpec | iv : DataBlob; | Added| +| ohos.security.cryptoFramework | IvParamsSpec | iv : DataBlob; | Added| +| ohos.security.cryptoFramework | ParamsSpec | algoName : string; | Added| +| ohos.security.cryptoFramework | CertChainData | encodingFormat: EncodingFormat; | Added| +| ohos.security.cryptoFramework | CertChainData | count : number; | Added| +| ohos.security.cryptoFramework | CertChainData | data: Uint8Array; | Added| +| ohos.security.cryptoFramework | EncodingBlob | encodingFormat : EncodingFormat; | Added| +| ohos.security.cryptoFramework | EncodingBlob | data : Uint8Array; | Added| +| ohos.security.cryptoFramework | EncodingFormat | FORMAT_PEM = 1 | Added| +| ohos.security.cryptoFramework | EncodingFormat | FORMAT_DER = 0 | Added| +| ohos.security.cryptoFramework | DataArray | data : Array\; | Added| +| ohos.security.cryptoFramework | DataBlob | data : Uint8Array; | Added| +| ohos.security.cryptoFramework | Result | ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE = 17630007 | Added| +| ohos.security.cryptoFramework | Result | ERR_KEYUSAGE_NO_CERTSIGN = 17630006 | Added| +| ohos.security.cryptoFramework | Result | ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY = 17630005 | Added| +| ohos.security.cryptoFramework | Result | ERR_CERT_HAS_EXPIRED = 17630004 | Added| +| ohos.security.cryptoFramework | Result | ERR_CERT_NOT_YET_VALID = 17630003 | Added| +| ohos.security.cryptoFramework | Result | ERR_CERT_SIGNATURE_FAILURE = 17630002 | Added| +| ohos.security.cryptoFramework | Result | ERR_CRYPTO_OPERATION = 17630001 | Added| +| ohos.security.cryptoFramework | Result | ERR_EXTERNAL_ERROR = 17620002 | Added| +| ohos.security.cryptoFramework | Result | ERR_OUT_OF_MEMORY = 17620001 | Added| +| ohos.security.cryptoFramework | Result | NOT_SUPPORT = 801 | Added| +| ohos.security.cryptoFramework | Result | INVALID_PARAMS = 401 | Added| +| ohos.security.huks | HuksTag | HUKS_TAG_CHALLENGE_POS = HuksTagType.HUKS_TAG_TYPE_UINT | 310 | +| ohos.security.huks | HuksTag | HUKS_TAG_CHALLENGE_TYPE = HuksTagType.HUKS_TAG_TYPE_UINT | 309 | +| ohos.security.huks | HuksTag | HUKS_TAG_KEY_SECURE_SIGN_TYPE = HuksTagType.HUKS_TAG_TYPE_UINT | 308 | +| ohos.security.huks | HuksTag | HUKS_TAG_KEY_AUTH_ACCESS_TYPE = HuksTagType.HUKS_TAG_TYPE_UINT | 307 | +| ohos.security.huks | HuksSecureSignType | HUKS_SECURE_SIGN_WITH_AUTHINFO = 1 | Added| +| ohos.security.huks | HuksChallengePosition | HUKS_CHALLENGE_POS_3 | Added| +| ohos.security.huks | HuksChallengePosition | HUKS_CHALLENGE_POS_2 | Added| +| ohos.security.huks | HuksChallengePosition | HUKS_CHALLENGE_POS_1 | Added| +| ohos.security.huks | HuksChallengePosition | HUKS_CHALLENGE_POS_0 = 0 | Added| +| ohos.security.huks | HuksChallengeType | HUKS_CHALLENGE_TYPE_NONE = 2 | Added| +| ohos.security.huks | HuksChallengeType | HUKS_CHALLENGE_TYPE_CUSTOM = 1 | Added| +| ohos.security.huks | HuksChallengeType | HUKS_CHALLENGE_TYPE_NORMAL = 0 | Added| +| ohos.security.huks | HuksAuthAccessType | HUKS_AUTH_ACCESS_INVALID_NEW_BIO_ENROLL = 1 \<\< 1 | Added| +| ohos.security.huks | HuksAuthAccessType | HUKS_AUTH_ACCESS_INVALID_CLEAR_PASSWORD = 1 \<\< 0 | Added| +| ohos.security.huks | HuksUserAuthType | HUKS_USER_AUTH_TYPE_PIN = 1 \<\< 2 | Added| +| ohos.security.huks | HuksUserAuthType | HUKS_USER_AUTH_TYPE_FACE = 1 \<\< 1 | Added| +| ohos.security.huks | HuksUserAuthType | HUKS_USER_AUTH_TYPE_FINGERPRINT = 1 \<\< 0 | Added| +| ohos.security.huks | HuksErrorCode | HUKS_ERROR_DEVICE_NO_CREDENTIAL = -44 | Added| +| ohos.security.huks | HuksErrorCode | HUKS_ERROR_KEY_AUTH_FAILED = -43 | Added| +| ohos.security.huks | HuksErrorCode | HUKS_ERROR_USER_AUTH_TYPE_NOT_SUPPORT = -42 | Added| +| ohos.security.huks | HuksErrorCode | HUKS_ERROR_GET_USERIAM_AUTHINFO_FAILED = -41 | Added| +| ohos.security.huks | HuksErrorCode | HUKS_ERROR_GET_USERIAM_SECINFO_FAILED = -40 | Added| +| ohos.security.huks | huks | attestKey(keyAlias: string, options: HuksOptions, callback: AsyncCallback\) : void;
attestKey(keyAlias: string, options: HuksOptions) : Promise\; | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-sensor.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-sensor.md new file mode 100644 index 0000000000000000000000000000000000000000..ff93a993df624703ca32accbfc97af1b519c0736 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-sensor.md @@ -0,0 +1,15 @@ +# JS API Changes of the Pan-Sensor Subsystem + +The table below lists the APIs changes of the pan-sensor subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.vibrator | VibratePreset | count: number; | Added| +| ohos.vibrator | VibratePreset | effectId: string; | Added| +| ohos.vibrator | VibratePreset | type: "preset"; | Added| +| ohos.vibrator | VibrateTime | duration: number; | Added| +| ohos.vibrator | VibrateTime | type: "time"; | Added| +| ohos.vibrator | VibrateAttribute | usage: Usage, | Added| +| ohos.vibrator | VibrateAttribute | id?: number, | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-soft-bus.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-soft-bus.md new file mode 100644 index 0000000000000000000000000000000000000000..60e29e47b92a85e1ebc8516c554626db9ef77f0f --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-soft-bus.md @@ -0,0 +1,10 @@ +# JS API Changes of the DSoftBus Subsystem + +The table below lists the APIs changes of the DSoftBus subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.rpc | RemoteObject | onRemoteRequestEx(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean \| Promise\; | Added| +| ohos.rpc | RemoteObject | onRemoteRequest(code: number, data: MessageParcel, reply: MessageParcel, options: MessageOption): boolean; | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-telephony.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-telephony.md new file mode 100644 index 0000000000000000000000000000000000000000..3a388b163f1241354821216b177d61c9c5b1dea5 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-telephony.md @@ -0,0 +1,26 @@ +# JS API Changes of the Telephony Subsystem + +The table below lists the APIs changes of the telephony subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.telephony.data | data | getDefaultCellularDataSlotIdSync(): number; | Added| +| ohos.telephony.radio | ImsServiceType | TYPE_SMS | Added| +| ohos.telephony.radio | ImsServiceType | TYPE_UT | Added| +| ohos.telephony.radio | ImsServiceType | TYPE_VIDEO | Added| +| ohos.telephony.radio | ImsServiceType | TYPE_VOICE | Added| +| ohos.telephony.radio | ImsRegInfo | imsRegTech: ImsRegTech; | Added| +| ohos.telephony.radio | ImsRegInfo | imsRegState: ImsRegState; | Added| +| ohos.telephony.radio | ImsRegTech | REGISTRATION_TECH_NR | Added| +| ohos.telephony.radio | ImsRegTech | REGISTRATION_TECH_IWLAN | Added| +| ohos.telephony.radio | ImsRegTech | REGISTRATION_TECH_LTE | Added| +| ohos.telephony.radio | ImsRegTech | REGISTRATION_TECH_NONE | Added| +| ohos.telephony.radio | ImsRegState | IMS_REGISTERED | Added| +| ohos.telephony.radio | ImsRegState | IMS_UNREGISTERED | Added| +| ohos.telephony.radio | radio | off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback\): void; | Added| +| ohos.telephony.radio | radio | on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback\): void; | Added| +| ohos.telephony.radio | radio | getImsRegInfo(slotId: number, imsType: ImsServiceType, callback: AsyncCallback\): void;
getImsRegInfo(slotId: number, imsType: ImsServiceType): Promise\; | Added| +| ohos.telephony.sim | sim | getOpName(slotId: number, callback: AsyncCallback\): void;
getOpName(slotId: number): Promise\; | Added| +| ohos.telephony.sim | sim | getOpKey(slotId: number, callback: AsyncCallback\): void;
getOpKey(slotId: number): Promise\; | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-unitest.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-unitest.md new file mode 100644 index 0000000000000000000000000000000000000000..d9afceaa16777b0c35dc350b4dd37be4d3281b19 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-unitest.md @@ -0,0 +1,24 @@ +# JS API Changes of the Test Subsystem + +The table below lists the APIs changes of the test subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.uitest | PointerMatrix | setPoint(finger: number, step: number, point: Point):void; | Added| +| ohos.uitest | PointerMatrix | static create(fingers: number, steps: number):PointerMatrix; | Added| +| ohos.uitest | UiDriver | injectMultiPointerAction(pointers: PointerMatrix, speed?: number):Promise\; | Added| +| ohos.uitest | UiDriver | fling(from: Point, to: Point, stepLen: number, speed: number):Promise\; | Added| +| ohos.uitest | UiDriver | waitForIdle(idleTime: number, timeout: number):Promise\; | Added| +| ohos.uitest | UiDriver | pressHome():Promise\; | Added| +| ohos.uitest | UiDriver | wakeUpDisplay():Promise\; | Added| +| ohos.uitest | UiDriver | getDisplayDensity():Promise\; | Added| +| ohos.uitest | UiDriver | getDisplaySize():Promise\; | Added| +| ohos.uitest | UiDriver | setDisplayRotationEnabled(enabled:boolean):Promise\; | Added| +| ohos.uitest | UiDriver | getDisplayRotation():Promise\; | Added| +| ohos.uitest | UiDriver | setDisplayRotation(rotation: DisplayRotation):Promise\; | Added| +| ohos.uitest | DisplayRotation | ROTATION_270 | Added| +| ohos.uitest | DisplayRotation | ROTATION_180 | Added| +| ohos.uitest | DisplayRotation | ROTATION_90 | Added| +| ohos.uitest | DisplayRotation | ROTATION_0 | Added| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-update.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-update.md new file mode 100644 index 0000000000000000000000000000000000000000..695eb56a2a9691579a3a7b262f99539232700547 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-update.md @@ -0,0 +1,22 @@ +# JS API Changes of the Update Subsystem + +The table below lists the APIs changes of the update subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.update | Order | INSTALL_AND_APPLY = 6 | Added| +| ohos.update | Order | DOWNLOAD_AND_INSTALL = 3 | Added| +| ohos.update | NetType | CELLULAR_AND_WIFI = 7 | Added| +| ohos.update | NetType | WIFI = 6 | Added| +| ohos.update | DescriptionFormat | SIMPLIFIED = 1 | Added| +| ohos.update | DescriptionFormat | STANDARD = 0 | Added| +| ohos.update | ComponentDescription | descriptionInfo: DescriptionInfo; | Added| +| ohos.update | ComponentDescription | componentId: string; | Added| +| ohos.update | DescriptionOptions | language: string; | Added| +| ohos.update | DescriptionOptions | format: DescriptionFormat; | Added| +| ohos.update | VersionComponent | componentId: string; | Added| +| ohos.update | Updater | getCurrentVersionDescription(descriptionOptions: DescriptionOptions, callback: AsyncCallback>): void;
getCurrentVersionDescription(descriptionOptions: DescriptionOptions): Promise>; | Added| +| ohos.update | Updater | getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOptions: DescriptionOptions, callback: AsyncCallback>): void;
getNewVersionDescription(versionDigestInfo: VersionDigestInfo, descriptionOptions: DescriptionOptions): Promise>; | Added| +| ohos.update | BusinessSubType | PARAM = 2 | Deleted| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-web.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-web.md new file mode 100644 index 0000000000000000000000000000000000000000..41d6f590aa5f7a0f36b520fe6887d8bd5314c778 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-web.md @@ -0,0 +1,50 @@ +# JS API Changes of the Web Subsystem + +The table below lists the APIs changes of the web subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.web.webview | WebCookieManager | static deleteSessionCookie(): void; | Added| +| ohos.web.webview | WebCookieManager | static deleteEntireCookie(): void; | Added| +| ohos.web.webview | WebCookieManager | static existCookie(): boolean; | Added| +| ohos.web.webview | WebCookieManager | static putAcceptThirdPartyCookieEnabled(accept: boolean): void; | Added| +| ohos.web.webview | WebCookieManager | static isThirdPartyCookieAllowed(): boolean; | Added| +| ohos.web.webview | WebCookieManager | static putAcceptCookieEnabled(accept: boolean): void; | Added| +| ohos.web.webview | WebCookieManager | static isCookieAllowed(): boolean; | Added| +| ohos.web.webview | WebCookieManager | static saveCookieAsync(): Promise\;
static saveCookieAsync(callback: AsyncCallback\): void; | Added| +| ohos.web.webview | WebCookieManager | static saveCookieSync(): boolean; | Added| +| ohos.web.webview | WebCookieManager | static setCookie(url: string, value: string): boolean; | Added| +| ohos.web.webview | WebCookieManager | static getCookie(url: string): string; | Added| +| ohos.web.webview | GeolocationPermissions | static getStoredGeolocation() : Promise\>;
static getStoredGeolocation(callback : AsyncCallback\>): void; | Added| +| ohos.web.webview | GeolocationPermissions | static getAccessibleGeolocation(origin: string): Promise\;
static getAccessibleGeolocation(origin: string, callback: AsyncCallback\): void; | Added| +| ohos.web.webview | GeolocationPermissions | static deleteAllGeolocation(): void; | Added| +| ohos.web.webview | GeolocationPermissions | static deleteGeolocation(origin: string): void; | Added| +| ohos.web.webview | GeolocationPermissions | static allowGeolocation(origin: string): void; | Added| +| ohos.web.webview | WebAsyncController | storeWebArchive(baseName: string, autoName: boolean): Promise\;
storeWebArchive(baseName: string, autoName: boolean, callback : AsyncCallback\): void; | Added| +| ohos.web.webview | WebAsyncController | constructor(controller: WebController); | Added| +| ohos.web.webview | WebDataBase | static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void; | Added| +| ohos.web.webview | WebDataBase | static getHttpAuthCredentials(host: string, realm: string): Array\; | Added| +| ohos.web.webview | WebDataBase | static deleteHttpAuthCredentials(): void; | Added| +| ohos.web.webview | WebDataBase | static existHttpAuthCredentials(): boolean; | Added| +| ohos.web.webview | WebStorage | static getOriginUsage(origin : string) : Promise\ ;
static getOriginUsage(origin : string, callback : AsyncCallback\) : void; | Added| +| ohos.web.webview | WebStorage | static getOriginQuota(origin : string) : Promise\;
static getOriginQuota(origin : string, callback : AsyncCallback\) : void; | Added| +| ohos.web.webview | WebStorage | static getOrigins() : Promise\>;
static getOrigins(callback: AsyncCallback\>) : void; | Added| +| ohos.web.webview | WebStorage | static deleteOrigin(origin : string): void; | Added| +| ohos.web.webview | WebStorage | static deleteAllData() : void; | Added| +| ohos.web.webview | WebStorageOrigin | quota: number; | Added| +| ohos.web.webview | WebStorageOrigin | usage: number; | Added| +| ohos.web.webview | WebStorageOrigin | origin: string; | Added| +| ohos.web | WebDataBase | static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void; | Deleted| +| ohos.web | WebDataBase | static getHttpAuthCredentials(host: string, realm: string): Array\; | Deleted| +| ohos.web | WebDataBase | static deleteHttpAuthCredentials(): void; | Deleted| +| ohos.web | WebDataBase | static existHttpAuthCredentials(): boolean; | Deleted| +| ohos.web | WebStorage | static getOriginUsage(origin : string) : Promise\ ;
static getOriginUsage(origin : string, callback : AsyncCallback\) : void; | Deleted| +| ohos.web | WebStorage | static getOriginQuota(origin : string) : Promise\;
static getOriginQuota(origin : string, callback : AsyncCallback\) : void; | Deleted| +| ohos.web | WebStorage | static getOrigins() : Promise\>;
static getOrigins(callback: AsyncCallback\>) : void; | Deleted| +| ohos.web | WebStorage | static deleteOrigin(origin : string): void; | Deleted| +| ohos.web | WebStorage | static deleteAllData() : void; | Deleted| +| ohos.web | WebStorageOrigin | quota: number; | Deleted| +| ohos.web | WebStorageOrigin | usage: number; | Deleted| +| ohos.web | WebStorageOrigin | origin: string; | Deleted| diff --git a/en/release-notes/api-change/v3.2-beta3/js-apidiff-window.md b/en/release-notes/api-change/v3.2-beta3/js-apidiff-window.md new file mode 100644 index 0000000000000000000000000000000000000000..94f41241876d724b1927ae8e66d7a143fa138f4c --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/js-apidiff-window.md @@ -0,0 +1,72 @@ +# JS API Changes of the Window Manager Subsystem + +The table below lists the APIs changes of the window manager subsystem in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2. + +## API Changes + +| Module| Class| Method/Attribute/Enumeration/Constant| Change Type| +|---|---|---|---| +| ohos.animation.windowAnimationManager | WindowAnimationController | onWindowAnimationTargetsUpdate(fullScreenWindowTarget: WindowAnimationTarget, floatingWindowTargets: Array\): void; | Added | +| ohos.animation.windowAnimationManager | WindowAnimationTarget | readonly missionId: number; | Added| +| ohos.animation.windowAnimationManager | windowAnimationManager | minimizeWindowWithAnimation(windowTarget: WindowAnimationTarget, callback: AsyncCallback\): void;
minimizeWindowWithAnimation(windowTarget: WindowAnimationTarget): Promise\; | Added | +| ohos.display | Display | getCutoutInfo(callback: AsyncCallback\): void;
getCutoutInfo(): Promise\; | Added| +| ohos.display | CutoutInfo | readonly waterfallDisplayAreaRects: WaterfallDisplayAreaRects; | Added| +| ohos.display | CutoutInfo | readonly boundingRects: Array\; | Added| +| ohos.display | WaterfallDisplayAreaRects | readonly bottom: Rect; | Added| +| ohos.display | WaterfallDisplayAreaRects | readonly top: Rect; | Added| +| ohos.display | WaterfallDisplayAreaRects | readonly right: Rect; | Added| +| ohos.display | WaterfallDisplayAreaRects | readonly left: Rect; | Added| +| ohos.display | Rect | height: number; | Added| +| ohos.display | Rect | width: number; | Added| +| ohos.display | Rect | top: number; | Added| +| ohos.display | Rect | left: number; | Added| +| ohos.display | display | hasPrivateWindow(displayId: number): boolean; | Added| +| ohos.window | Window | setCornerRadius(cornerRadius: number): void; | Added| +| ohos.window | Window | setShadow(radius: number, color?: string, offsetX?: number, offsetY?: number): void; | Added| +| ohos.window | Window | setBackdropBlurStyle(blurStyle: BlurStyle): void; | Added| +| ohos.window | Window | setBackdropBlur(radius: number): void; | Added| +| ohos.window | Window | setBlur(radius: number): void; | Added| +| ohos.window | Window | getTransitionController(): TransitionController; | Added| +| ohos.window | Window | translate(translateOptions: TranslateOptions): void; | Added| +| ohos.window | Window | rotate(rotateOptions: RotateOptions): void; | Added| +| ohos.window | Window | scale(scaleOptions: ScaleOptions): void; | Added| +| ohos.window | Window | opacity(opacity: number): void; | Added| +| ohos.window | Window | snapshot(callback: AsyncCallback\): void;
snapshot(): Promise\; | Added| +| ohos.window | Window | setSnapshotSkip(isSkip: boolean): void; | Added| +| ohos.window | Window | setWakeUpScreen(wakeUp: boolean): void; | Added| +| ohos.window | Window | bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback\): Promise\;
bindDialogTarget(token: rpc.RemoteObject, deathCallback: Callback\, callback: AsyncCallback\): void; | Added| +| ohos.window | Window | off(type: 'dialogTargetTouch', callback?: Callback\): void; | Added| +| ohos.window | Window | on(type: 'dialogTargetTouch', callback: Callback\): void; | Added| +| ohos.window | Window | off(type: 'screenshot', callback?: Callback\): void; | Added| +| ohos.window | Window | on(type: 'screenshot', callback: Callback\): void; | Added| +| ohos.window | Window | showWithAnimation(callback: AsyncCallback\): void;
showWithAnimation(): Promise\; | Added| +| ohos.window | Window | hideWithAnimation(callback: AsyncCallback\): void;
hideWithAnimation(): Promise\; | Added| +| ohos.window | BlurStyle | THICK | Added| +| ohos.window | BlurStyle | REGULAR | Added| +| ohos.window | BlurStyle | THIN | Added| +| ohos.window | BlurStyle | OFF | Added| +| ohos.window | TransitionController | animationForHidden(context: TransitionContext): void; | Added| +| ohos.window | TransitionController | animationForShown(context: TransitionContext): void; | Added| +| ohos.window | TransitionContext | completeTransition(isCompleted: boolean): void; | Added| +| ohos.window | TransitionContext | toWindow: Window | Added| +| ohos.window | TranslateOptions | z?: number; | Added| +| ohos.window | TranslateOptions | y?: number; | Added| +| ohos.window | TranslateOptions | x?: number; | Added| +| ohos.window | RotateOptions | pivotY?: number; | Added| +| ohos.window | RotateOptions | pivotX?: number; | Added| +| ohos.window | RotateOptions | z?: number; | Added| +| ohos.window | RotateOptions | y?: number; | Added| +| ohos.window | RotateOptions | x?: number; | Added| +| ohos.window | ScaleOptions | pivotY?: number; | Added| +| ohos.window | ScaleOptions | pivotX?: number; | Added| +| ohos.window | ScaleOptions | y?: number; | Added| +| ohos.window | ScaleOptions | x?: number; | Added| +| ohos.window | WindowProperties | id: number | Added| +| ohos.window | WindowType | TYPE_SCREENSHOT | Added| +| ohos.window | WindowType | TYPE_DIALOG | Added| +| ohos.window | WindowType | TYPE_FLOAT_CAMERA | Added| +| ohos.screen | Orientation | SENSOR_HORIZONTAL = 7 | Deleted| +| ohos.screen | Orientation | SENSOR_VERTICAL = 6 | Deleted| +| ohos.screen | Orientation | SENSOR = 5 | Deleted| +| ohos.window | Window | setWindowType(type: WindowType): Promise\;
setWindowType(type: WindowType, callback: AsyncCallback\): void; | Deprecated| +| ohos.window | WindowProperties | isRoundCorner: boolean | Deprecated| diff --git a/en/release-notes/api-change/v3.2-beta3/readme.md b/en/release-notes/api-change/v3.2-beta3/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..af4d7cc1dd326b2a086cacd23eebeb5f49bb1b78 --- /dev/null +++ b/en/release-notes/api-change/v3.2-beta3/readme.md @@ -0,0 +1,32 @@ +# Readme + +This directory records the API changes in OpenHarmony 3.2 Beta3 over OpenHarmony 3.2 Beta2, including new, updated, deprecated, and deleted APIs. + +- JS API Differences + - [Ability framework](js-apidiff-ability.md) + - [Accessibility subsystem](js-apidiff-accessibility.md) + - [Account subsystem](js-apidiff-account.md) + - [ArkUI development framework](js-apidiff-arkui.md) + - [Power management subsystem](js-apidiff-battery.md) + - [Bundle management framework](js-apidiff-bundle.md) + - [Communication subsystem](js-apidiff-communicate.md) + - [Utils subsystem](js-apidiff-compiler-and-runtime.md) + - [DFX subsystem](js-apidiff-dfx.md) + - [Distributed data management subsystem](js-apidiff-distributed-data.md) + - [Distributed hardware subsystem](js-apidiff-distributed-hardware.md) + - [Common event and notification subsystem](js-apidiff-event-and-notification.md) + - [File management subsystem](js-apidiff-file-management.md) + - [Globalization subsystem](js-apidiff-global.md) + - [Graphics subsystem](js-apidiff-graphic.md) + - [Misc services subsystem](js-apidiff-misc.md) + - [Multimodal input subsystem](js-apidiff-multi-modal-input.md) + - [Multimedia subsystem](js-apidiff-multimedia.md) + - [Resource scheduler subsystem](js-apidiff-resource-scheduler.md) + - [Security subsystem](js-apidiff-security.md) + - [Pan-sensor subsystem](js-apidiff-sensor.md) + - [DSoftBus subsystem](js-apidiff-soft-bus.md) + - [Telephony subsystem](js-apidiff-telephony.md) + - [Test subsystem](js-apidiff-unitest.md) + - [Update subsystem](js-apidiff-update.md) + - [Web subsystem](js-apidiff-web.md) + - [Window manager subsystem](js-apidiff-window.md) diff --git a/en/website.md b/en/website.md index 7db9fc97030c762eb15010dcbcd428e85ef425ab..158b3a9361862cbb14bc7dfca3c1af5fbbea3e99 100644 --- a/en/website.md +++ b/en/website.md @@ -29,7 +29,35 @@ - [OpenHarmony 1.0 (2020-09-10)](release-notes/OpenHarmony-1-0.md) - API Differences - + - OpenHarmony 3.2 Beta3 + - JS API Differences + - [Ability framework](release-notes/api-change/v3.2-beta3/js-apidiff-ability.md) + - [Accessibility subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-accessibility.md) + - [Account subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-account.md) + - [ArkUI development framework](release-notes/api-change/v3.2-beta3/js-apidiff-arkui.md) + - [Power management subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-battery.md) + - [Bundle management framework](release-notes/api-change/v3.2-beta3/js-apidiff-bundle.md) + - [Communication subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-communicate.md) + - [Utils subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-compiler-and-runtime.md) + - [DFX subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-dfx.md) + - [Distributed data management subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-distributed-data.md) + - [Distributed hardware subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-distributed-hardware.md) + - [Common event and notification subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-event-and-notification.md) + - [File management subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-file-management.md) + - [Globalization subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-global.md) + - [Graphics subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-graphic.md) + - [Misc services subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-misc.md) + - [Multimodal input subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-multi-modal-input.md) + - [Multimedia subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-multimedia.md) + - [Resource scheduler subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-resource-scheduler.md) + - [Security subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-security.md) + - [Pan-sensor subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-sensor.md) + - [DSoftBus subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-soft-bus.md) + - [Telephony subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-telephony.md) + - [Test subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-unitest.md) + - [Update subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-update.md) + - [Web subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-web.md) + - [Window manager subsystem](release-notes/api-change/v3.2-beta3/js-apidiff-window.md) - OpenHarmony 3.2 Beta2 - JS API Differences - [Ability framework](release-notes/api-change/v3.2-beta2/js-apidiff-ability.md) @@ -49,7 +77,7 @@ - [Misc services subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-misc.md) - [Multimodal input subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-multi-modal-input.md) - [Multimedia subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-multimedia.md) - - [Distributed scheduler subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-resource-scheduler.md) + - [Resource scheduler subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-resource-scheduler.md) - [Security subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-security.md) - [Pan-sensor subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-sensor.md) - [DSoftBus subsystem](release-notes/api-change/v3.2-beta2/js-apidiff-soft-bus.md) @@ -79,7 +107,6 @@ - [Multimodal input subsystem](release-notes/api-change/v3.2-beta1/js-apidiff-multi-modal-input.md) - [Multimedia subsystem](release-notes/api-change/v3.2-beta1/js-apidiff-multimedia.md) - [Distributed scheduler subsystem](release-notes/api-change/v3.2-beta1/js-apidiff-resource-scheduler.md) - - [DSoftBus subsystem](release-notes/api-change/v3.2-beta1/js-apidiff-soft-bus.md) - [Test subsystem](release-notes/api-change/v3.2-beta1/js-apidiff-unitest.md) - [Web subsystem](release-notes/api-change/v3.2-beta1/js-apidiff-web.md) - [Window manager subsystem](release-notes/api-change/v3.2-beta1/js-apidiff-window.md) @@ -129,7 +156,7 @@ - OpenHarmony Third-Party Components - [OpenHarmony Third-Party Components](third-party-components/third-party-components-introduction.md) - [Using OpenHarmony JS and TS Third-Party Components](third-party-components/npm-third-party-guide.md) - + - Contribution - [How to Contribute](contribute/how-to-contribute.md) - [Code of Conduct](contribute/code-of-conduct.md) diff --git a/zh-cn/application-dev/Readme-CN.md b/zh-cn/application-dev/Readme-CN.md index 4743c1e020b9e08362342363ba79178e9c07139e..dde8993091b6eb93c20db2f5b35e86fb670c40e6 100644 --- a/zh-cn/application-dev/Readme-CN.md +++ b/zh-cn/application-dev/Readme-CN.md @@ -16,6 +16,17 @@ - [应用包结构说明(Stage模型)](quick-start/stage-structure.md) - [SysCap说明](quick-start/syscap.md) - [HarmonyAppProvision配置文件](quick-start/app-provision-structure.md) + - 学习ArkTS语言 + - [初识ArkTS语言](quick-start/arkts-get-started.md) + - ArkTS语法(声明式UI) + - [基本UI描述](quick-start/arkts-basic-ui-description.md) + - 状态管理 + - [基本概念](quick-start/arkts-state-mgmt-concepts.md) + - [页面级变量的状态管理](quick-start/arkts-state-mgmt-page-level.md) + - [应用级变量的状态管理](quick-start/arkts-state-mgmt-application-level.md) + - [动态构建UI元素](quick-start/arkts-dynamic-ui-elememt-building.md) + - [渲染控制](quick-start/arkts-rendering-control.md) + - [使用限制与扩展](quick-start/arkts-restrictions-and-extensions.md) - 开发 - [Ability开发](ability/Readme-CN.md) - [UI开发](ui/Readme-CN.md) diff --git a/zh-cn/application-dev/ability/continuationmanager.md b/zh-cn/application-dev/ability/continuationmanager.md index d82b77dbdf811b3fdc37a6a021b2416c0e0d8f9c..d5a92c9deb6f5433db1c8ec96efdf0c2a18328cb 100644 --- a/zh-cn/application-dev/ability/continuationmanager.md +++ b/zh-cn/application-dev/ability/continuationmanager.md @@ -55,6 +55,7 @@ continuationManager作为流转能力的入口,主要用于拉起系统中的 ```ts import abilityAccessCtrl from "@ohos.abilityAccessCtrl"; import bundle from '@ohos.bundle'; + import featureAbility from '@ohos.ability.featureAbility'; async function requestPermission() { let permissions: Array = [ @@ -122,7 +123,8 @@ continuationManager作为流转能力的入口,主要用于拉起系统中的 // 如果未申请该权限,则需要调用requestPermissionsFromUser接口申请权限 if (needGrantPermission) { try { - await globalThis.abilityContext.requestPermissionsFromUser(permissions); + // globalThis.context即Ability.context,需提前在MainAbility.ts文件中赋值 + await globalThis.context.requestPermissionsFromUser(permissions); } catch (err) { console.error('app permission request permissions error' + JSON.stringify(err)); } diff --git a/zh-cn/application-dev/ability/fa-brief.md b/zh-cn/application-dev/ability/fa-brief.md index eff2aef25d1eb9e1f2a6a3a9b9938971304cab9d..3d8989bc1f7c56a6e9b614b3a6cfb7647d21f865 100644 --- a/zh-cn/application-dev/ability/fa-brief.md +++ b/zh-cn/application-dev/ability/fa-brief.md @@ -39,15 +39,15 @@ FA模型的应用包的工程目录结构,请参考[OpenHarmony工程介绍](h 针对FA模型下的Ability开发,有以下相关实例可供参考: -- [`FaModel`:FA模型(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FaModel) +- [`FaModel`:FA模型(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FaModel) - [`DistributedCalc`:分布式计算器(JS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/DistributeCalc) -- [`DistributedCalc`:分布式计算器(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc) -- [`DistributeGraffiti`:分布式涂鸦(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DistributedGraffiti) +- [`DistributedCalc`:分布式计算器(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc) +- [`DistributeGraffiti`:分布式涂鸦(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DistributedGraffiti) - [分布式调度启动远程FA(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteStartFA) - [分布式新闻客户端(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/NewsDemo) -- [分布式手写板(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) +- [分布式手写板(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/DistributeDatabaseDrawEts) - [分布式鉴权(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/GameAuthOpenH) -- [分布式游戏手柄(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) -- [分布式邮件(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) -- [分布式亲子早教系统(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) -- [分布式遥控器(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) \ No newline at end of file +- [分布式游戏手柄(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/HandleGameApplication) +- [分布式邮件(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OHMailETS) +- [分布式亲子早教系统(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/OpenHarmonyPictureGame) +- [分布式遥控器(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Distributed/RemoteControllerETS) \ No newline at end of file diff --git a/zh-cn/application-dev/ability/fa-dataability.md b/zh-cn/application-dev/ability/fa-dataability.md index bd66df25aa9f2b56c6bdfda61bbf68e0c10f1be1..78855f0834476bf389e9a17faed5cdf6a126894f 100644 --- a/zh-cn/application-dev/ability/fa-dataability.md +++ b/zh-cn/application-dev/ability/fa-dataability.md @@ -311,4 +311,4 @@ URI示例: 针对DataAbility开发,有以下相关实例可供参考: -- [`DataAbility`:DataAbility的创建与访问(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DataAbility) +- [`DataAbility`:DataAbility的创建与访问(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DataAbility) diff --git a/zh-cn/application-dev/ability/fa-formability.md b/zh-cn/application-dev/ability/fa-formability.md index 0f2be340b5dbad6500929a80eceec167f58a1fde..3fbe75aba88249f3248233b5626a3b1fa9139a70 100644 --- a/zh-cn/application-dev/ability/fa-formability.md +++ b/zh-cn/application-dev/ability/fa-formability.md @@ -403,5 +403,5 @@ onUpdate(formId) { ## 相关实例 针对FA模型卡片提供方的开发,有以下相关实例可供参考: -- [`FormAbility`:FA模型卡片(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormAbility) -- [`FormLauncher`:卡片使用方(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormLauncher) \ No newline at end of file +- [`FormAbility`:FA模型卡片(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormAbility) +- [`FormLauncher`:卡片使用方(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormLauncher) \ No newline at end of file diff --git a/zh-cn/application-dev/ability/fa-pageability.md b/zh-cn/application-dev/ability/fa-pageability.md index c854269adc4054c88b3f3d1a61c89bf6db1d6129..abab9903310c167f82cdb8dbe8cb80d4243686cb 100644 --- a/zh-cn/application-dev/ability/fa-pageability.md +++ b/zh-cn/application-dev/ability/fa-pageability.md @@ -80,19 +80,17 @@ ability支持单实例和多实例两种启动模式。 ```javascript import featureAbility from '@ohos.ability.featureAbility' featureAbility.startAbility({ - want: - { - action: "", - entities: [""], - type: "", - deviceId: "", - bundleName: "com.example.myapplication", - /* FA模型中abilityName由package + Ability name组成 */ - abilityName: "com.example.entry.secondAbility", - uri: "" - }, - }, - ); + want: { + action: "", + entities: [""], + type: "", + deviceId: "", + bundleName: "com.example.myapplication", + /* FA模型中abilityName由package + Ability name组成 */ + abilityName: "com.example.entry.secondAbility", + uri: "" + } + }); ``` ### 启动远程PageAbility(当前仅对系统应用开放) @@ -227,4 +225,4 @@ export default { 针对PageAbility开发,有以下相关实例可供参考: -- [`DMS`:分布式Demo(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DMS) \ No newline at end of file +- [`DMS`:分布式Demo(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DMS) \ No newline at end of file diff --git a/zh-cn/application-dev/ability/fa-serviceability.md b/zh-cn/application-dev/ability/fa-serviceability.md index d00801955385bee15b008864cb96537879272cb3..162f45f14406b52de45c9bf13e1c9fe08882e73c 100644 --- a/zh-cn/application-dev/ability/fa-serviceability.md +++ b/zh-cn/application-dev/ability/fa-serviceability.md @@ -406,5 +406,5 @@ export default { ## 相关实例 针对ServiceAbility开发,有以下相关实例可供参考: -- [`ServiceAbility`:ServiceAbility的创建与使用(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceAbility) -- [`DMS`:分布式Demo(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DMS) +- [`ServiceAbility`:ServiceAbility的创建与使用(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceAbility) +- [`DMS`:分布式Demo(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/DMS) diff --git a/zh-cn/application-dev/ability/stage-ability.md b/zh-cn/application-dev/ability/stage-ability.md index b10f8d6934228cf668dca0390e47e5ef6c60ce8a..4a39afa52ebff9f2d33fc8dcac0a79e17fdaaf75 100644 --- a/zh-cn/application-dev/ability/stage-ability.md +++ b/zh-cn/application-dev/ability/stage-ability.md @@ -324,4 +324,4 @@ struct Index { ## 相关实例 针对Stage模型Ability开发,有以下相关示例可供参考: -- [`StageCallAbility`:StageCallAbility的创建与使用(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageCallAbility) +- [`StageCallAbility`:StageCallAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageCallAbility) diff --git a/zh-cn/application-dev/ability/stage-brief.md b/zh-cn/application-dev/ability/stage-brief.md index 858dc74a03b441bf7a4f48aef1cd55c8648c2f85..5adca9fd9cd56566346a079a5ecc3aee9b0fda47 100644 --- a/zh-cn/application-dev/ability/stage-brief.md +++ b/zh-cn/application-dev/ability/stage-brief.md @@ -111,7 +111,7 @@ Stage模型的应用包的工程目录结构,请参考[OpenHarmony工程介绍 针对Stage模型下的Ability开发,有以下相关实例可供参考: -- [`StageModel`:Stage模型(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageModel) -- [`WindowExtAbility`:窗口扩展(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/WindowExtAbility) -- [`MissionManager`:系统任务管理(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/MissionManager) -- [`Launcher`:仿桌面应用(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/Launcher) +- [`StageModel`:Stage模型(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageModel) +- [`WindowExtAbility`:窗口扩展(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/WindowExtAbility) +- [`MissionManager`:系统任务管理(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/MissionManager) +- [`Launcher`:仿桌面应用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/Launcher) diff --git a/zh-cn/application-dev/ability/stage-call.md b/zh-cn/application-dev/ability/stage-call.md index eae390bd7e04f88317f70d2d2875506cb947ff94..7aa9769c0a56c39bc9d93772c5a1e0cd7d4ba2f3 100644 --- a/zh-cn/application-dev/ability/stage-call.md +++ b/zh-cn/application-dev/ability/stage-call.md @@ -284,4 +284,4 @@ releaseCall() { ## 相关实例 针对Stage模型本地Call功能开发,有以下相关实例可供参考: -- [`StageCallAbility`:StageCallAbility的创建与使用(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageCallAbility) +- [`StageCallAbility`:StageCallAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/StageCallAbility) diff --git a/zh-cn/application-dev/ability/stage-formextension.md b/zh-cn/application-dev/ability/stage-formextension.md index 1d4a427c3e8fb8d44dc18f4dab4a12803e063fff..1e9bcb98842c26520619ede57ac6b7f38f25f470 100644 --- a/zh-cn/application-dev/ability/stage-formextension.md +++ b/zh-cn/application-dev/ability/stage-formextension.md @@ -414,5 +414,5 @@ onUpdate(formId) { ## 相关实例 针对Stage模型卡片提供方的开发,有以下相关实例可供参考: -- [`FormExtAbility`:Stage模型卡片(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormExtAbility) -- [`GalleryForm`:图库卡片(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm) \ No newline at end of file +- [`FormExtAbility`:Stage模型卡片(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/FormExtAbility) +- [`GalleryForm`:图库卡片(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/GalleryForm) \ No newline at end of file diff --git a/zh-cn/application-dev/ability/stage-serviceextension.md b/zh-cn/application-dev/ability/stage-serviceextension.md index 664eb0e4461ec704e55cf4f47d720faabef5cee4..f52701d88dfd1d9bca4be663ff8652c44e480a0b 100644 --- a/zh-cn/application-dev/ability/stage-serviceextension.md +++ b/zh-cn/application-dev/ability/stage-serviceextension.md @@ -75,4 +75,4 @@ OpenHarmony当前不支持三方应用创建ServiceExtensionAbility。 ## 相关实例 针对ServiceExtensionAbility开发,有以下相关实例可供参考: -- [`ServiceExtAbility`:StageExtAbility的创建与使用(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceExtAbility) +- [`ServiceExtAbility`:StageExtAbility的创建与使用(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/ServiceExtAbility) diff --git a/zh-cn/application-dev/connectivity/http-request.md b/zh-cn/application-dev/connectivity/http-request.md index 3605d45f313f84b9c70382a62e7754c121418dc4..08a74db395b4761440c0da4ed30417af6a9d14fb 100644 --- a/zh-cn/application-dev/connectivity/http-request.md +++ b/zh-cn/application-dev/connectivity/http-request.md @@ -76,5 +76,5 @@ httpRequest.request( ## 相关实例 针对HTTP数据请求,有以下相关实例可供参考: -- [`Http:`数据请求(eTS)(API9))](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Http) -- [使用HTTP实现与服务端通信(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) \ No newline at end of file +- [`Http:`数据请求(ArkTS)(API9))](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Http) +- [使用HTTP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/SmartChatEtsOH) \ No newline at end of file diff --git a/zh-cn/application-dev/connectivity/socket-connection.md b/zh-cn/application-dev/connectivity/socket-connection.md index a538d2134dee0e74e6510d81ddab7b2663535d73..2c04d2270a2f2b9c0e9a4551fe06bd1d91483620 100644 --- a/zh-cn/application-dev/connectivity/socket-connection.md +++ b/zh-cn/application-dev/connectivity/socket-connection.md @@ -125,6 +125,6 @@ UDP与TCP流程大体类似,下面以TCP为例: ## 相关实例 针对Socket连接开发,有以下相关实例可供参考: -- [`Socket`:Socket 连接(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) -- [使用UDP实现与服务端通信(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) -- [使用TCP实现与服务端通信(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) \ No newline at end of file +- [`Socket`:Socket 连接(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/Socket) +- [使用UDP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/UdpDemoOH) +- [使用TCP实现与服务端通信(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NetworkManagement/TcpSocketDemo) \ No newline at end of file diff --git a/zh-cn/application-dev/connectivity/websocket-connection.md b/zh-cn/application-dev/connectivity/websocket-connection.md index 41ddfa0a73707b4d5cf0db3c3b30d735dbb775f3..6efe6b5b39ac1efb22d5dc89d6a75d2c018ad808 100644 --- a/zh-cn/application-dev/connectivity/websocket-connection.md +++ b/zh-cn/application-dev/connectivity/websocket-connection.md @@ -87,4 +87,4 @@ WebSocket连接功能主要由webSocket模块提供。使用该功能需要申 ## 相关实例 针对WebSocket连接的开发,有以下相关实例可供参考: -- [`WebSocket`:WebSocket(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/WebSocket) \ No newline at end of file +- [`WebSocket`:WebSocket(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Network/WebSocket) \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-distributedobject-guidelines.md b/zh-cn/application-dev/database/database-distributedobject-guidelines.md index 6ba96a9b202191e1323ea2d362eab3ff58dfbea0..b18ca1730cce8cb3c8f89d63f4cfb3b140a7d763 100644 --- a/zh-cn/application-dev/database/database-distributedobject-guidelines.md +++ b/zh-cn/application-dev/database/database-distributedobject-guidelines.md @@ -259,5 +259,5 @@ ## 相关实例 针对分布式数据对象,有以下相关实例可供参考: -- [`DistributedNote`:分布式备忘录(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedNote) -- [`DistributedObjectDms`:分布式跑马灯(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedObjectDms) \ No newline at end of file +- [`DistributedNote`:分布式备忘录(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedNote) +- [`DistributedObjectDms`:分布式跑马灯(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedObjectDms) \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-mdds-guidelines.md b/zh-cn/application-dev/database/database-mdds-guidelines.md index fa22e9d631121538f22ce310c081ff5bb00efa10..aa8938f6b21529ac5b0c3d76a72df8301bc56922 100644 --- a/zh-cn/application-dev/database/database-mdds-guidelines.md +++ b/zh-cn/application-dev/database/database-mdds-guidelines.md @@ -266,8 +266,8 @@ 针对分布式数据开发,有以下相关实例可供参考: - [`DistributedCalc`:分布式计算器(JS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/DistributeCalc) -- [`DistributedCalc`:分布式计算器(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc) -- [`DistributedDataGobang`:分布式五子棋(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedDataGobang) -- [`DDMQuery`:结果集与谓词(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DDMQuery) -- [`KvStore`:分布式数据库(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Kvstore) +- [`DistributedCalc`:分布式计算器(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/DistributeCalc) +- [`DistributedDataGobang`:分布式五子棋(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedDataGobang) +- [`DDMQuery`:结果集与谓词(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DDMQuery) +- [`KvStore`:分布式数据库(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Kvstore) - [分布式数据库(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Data/JsDistributedData) \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-preference-guidelines.md b/zh-cn/application-dev/database/database-preference-guidelines.md index 7714776aa3febdd6a41923b02f6c4bd7ae4a8b19..ad418f8682ffed9d5907105595555b3abeb3dbda 100644 --- a/zh-cn/application-dev/database/database-preference-guidelines.md +++ b/zh-cn/application-dev/database/database-preference-guidelines.md @@ -205,4 +205,4 @@ 针对首选项开发,有以下相关实例可供参考: -- [`Preferences`:首选项(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Preferences) \ No newline at end of file +- [`Preferences`:首选项(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/Preferences) \ No newline at end of file diff --git a/zh-cn/application-dev/database/database-relational-guidelines.md b/zh-cn/application-dev/database/database-relational-guidelines.md index 64398cd48fbdd355d8a40a6f1464b7a553e7333c..3a89466da4747b55dae10e73bc1d17c1b2730ce4 100644 --- a/zh-cn/application-dev/database/database-relational-guidelines.md +++ b/zh-cn/application-dev/database/database-relational-guidelines.md @@ -418,5 +418,5 @@ ## 相关实例 针对关系型数据库开发,有以下相关实例可供参考: -- [`DistributedRdb`:分布式关系型数据库(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedRdb) +- [`DistributedRdb`:分布式关系型数据库(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/data/DistributedRdb) - [关系型数据库(JS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/Data/JSRelationshipData) \ No newline at end of file diff --git a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md index 18c8143806545696068a51a76f06a34f7e34e9df..e13a7049bcad16fbdfb9cf3ac0a66cf84814c60d 100644 --- a/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md +++ b/zh-cn/application-dev/device-usage-statistics/device-usage-statistics-dev-guide.md @@ -439,5 +439,5 @@ import stats from '@ohos.bundleState'; ``` ## 相关实例 针对设备使用信息统计,有以下相关实例可供参考: -- [`DeviceUsageStatistics`:设备使用信息统计(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/DeviceUsageStatistics) +- [`DeviceUsageStatistics`:设备使用信息统计(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/DeviceUsageStatistics) diff --git a/zh-cn/application-dev/device/device-location-overview.md b/zh-cn/application-dev/device/device-location-overview.md index d1ca6ae0f462711023deceaab0df665287072f3e..b955a1a06d6b9b71b47d012f9a1c6fe14627fd47 100644 --- a/zh-cn/application-dev/device/device-location-overview.md +++ b/zh-cn/application-dev/device/device-location-overview.md @@ -42,4 +42,4 @@ 针对位置服务,有以下相关实例可供参考: --[`Location`:位置服务(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location) +- [`Location`:位置服务(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Location) diff --git a/zh-cn/application-dev/device/sensor-guidelines.md b/zh-cn/application-dev/device/sensor-guidelines.md index e0dfb477374c29ce46b2885b68a568678c2a627c..9c225832d3a0abb6f8afe034baa90f4239dc2ca3 100644 --- a/zh-cn/application-dev/device/sensor-guidelines.md +++ b/zh-cn/application-dev/device/sensor-guidelines.md @@ -96,4 +96,4 @@ 针对传感器开发,有以下相关实例可供参考: -- [`Sensor`:传感器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Sensor) \ No newline at end of file +- [`Sensor`:传感器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Sensor) \ No newline at end of file diff --git a/zh-cn/application-dev/device/usb-guidelines.md b/zh-cn/application-dev/device/usb-guidelines.md index cd215f3a67788ae7513aad04045a75f4b78e660d..5ae59b9f4e1b5dda5ede796fa32e93616ed76999 100644 --- a/zh-cn/application-dev/device/usb-guidelines.md +++ b/zh-cn/application-dev/device/usb-guidelines.md @@ -4,7 +4,7 @@ ## 场景介绍 -Host模式下,可以获取到已经连接的设备列表,并根据需要打开和关闭设备、控制设备权限、进行数据传输等。 +Host模式下,可以获取到已经连接的USB设备列表,并根据需要打开和关闭设备、控制设备权限、进行数据传输等。 ## 接口说明 @@ -19,6 +19,7 @@ USB类开放能力如下,具体请查阅[API参考文档](../reference/apis/js | ------------------------------------------------------------ | ------------------------------------------------------------ | | hasRight(deviceName: string): boolean | 如果“使用者”(如各种App或系统)有权访问设备则返回true;无权访问设备则返回false。 | | requestRight(deviceName: string): Promise<boolean> | 请求给定软件包的临时权限以访问设备。 | +| removeRight(deviceName: string): boolean | 移除软件包对设备的访问权限。| | connectDevice(device: USBDevice): Readonly<USBDevicePipe> | 根据`getDevices()`返回的设备信息打开USB设备。 | | getDevices(): Array<Readonly<USBDevice>> | 返回USB设备列表。 | | setConfiguration(pipe: USBDevicePipe, config: USBConfig): number | 设置设备的配置。 | @@ -163,4 +164,4 @@ USB设备可作为Host设备连接Device设备进行数据传输。开发示例 针对USB管理开发,有以下相关实例可供参考: -- [`USBManager`:USB管理(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/USBManager) \ No newline at end of file +- [`USBManager`:USB管理(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/USBManager) \ No newline at end of file diff --git a/zh-cn/application-dev/device/vibrator-guidelines.md b/zh-cn/application-dev/device/vibrator-guidelines.md index 6ba0789ca707b0034ee24c91b5e48e0d7fb5bc31..21853379693b3499c68320db080072573802be59 100644 --- a/zh-cn/application-dev/device/vibrator-guidelines.md +++ b/zh-cn/application-dev/device/vibrator-guidelines.md @@ -54,4 +54,4 @@ 针对振动开发,有以下相关实例可供参考: -- [`Vibrator`:振动(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Vibrator) \ No newline at end of file +- [`Vibrator`:振动(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/device/Vibrator) \ No newline at end of file diff --git a/zh-cn/application-dev/dfx/hiappevent-guidelines.md b/zh-cn/application-dev/dfx/hiappevent-guidelines.md index cdecfcafbb0a94aaf26271a49abd3dabd0908a83..d56dc9a859e36738bb3a819cdb73ee628da4da86 100644 --- a/zh-cn/application-dev/dfx/hiappevent-guidelines.md +++ b/zh-cn/application-dev/dfx/hiappevent-guidelines.md @@ -1,4 +1,4 @@ -# 应用事件开发指导 +# 应用事件打点开发指导 ## 场景介绍 @@ -8,7 +8,7 @@ 应用事件JS打点接口由hiAppEvent模块提供。 -以下仅提供简单的接口介绍,API接口的具体使用说明(参数使用限制、具体取值范围等),请参考[应用事件打点API文档](../reference/apis/js-apis-hiappevent.md)。 +以下仅提供简单的接口介绍,API接口的具体使用说明(参数使用限制、具体取值范围等)请参考[应用事件打点API文档](../reference/apis/js-apis-hiviewdfx-hiappevent.md)。 **打点接口功能介绍:** @@ -17,17 +17,11 @@ | write(AppEventInfo info, AsyncCallback\ callback): void | 应用事件异步打点方法,使用callback方式作为异步回调。 | | write(AppEventInfo info): Promise\ | 应用事件异步打点方法,使用Promise方式作为异步回调。 | -当采用callback作为异步回调时,可以在callback中进行下一步处理。 - -当采用Promise对象返回时,也可以在Promise对象中类似地处理接口返回值。 - -具体结果码说明见[事件校验结果码](#事件校验结果码)。 - **打点配置接口功能介绍:** -| 接口名 | 描述 | -| --------------------------------------- | ---------------------------------------------------- | -| configure(ConfigOption config): boolean | 应用事件打点配置方法,可以对打点功能进行自定义配置。 | +| 接口名 | 描述 | +| ------------------------------------ | ---------------------------------------------------- | +| configure(ConfigOption config): void | 应用事件打点配置方法,可以对打点功能进行自定义配置。 | **订阅接口功能介绍:** @@ -42,24 +36,6 @@ | ----------------- | -------------------- | | clearData(): void | 清除本地的打点数据。 | -### 事件校验结果码 - -| 错误码 | 原因 | 校验规则 | 处理结果 | -| ------ | ----------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | -| 0 | 无 | 事件校验成功 | 事件正常打点。 | -| -1 | 无效的事件名称 | 非空且长度在48个字符以内(含)。
只由以下字符组成:0-9、a-z、_。
非数字以及下划线开头。 | 忽略该事件,不执行打点。 | -| -2 | 无效的事件基本参数类型 | 事件名称参数必须为string。
事件类型参数必须为number类型。
事件参数必须为object类型。 | 忽略该事件,不执行打点。 | -| -4 | 无效的事件领域名称 | 非空且长度在32个字符以内(含)。
只由以下字符组成:0-9、a-z、_。
非数字以及下划线开头。 | 忽略该事件,不执行打点。 | -| -99 | 应用打点功能被关闭 | 应用打点功能被关闭。 | 忽略该事件,不执行打点。 | -| -100 | 未知错误 | 无。 | 忽略该事件,不执行打点。 | -| 1 | 无效的key参数名称 | 非空且长度在16个字符以内(含)。
只由以下字符组成:0-9、a-z、_。
非数字以及下划线开头。
非下划线结尾。 | 忽略该键值对参数后,继续执行打点。 | -| 2 | 无效的key参数类型 | Key参数必须为字符串类型。 | 忽略该键值对参数后,继续执行打点。 | -| 3 | 无效的value参数类型 | value参数只支持以下类型:
boolean、number、string、Array[基本类型]。 | 忽略该键值对参数后,继续执行打点。 | -| 4 | 非法长度的string类型value参数 | 参数值长度必须在8*1024个字符以内(含)。 | 对字符串进行截断(只保留前8*1024个字符)后,继续执行打点。 | -| 5 | key-value参数对数过多 | key-value参数对数必须在32对以内(含)。 | 忽略后面多余的键值对参数后,继续执行打点。 | -| 6 | 非法容量的Array类型value参数 | Array类型的value参数容量必须在100个以内(含)。 | 对数组进行截断(只保留前100个元素)后,继续执行打点。 | -| 7 | 非法类型的Array类型value参数 | Array内的参数必须为同一类型,且只能为boolean、number、string类型。 | 忽略该键值对参数后,继续执行打点。 | - ## 开发步骤 以一次应用事件打点订阅流程为例,说明开发步骤。 @@ -67,7 +43,7 @@ 1. 新建一个ets应用工程,编辑工程中的“entry > src > main > ets > pages > index.ets” 文件,依次添加三个按钮,以对应用事件打点订阅流程进行模拟。其中,按钮1模拟了应用事件打点的调用,按钮2模拟了添加自动触发回调的事件订阅者的调用,按钮3模拟了移除事件订阅者的调用,完整示例代码如下: ```ts - import hiAppEvent from '@ohos.hiAppEvent'; + import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'; @Entry @Component @@ -91,10 +67,10 @@ int_data: 100, str_data: "strValue" } - }).then((value) => { - console.log(`HiAppEvent success to write event: ${value}`); + }).then(() => { + console.log(`HiAppEvent success to write event`); }).catch((err) => { - console.error(`HiAppEvent failed to write event because ${err.code}`); + console.error(`code: ${err.code}, message: ${err.message}`); }); }) diff --git a/zh-cn/application-dev/dfx/hiappevent-overview.md b/zh-cn/application-dev/dfx/hiappevent-overview.md index 49d4a3baf10bec20a6239b24835fadba32271187..0a6d27bebe4dcd32a06284d31734267413ceb86d 100644 --- a/zh-cn/application-dev/dfx/hiappevent-overview.md +++ b/zh-cn/application-dev/dfx/hiappevent-overview.md @@ -4,7 +4,7 @@ HiAppEvent提供了应用事件打点接口,为应用提供事件打点的功 ## 基本概念 -HiAppEvent模块支持应用事件业务的开发,提供应用事件相关的功能,主要包括应用事件落盘、应用事件订阅、应用事件清理等功能。 +HiAppEvent模块支持应用事件业务的开发,提供应用事件相关的功能,主要包括应用事件落盘、应用事件订阅、应用事件清理、打点功能配置等功能。 **打点**:记录由用户操作引起的变化,提供业务数据信息,以供开发、产品、运维分析。 diff --git a/zh-cn/application-dev/internationalization/intl-guidelines.md b/zh-cn/application-dev/internationalization/intl-guidelines.md index 43d9e901f50bb1f1f8a3edf1bbc74295e85b409a..585764dac20d89d1e7d5691bfa0a0e240c945f57 100644 --- a/zh-cn/application-dev/internationalization/intl-guidelines.md +++ b/zh-cn/application-dev/internationalization/intl-guidelines.md @@ -324,4 +324,4 @@ -[`International`:国际化(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/UI/International) --[`International`:国际化(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) \ No newline at end of file +-[`International`:国际化(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/International) \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-capturer.md b/zh-cn/application-dev/media/audio-capturer.md index 3e91bd1d882e92ada0912066eec69b1df746e528..6d37e14b6d39f0db6e47c0084e2b060289e99863 100644 --- a/zh-cn/application-dev/media/audio-capturer.md +++ b/zh-cn/application-dev/media/audio-capturer.md @@ -1,77 +1,88 @@ # 音频采集开发指导 -## 场景介绍 +## 简介 -AudioCapturer提供了用于获取原始音频文件的方法。开发者可以通过本指导了解应用如何通过AudioCapturer采集音频。 +AudioCapturer提供了用于获取原始音频文件的方法。开发者可以通过本指导了解应用如何通过AudioCapturer接口的调用实现音频数据的采集。 -### 状态检查 +- **状态检查**:在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioCapturer的状态变更。因为针对AudioCapturer的某些操作,仅在音频采集器在固定状态时才能执行。如果应用在音频采集器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。 -在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioCapturer的状态变更。因为针对AudioCapturer的某些操作,仅在音频采集器在固定状态时才能执行。如果应用在音频采集器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。 +## 运作机制 -详细API含义可参考:[音频管理API文档AudioCapturer](../reference/apis/js-apis-audio.md#audiocapturer8) +该模块提供了音频采集模块的状态变化示意图 + +**图1** 音频采集状态变化示意图 + +![audio-capturer-state](figures/audio-capturer-state.png) + +**PREPARED状态:** 通过调用create()方法进入到该状态。
+**RUNNING状态:** 正在进行音频数据播放,可以在prepared状态通过调用start()方法进入此状态,也可以在stopped状态通过调用start()方法进入此状态。
+**STOPPED状态:** 在running状态可以通过stop()方法停止音频数据的播放。
+**RELEASED状态:** 在prepared和stop状态,用户均可通过release()方法释放掉所有占用的硬件和软件资源,并且不会再进入到其他的任何一种状态了。
+ +## 约束与限制 -**图1** 音频采集状态机 +开发者在进行音频数据采集功能开发前,需要先对所开发的应用配置麦克风权限(ohos.permission.MICROPHONE),权限配置相关内容可参考:[访问控制授权申请指导](../security/accesstoken-guidelines.md) -![](figures/audio-capturer-state.png) +## 开发指导 -## 开发步骤 +详细API含义可参考:[音频管理API文档AudioCapturer](../reference/apis/js-apis-audio.md#audiocapturer8) 1. 使用createAudioCapturer()创建一个AudioCapturer实例。 在audioCapturerOptions中设置音频采集器的相关参数。该实例可用于音频采集、控制和获取采集状态,以及注册通知回调。 ```js - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioCapturerInfo = { - source: audio.SourceType.SOURCE_TYPE_MIC, - capturerFlags: 1 - } - - var audioCapturerOptions = { - streamInfo: audioStreamInfo, - capturerInfo: audioCapturerInfo - } - - let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); - var state = audioRenderer.state; + var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + var audioCapturerInfo = { + source: audio.SourceType.SOURCE_TYPE_MIC, + capturerFlags: 1 + } + + var audioCapturerOptions = { + streamInfo: audioStreamInfo, + capturerInfo: audioCapturerInfo + } + + let audioCapturer = await audio.createAudioCapturer(audioCapturerOptions); + var state = audioRenderer.state; ``` 2. (可选)使用on('stateChange')订阅音频采集器状态更改。 -如果应用需要在采集器状态更新时进行一些操作,可以订阅该事件。更多事件请参考[API参考文档](../reference/apis/js-apis-audio.md)。 - - ```js - audioCapturer.on('stateChange',(state) => { - console.info('AudioCapturerLog: Changed State to : ' + state) - switch (state) { - case audio.AudioState.STATE_PREPARED: - console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); - console.info('Audio State is : Prepared'); - break; - case audio.AudioState.STATE_RUNNING: - console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); - console.info('Audio State is : Running'); - break; - case audio.AudioState.STATE_STOPPED: - console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); - console.info('Audio State is : stopped'); - break; - case audio.AudioState.STATE_RELEASED: - console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); - console.info('Audio State is : released'); - break; - default: - console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); - console.info('Audio State is : invalid'); - break; - } - }); - ``` + 如果应用需要在采集器状态更新时进行一些操作,可以订阅该事件。更多事件请参考[API参考文档](../reference/apis/js-apis-audio.md)。 + + ```js + audioCapturer.on('stateChange',(state) => { + console.info('AudioCapturerLog: Changed State to : ' + state) + switch (state) { + case audio.AudioState.STATE_PREPARED: + console.info('--------CHANGE IN AUDIO STATE----------PREPARED--------------'); + console.info('Audio State is : Prepared'); + break; + case audio.AudioState.STATE_RUNNING: + console.info('--------CHANGE IN AUDIO STATE----------RUNNING--------------'); + console.info('Audio State is : Running'); + break; + case audio.AudioState.STATE_STOPPED: + console.info('--------CHANGE IN AUDIO STATE----------STOPPED--------------'); + console.info('Audio State is : stopped'); + break; + case audio.AudioState.STATE_RELEASED: + console.info('--------CHANGE IN AUDIO STATE----------RELEASED--------------'); + console.info('Audio State is : released'); + break; + default: + console.info('--------CHANGE IN AUDIO STATE----------INVALID--------------'); + console.info('Audio State is : invalid'); + break; + } + }); + ``` 3. 调用start()方法来启动/恢复采集任务。 @@ -131,7 +142,7 @@ AudioCapturer提供了用于获取原始音频文件的方法。开发者可以 6. 采集完成后,调用stop方法,停止录制。 - ``` + ```js await audioCapturer.stop(); if (audioCapturer.state == audio.AudioState.STATE_STOPPED) { console.info('AudioRecLog: Capturer stopped'); diff --git a/zh-cn/application-dev/media/audio-interruptmode.md b/zh-cn/application-dev/media/audio-interruptmode.md index 897fa18ec4091959fc8883d637d53f14c7b9e8b8..b6b112551bd1354f46df67d60700e429f9619677 100644 --- a/zh-cn/application-dev/media/audio-interruptmode.md +++ b/zh-cn/application-dev/media/audio-interruptmode.md @@ -1,19 +1,16 @@ # 音频焦点模式开发指导 -## 场景介绍 +## 简介 音频焦点模式指的是应用内,允许对多个声音的播放进行控制。
音频应用可以在AudioRenderer下设置独立焦点模式、共享焦点模式。
当设置在共享的模式下,多个音频共用一个会话ID;独立焦点模式下,每一个音频拥有单独会话ID。 -### 异步操作 +- **异步操作**:为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数。 -为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数。 - -## 开发步骤 +## 开发指导 详细API含义可参考:[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8) - 1. 使用createAudioRenderer()创建一个AudioRenderer实例。
在audioRendererOptions中设置相关参数。
该实例可用于音频渲染、控制和获取采集状态,以及注册通知回调。
@@ -21,25 +18,25 @@ ```js import audio from '@ohos.multimedia.audio'; - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 - } - - var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 + } + + var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` 2. 设置焦点模式。 diff --git a/zh-cn/application-dev/media/audio-playback.md b/zh-cn/application-dev/media/audio-playback.md index 3ca354a1305c8e1282367633aba33c3c098bbac7..5b833306e08d8370f6d8433fdcc3dd91f9af01ce 100644 --- a/zh-cn/application-dev/media/audio-playback.md +++ b/zh-cn/application-dev/media/audio-playback.md @@ -266,5 +266,5 @@ export class AudioDemo { - [`JsDistributedMusicPlayer:`分布式音乐播放(JS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ability/JsDistributedMusicPlayer) - [`JsAudioPlayer`:音频播放和管理(JS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/JsAudioPlayer) -- [`eTsAudioPlayer`: 音频播放器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) -- [音频播放器(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) \ No newline at end of file +- [`eTsAudioPlayer`: 音频播放器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) +- [音频播放器(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-recorder.md b/zh-cn/application-dev/media/audio-recorder.md index 94215fe834e26b66115046fbe543137371ed5912..1da8cf5cc671fb009f9442008569a30b489c6582 100644 --- a/zh-cn/application-dev/media/audio-recorder.md +++ b/zh-cn/application-dev/media/audio-recorder.md @@ -200,6 +200,6 @@ export class AudioRecorderDemo { 针对音频录制开发,有以下相关实例可供参考: -- [`Recorder:`录音机(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Recorder) -- [`eTsAudioPlayer`: 音频播放器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) -- [音频播放器(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) +- [`Recorder:`录音机(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Recorder) +- [`eTsAudioPlayer`: 音频播放器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/blob/master/media/Recorder/entry/src/main/ets/MainAbility/pages/Play.ets) +- [音频播放器(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/Media/Audio_OH_ETS) diff --git a/zh-cn/application-dev/media/audio-renderer.md b/zh-cn/application-dev/media/audio-renderer.md index 4a59bcca5437b48825408f79bccf7526ef90a064..1e573b9a1edf423c9bb57fac7b337625798d95c8 100644 --- a/zh-cn/application-dev/media/audio-renderer.md +++ b/zh-cn/application-dev/media/audio-renderer.md @@ -1,52 +1,53 @@ # 音频渲染开发指导 -## 场景介绍 +## 简介 -AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可以通过本指导,了解如何在输出设备中播放音频文件并管理播放任务。 +AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可以通过本指导,了解如何在输出设备中播放音频文件并管理播放任务。同时,AudioRenderer支持音频中断的功能。 +开发者在调用AudioRenderer提供的各个接口时,需要理解以下名词: -同时,AudioRenderer支持音频中断的功能。 +- **音频中断**:当优先级较高的音频流需要播放时,AudioRenderer会中断优先级较低的流。例如,当用户在收听音乐时有来电,则优先级较低音乐播放将被暂停。 +- **状态检查**:在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioRenderer的状态变更。因为针对AudioRenderer的某些操作,仅在音频播放器在固定状态时才能执行。如果应用在音频播放器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。 +- **异步操作**:为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数,更多方式可参考[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8)。 -### 音频中断 +## 运作机制 -当优先级较高的音频流需要播放时,AudioRenderer会中断优先级较低的流。例如,当用户在收听音乐时有来电,则优先级较低音乐播放将被暂停,具体可参考[开发步骤](#开发步骤)。 +该模块提供了音频渲染模块的状态变化示意 -### 状态检查 +**图1** 音频渲染状态示意图 -在进行应用开发的过程中,建议开发者通过on('stateChange')方法订阅AudioRenderer的状态变更。因为针对AudioRenderer的某些操作,仅在音频播放器在固定状态时才能执行。如果应用在音频播放器处于错误状态时执行操作,系统可能会抛出异常或生成其他未定义的行为。 +![audio-renderer-state](figures/audio-renderer-state.png) -**图1** 音频渲染状态机 +**PREPARED状态:** 通过调用create()方法进入到该状态。
+**RUNNING状态:** 正在进行音频数据播放,可以在prepared状态通过调用start()方法进入此状态,也可以在pause状态和stopped状态通过调用start()方法进入此状态。
+**PAUSED状态:** 在running状态可以通过pause()方法暂停音频数据的播放,暂停播放之后可以通过调用start()方法继续音频数据播放。
+**STOPPED状态:** 在paused状态可以通过调用stop()方法停止音频数据的播放,在running状态可以通过stop()方法停止音频数据的播放。
+**RELEASED状态:** 在prepared、paused、stop等状态,用户均可通过release()方法释放掉所有占用的硬件和软件资源,并且不会再进入到其他的任何一种状态了。
-![](figures/audio-renderer-state.png) - -### 异步操作 - -为保证UI线程不被阻塞,大部分AudioRenderer调用都是异步的。对于每个API均提供了callback函数和Promise函数,以下示例均采用Promise函数,更多方式可参考[音频管理API文档AudioRenderer](../reference/apis/js-apis-audio.md#audiorenderer8)。 - -## 开发步骤 +## 开发指导 1. 使用createAudioRenderer()创建一个AudioRenderer实例。 在audioCapturerOptions中设置相关参数。该实例可用于音频渲染、控制和获取采集状态,以及注册通知回调。 ```js - var audioStreamInfo = { - samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, - channels: audio.AudioChannel.CHANNEL_1, - sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, - encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW - } - - var audioRendererInfo = { - content: audio.ContentType.CONTENT_TYPE_SPEECH, - usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, - rendererFlags: 1 - } - - var audioRendererOptions = { - streamInfo: audioStreamInfo, - rendererInfo: audioRendererInfo - } - - let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); + var audioStreamInfo = { + samplingRate: audio.AudioSamplingRate.SAMPLE_RATE_44100, + channels: audio.AudioChannel.CHANNEL_1, + sampleFormat: audio.AudioSampleFormat.SAMPLE_FORMAT_S16LE, + encodingType: audio.AudioEncodingType.ENCODING_TYPE_RAW + } + + var audioRendererInfo = { + content: audio.ContentType.CONTENT_TYPE_SPEECH, + usage: audio.StreamUsage.STREAM_USAGE_VOICE_COMMUNICATION, + rendererFlags: 1 + } + + var audioRendererOptions = { + streamInfo: audioStreamInfo, + rendererInfo: audioRendererInfo + } + + let audioRenderer = await audio.createAudioRenderer(audioRendererOptions); ``` 2. 使用on('interrupt')方法订阅音频中断事件。 @@ -58,49 +59,49 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 在音频中断的情况下,应用可能会碰到音频数据写入失败的问题。所以建议不感知、不处理中断的应用在写入音频数据前,使用audioRenderer.state检查播放器状态。而订阅音频中断事件,可以获取到更多详细信息,具体可参考[InterruptEvent](../reference/apis/js-apis-audio.md#interruptevent9)。 ```js - audioRenderer.on('interrupt', (interruptEvent) => { - console.info('InterruptEvent Received'); - console.info('InterruptType: ' + interruptEvent.eventType); - console.info('InterruptForceType: ' + interruptEvent.forceType); - console.info('AInterruptHint: ' + interruptEvent.hintType); - - if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { - switch (interruptEvent.hintType) { - // Force Pause: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - break; - // Force Stop: Action was taken by framework. - // Halt the write calls to avoid data loss. - case audio.InterruptHint.INTERRUPT_HINT_STOP: - isPlay = false; - break; - // Force Duck: Action was taken by framework, - // just notifying the app that volume has been reduced. - case audio.InterruptHint.INTERRUPT_HINT_DUCK: - break; - // Force Unduck: Action was taken by framework, - // just notifying the app that volume has been restored. - case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: - break; - } - } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { - switch (interruptEvent.hintType) { - // Share Resume: Action is to be taken by App. - // Resume the force paused stream if required. - case audio.InterruptHint.INTERRUPT_HINT_RESUME: - startRenderer(); - break; - // Share Pause: Stream has been interrupted, - // It can choose to pause or play concurrently. - case audio.InterruptHint.INTERRUPT_HINT_PAUSE: - isPlay = false; - pauseRenderer(); - break; - } - } - }); + audioRenderer.on('interrupt', (interruptEvent) => { + console.info('InterruptEvent Received'); + console.info('InterruptType: ' + interruptEvent.eventType); + console.info('InterruptForceType: ' + interruptEvent.forceType); + console.info('AInterruptHint: ' + interruptEvent.hintType); + + if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_FORCE) { + switch (interruptEvent.hintType) { + // Force Pause: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + break; + // Force Stop: Action was taken by framework. + // Halt the write calls to avoid data loss. + case audio.InterruptHint.INTERRUPT_HINT_STOP: + isPlay = false; + break; + // Force Duck: Action was taken by framework, + // just notifying the app that volume has been reduced. + case audio.InterruptHint.INTERRUPT_HINT_DUCK: + break; + // Force Unduck: Action was taken by framework, + // just notifying the app that volume has been restored. + case audio.InterruptHint.INTERRUPT_HINT_UNDUCK: + break; + } + } else if (interruptEvent.forceType == audio.InterruptForceType.INTERRUPT_SHARE) { + switch (interruptEvent.hintType) { + // Share Resume: Action is to be taken by App. + // Resume the force paused stream if required. + case audio.InterruptHint.INTERRUPT_HINT_RESUME: + startRenderer(); + break; + // Share Pause: Stream has been interrupted, + // It can choose to pause or play concurrently. + case audio.InterruptHint.INTERRUPT_HINT_PAUSE: + isPlay = false; + pauseRenderer(); + break; + } + } + }); ``` 3. 调用start()方法来启动/恢复播放任务。 @@ -108,24 +109,24 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 启动完成后,渲染器状态将变更为STATE_RUNNING,然后应用可以开始读取缓冲区。 ```js - async function startRenderer() { - var state = audioRenderer.state; - // state should be prepared, paused or stopped. - if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || - state != audio.AudioState.STATE_STOPPED) { - console.info('Renderer is not in a correct state to start'); - return; - } - - await audioRenderer.start(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_RUNNING) { - console.info('Renderer started'); - } else { - console.error('Renderer start failed'); - } - } + async function startRenderer() { + var state = audioRenderer.state; + // state should be prepared, paused or stopped. + if (state != audio.AudioState.STATE_PREPARED || state != audio.AudioState.STATE_PAUSED || + state != audio.AudioState.STATE_STOPPED) { + console.info('Renderer is not in a correct state to start'); + return; + } + + await audioRenderer.start(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_RUNNING) { + console.info('Renderer started'); + } else { + console.error('Renderer start failed'); + } + } ``` 4. 调用write()方法向缓冲区写入数据。 @@ -133,83 +134,83 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 将需要播放的音频数据读入缓冲区,重复调用write()方法写入。 ```js - async function writeBuffer(buf) { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.error('Renderer is not running, do not write'); - isPlay = false; - return; - } - let writtenbytes = await audioRenderer.write(buf); - - console.info('Actual written bytes: ' + writtenbytes); - if (writtenbytes < 0) { - console.error('Write buffer failed. check the state of renderer'); - } - } - - // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. - const bufferSize = await audioRenderer.getBufferSize(); - const path = '/data/file_example_WAV_2MG.wav'; - let ss = fileio.createStreamSync(path, 'r'); - const totalSize = 2146166; // file_example_WAV_2MG.wav - let rlen = 0; - let discardHeader = new ArrayBuffer(44); - ss.readSync(discardHeader); - rlen += 44; + async function writeBuffer(buf) { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.error('Renderer is not running, do not write'); + isPlay = false; + return; + } + let writtenbytes = await audioRenderer.write(buf); + + console.info('Actual written bytes: ' + writtenbytes); + if (writtenbytes < 0) { + console.error('Write buffer failed. check the state of renderer'); + } + } - var id = setInterval(() => { - if (isPlay || isRelease) { - if (rlen >= totalSize || isRelease) { - ss.closeSync(); - stopRenderer(); - clearInterval(id); - } - let buf = new ArrayBuffer(bufferSize); - rlen += ss.readSync(buf); - console.info('Total bytes read from file: ' + rlen); - writeBuffer(buf); - } else { - console.info('check after next interval'); - } - } , 30); // interval to be set based on audio file format + // Reasonable minimum buffer size for renderer. However, the renderer can accept other read sizes as well. + const bufferSize = await audioRenderer.getBufferSize(); + const path = '/data/file_example_WAV_2MG.wav'; + let ss = fileio.createStreamSync(path, 'r'); + const totalSize = 2146166; // file_example_WAV_2MG.wav + let rlen = 0; + let discardHeader = new ArrayBuffer(44); + ss.readSync(discardHeader); + rlen += 44; + + var id = setInterval(() => { + if (isPlay || isRelease) { + if (rlen >= totalSize || isRelease) { + ss.closeSync(); + stopRenderer(); + clearInterval(id); + } + let buf = new ArrayBuffer(bufferSize); + rlen += ss.readSync(buf); + console.info('Total bytes read from file: ' + rlen); + writeBuffer(buf); + } else { + console.info('check after next interval'); + } + } , 30); // interval to be set based on audio file format ``` 5. (可选)调用pause()方法或stop()方法暂停/停止渲染音频数据。 ```js - async function pauseRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING) { - console.info('Renderer is not running'); - return; - } - - await audioRenderer.pause(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_PAUSED) { - console.info('Renderer paused'); - } else { - console.error('Renderer pause failed'); - } - } - - async function stopRenderer() { - var state = audioRenderer.state; - if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { - console.info('Renderer is not running or paused'); - return; - } - - await audioRenderer.stop(); - - state = audioRenderer.state; - if (state == audio.AudioState.STATE_STOPPED) { - console.info('Renderer stopped'); - } else { - console.error('Renderer stop failed'); - } + async function pauseRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING) { + console.info('Renderer is not running'); + return; + } + + await audioRenderer.pause(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_PAUSED) { + console.info('Renderer paused'); + } else { + console.error('Renderer pause failed'); + } + } + + async function stopRenderer() { + var state = audioRenderer.state; + if (state != audio.AudioState.STATE_RUNNING || state != audio.AudioState.STATE_PAUSED) { + console.info('Renderer is not running or paused'); + return; + } + + await audioRenderer.stop(); + + state = audioRenderer.state; + if (state == audio.AudioState.STATE_STOPPED) { + console.info('Renderer stopped'); + } else { + console.error('Renderer stop failed'); + } } ``` @@ -218,20 +219,20 @@ AudioRenderer提供了渲染音频文件和控制播放的接口,开发者可 AudioRenderer会使用大量的系统资源,所以请确保完成相关任务后,进行资源释放。 ```js - async function releaseRenderer() { - if (state_ == RELEASED || state_ == NEW) { - console.info('Resourced already released'); - return; - } - - await audioRenderer.release(); - - state = audioRenderer.state; - if (state == STATE_RELEASED) { - console.info('Renderer released'); - } else { - console.info('Renderer release failed'); - } - - } + async function releaseRenderer() { + if (state_ == RELEASED || state_ == NEW) { + console.info('Resourced already released'); + return; + } + + await audioRenderer.release(); + + state = audioRenderer.state; + if (state == STATE_RELEASED) { + console.info('Renderer released'); + } else { + console.info('Renderer release failed'); + } + + } ``` \ No newline at end of file diff --git a/zh-cn/application-dev/media/audio-stream-manager.md b/zh-cn/application-dev/media/audio-stream-manager.md index 84f3f7215227cfcf649edea9a4fb9184553f44aa..eae42fd248eba633fa4ad771bbd92529b93bd59e 100644 --- a/zh-cn/application-dev/media/audio-stream-manager.md +++ b/zh-cn/application-dev/media/audio-stream-manager.md @@ -1,27 +1,30 @@ # 音频流管理开发指导 -## 场景介绍 +## 简介 AudioStreamManager提供了音频流管理的方法。开发者可以通过本指导了解应用如何通过AudioStreamManager管理音频流。 -### 工作流程 +## 运作机制 -在进行应用开发的过程中,开发者需要使用getStreamManager()创建一个AudioStreamManager实例,进而通过该实例管理音频流。开发者可通过调用on('audioRendererChange')、on('audioCapturerChange')监听音频播放应用和音频录制应用,在应用状态变化、设备变化、音频属性变化时获得通知。同时可通过off('audioRendererChange')、off('audioCapturerChange')取消相关事件的监听。与此同时,开发者可以通过调用(可选)使用getCurrentAudioRendererInfoArray()获取当前音频播放应用的音频流唯一ID、音频播放客户端的UID、音频状态等信息,同理可调用getCurrentAudioCapturerInfoArray()获取音频录制应用的信息。其具体调用关系可参考音频流管理调用关系图。 - -详细API含义可参考:[音频管理API文档AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9) +该模块提供了音频流管理调用关系图 **图1** 音频流管理调用关系图 -![](figures/zh-ch_image_audio_stream_manager.png) +![zh-ch_image_audio_stream_manager](figures/zh-ch_image_audio_stream_manager.png) + +**说明**:在进行应用开发的过程中,开发者需要使用getStreamManager()创建一个AudioStreamManager实例,进而通过该实例管理音频流。开发者可通过调用on('audioRendererChange')、on('audioCapturerChange')监听音频播放应用和音频录制应用,在应用状态变化、设备变化、音频属性变化时获得通知。同时可通过off('audioRendererChange')、off('audioCapturerChange')取消相关事件的监听。与此同时,开发者可以通过调用(可选)使用getCurrentAudioRendererInfoArray()获取当前音频播放应用的音频流唯一ID、音频播放客户端的UID、音频状态等信息,同理可调用getCurrentAudioCapturerInfoArray()获取音频录制应用的信息。 -## 开发步骤 +## 开发指导 + +详细API含义可参考:[音频管理API文档AudioStreamManager](../reference/apis/js-apis-audio.md#audiostreammanager9) 1. 创建AudioStreamManager实例。 在使用AudioStreamManager的API前,需要使用getStreamManager()创建一个AudioStreamManager实例。 ```js - var audioStreamManager = audio.getStreamManager(); + var audioManager = audio.getAudioManager(); + var audioStreamManager = audioManager.getStreamManager(); ``` 2. (可选)使用on('audioRendererChange')监听音频渲染器更改事件。 diff --git a/zh-cn/application-dev/media/camera.md b/zh-cn/application-dev/media/camera.md index 044535a7ce6c5d80f236b49399c2076108483bc3..5840b57d53683eb3252ce9cf1ae6514240ff963a 100644 --- a/zh-cn/application-dev/media/camera.md +++ b/zh-cn/application-dev/media/camera.md @@ -16,7 +16,7 @@ Xcomponent创建方法可参考:[XComponent创建方法](#xcomponent创建方法) -拍照保存接口可参考:[图片处理API文档](../reference/apis/js-apis-image.md) +拍照保存接口可参考:[图片处理API文档](image.md#imagereceiver的使用) #### 创建实例 diff --git a/zh-cn/application-dev/media/image.md b/zh-cn/application-dev/media/image.md index 3536c857eed935735b273d047314dad492106421..8d69c76aca22570ed3a875670be6d0c3496bfa74 100644 --- a/zh-cn/application-dev/media/image.md +++ b/zh-cn/application-dev/media/image.md @@ -269,5 +269,5 @@ public async init(surfaceId: any) { 针对图片开发,有以下相关实例可供参考: -- [`Image`:图片处理(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Image) -- [`GamePuzzle`:拼图(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/GamePuzzle) \ No newline at end of file +- [`Image`:图片处理(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/Image) +- [`GamePuzzle`:拼图(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/GamePuzzle) \ No newline at end of file diff --git a/zh-cn/application-dev/media/opensles-capture.md b/zh-cn/application-dev/media/opensles-capture.md index ef458a0911c4c72e4b17953572c43e851addeb26..4c9a88531543ba15f882720fe83e512373496c2c 100644 --- a/zh-cn/application-dev/media/opensles-capture.md +++ b/zh-cn/application-dev/media/opensles-capture.md @@ -1,10 +1,10 @@ # OpenSL ES音频录制开发指导 -## 场景介绍 +## 简介 -开发者可以通过本文了解到在**OpenHarmony**如何使用 **OpenSL ES** 进行录音相关操作;当前仅实现了部分[**OpenSL ES**接口](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h),未实现接口调用后会返回**SL_RESULT_FEATURE_UNSUPPORTED**。 +开发者可以通过本文档了解在**OpenHarmony**中如何使用**OpenSL ES**进行录音相关操作;当前仅实现了部分[**OpenSL ES**接口](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h),因此调用未实现接口后会返回**SL_RESULT_FEATURE_UNSUPPORTED**。 -## 开发步骤 +## 开发指导 以下步骤描述了在**OpenHarmony**如何使用 **OpenSL ES** 开发音频录音功能: diff --git a/zh-cn/application-dev/media/opensles-playback.md b/zh-cn/application-dev/media/opensles-playback.md index 66e90957f3fe127f53714bf6615bb4f85541b61a..51108a83dc6567b4c21e69c21a0424cb1b0b951a 100644 --- a/zh-cn/application-dev/media/opensles-playback.md +++ b/zh-cn/application-dev/media/opensles-playback.md @@ -1,10 +1,10 @@ # OpenSL ES音频播放开发指导 -## 场景介绍 +## 简介 -开发者可以通过本文了解到在**OpenHarmony**如何使用**OpenSL ES**进行音频播放相关操作;当前仅实现了部分[**OpenSL ES**接口](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h),未实现接口调用后会返回**SL_RESULT_FEATURE_UNSUPPORTED** +开发者可以通过本文档了解在**OpenHarmony**中如何使用**OpenSL ES**进行音频播放相关操作;当前仅实现了部分[**OpenSL ES**接口](https://gitee.com/openharmony/third_party_opensles/blob/master/api/1.0.1/OpenSLES.h),因此调用未实现接口后会返回**SL_RESULT_FEATURE_UNSUPPORTED** -## 开发步骤 +## 开发指导 以下步骤描述了在**OpenHarmony**如何使用**OpenSL ES**开发音频播放功能: @@ -58,7 +58,7 @@ 5. 获取接口 **SL_IID_OH_BUFFERQUEUE** 的 **bufferQueueItf** 实例 - ``` + ```c++ SLOHBufferQueueItf bufferQueueItf; (*pcmPlayerObject)->GetInterface(pcmPlayerObject, SL_IID_OH_BUFFERQUEUE, &bufferQueueItf); ``` diff --git a/zh-cn/application-dev/media/video-playback.md b/zh-cn/application-dev/media/video-playback.md index b9f30aab7ed944d3a702adc002d6e18627b31414..ea6044a54b0774ebd6954839a29b931874e0558a 100644 --- a/zh-cn/application-dev/media/video-playback.md +++ b/zh-cn/application-dev/media/video-playback.md @@ -451,5 +451,5 @@ export class VideoPlayerDemo { ## 相关实例 针对视频播放开发,有以下相关实例可供参考: -- [`VideoPlayer:`视频播放(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/VideoPlayer) -- [视频播放器(eTS)(API 9)](https://gitee.com/openharmony/codelabs/tree/master/Media/VideoPlayerStage) \ No newline at end of file +- [`VideoPlayer:`视频播放(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/media/VideoPlayer) +- [视频播放器(ArkTS)(API 9)](https://gitee.com/openharmony/codelabs/tree/master/Media/VideoPlayerStage) \ No newline at end of file diff --git a/zh-cn/application-dev/napi/napi-guidelines.md b/zh-cn/application-dev/napi/napi-guidelines.md index 99035e6ecc3d55ac10888ff664e171457143ba54..84c0b827089cf8001181fa2b45b6c2b820431d57 100644 --- a/zh-cn/application-dev/napi/napi-guidelines.md +++ b/zh-cn/application-dev/napi/napi-guidelines.md @@ -643,6 +643,6 @@ export default { ``` ## 相关实例 针对Native API的开发,有以下相关实例可供参考: -- [`NativeAPI`:NativeAPI(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Native/NativeAPI) -- [第一个Native C++应用(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) -- [Native Component(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) \ No newline at end of file +- [`NativeAPI`:NativeAPI(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Native/NativeAPI) +- [第一个Native C++应用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/NativeTemplateDemo) +- [Native Component(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/NativeAPI/XComponent) \ No newline at end of file diff --git a/zh-cn/application-dev/notification/common-event.md b/zh-cn/application-dev/notification/common-event.md index 1ccccada26dfc008c6ecbe669007459e6a42ce51..74f52e4b4073d12b41a8f0588127c6dc6a6447da 100644 --- a/zh-cn/application-dev/notification/common-event.md +++ b/zh-cn/application-dev/notification/common-event.md @@ -175,6 +175,6 @@ if (this.subscriber != null) { 针对公共事件开发,有以下相关实例可供参考: -- [`CommonEvent`:订阅公共事件(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/CommonEvent) +- [`CommonEvent`:订阅公共事件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/CommonEvent) diff --git a/zh-cn/application-dev/notification/notification-guidelines.md b/zh-cn/application-dev/notification/notification-guidelines.md index 0003426cfca8a737d6cd8245140477c3afa70efa..05e9e97a51132ca686c0a27aebb3e44ed2327f04 100644 --- a/zh-cn/application-dev/notification/notification-guidelines.md +++ b/zh-cn/application-dev/notification/notification-guidelines.md @@ -262,6 +262,6 @@ Notification.cancel(1, "label", cancelCallback) 针对通知开发,有以下相关可供参考: -- [`Notification:`订阅、发送通知(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/Notification) +- [`Notification:`订阅、发送通知(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Notification/Notification) -- [`Notification`:通知(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/Notification) +- [`Notification`:通知(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/Notification) diff --git a/zh-cn/application-dev/quick-start/Readme-CN.md b/zh-cn/application-dev/quick-start/Readme-CN.md index 0789c9dcef1e697ea822f28a1939588495204758..5e82e49502ed6523d297546178ce5973e585b881 100755 --- a/zh-cn/application-dev/quick-start/Readme-CN.md +++ b/zh-cn/application-dev/quick-start/Readme-CN.md @@ -12,14 +12,14 @@ - [SysCap说明](syscap.md) - [HarmonyAppProvision配置文件](app-provision-structure.md) - - 学习eTS语言 - - [初识ets语言](ets-get-started.md) - - eTS语法(声明式UI) - - [基本UI描述](ets-basic-ui-description.md) + - 学习ArkTS语言 + - [初识ArkTS语言](arkts-get-started.md) + - ArkTS语法(声明式UI) + - [基本UI描述](arkts-basic-ui-description.md) - 状态管理 - - [基本概念](ets-state-mgmt-concepts.md) - - [页面级变量的状态管理](ets-state-mgmt-page-level.md) - - [应用级变量的状态管理](ets-state-mgmt-application-level.md) - - [动态构建UI元素](ets-dynamic-ui-elememt-building.md) - - [渲染控制](ets-rendering-control.md) - - [使用限制与扩展](ets-restrictions-and-extensions.md) \ No newline at end of file + - [基本概念](arkts-state-mgmt-concepts.md) + - [页面级变量的状态管理](arkts-state-mgmt-page-level.md) + - [应用级变量的状态管理](arkts-state-mgmt-application-level.md) + - [动态构建UI元素](arkts-dynamic-ui-elememt-building.md) + - [渲染控制](arkts-rendering-control.md) + - [使用限制与扩展](arkts-restrictions-and-extensions.md) \ No newline at end of file diff --git a/zh-cn/application-dev/quick-start/ets-basic-ui-description.md b/zh-cn/application-dev/quick-start/arkts-basic-ui-description.md similarity index 90% rename from zh-cn/application-dev/quick-start/ets-basic-ui-description.md rename to zh-cn/application-dev/quick-start/arkts-basic-ui-description.md index c9586b3d4b0782d60f981821098de87de267ca43..9bcdcd80c6716abf591cd38c90e15163c17e4fcc 100644 --- a/zh-cn/application-dev/quick-start/ets-basic-ui-description.md +++ b/zh-cn/application-dev/quick-start/arkts-basic-ui-description.md @@ -1,6 +1,6 @@ # 基本UI描述 -eTS通过装饰器@Component和@Entry装饰struct关键字声明的数据结构,构成一个自定义组件。自定义组件中提供了一个build函数,开发者需在该函数内以链式调用的方式进行基本的UI描述,UI描述的方法请参考[UI描述规范](#ui描述规范)。 +ArkTS通过装饰器@Component和@Entry装饰struct关键字声明的数据结构,构成一个自定义组件。自定义组件中提供了一个build函数,开发者需在该函数内以链式调用的方式进行基本的UI描述,UI描述的方法请参考[UI描述规范](#ui描述规范)。 ## 基本概念 @@ -29,7 +29,7 @@ eTS通过装饰器@Component和@Entry装饰struct关键字声明的数据结构 - @Preview:装饰struct, 用@Preview装饰的自定义组件可以在DevEco Studio的预览器上进行实时预览,加载页面时,将创建并呈现@Preview装饰的自定义组件。 - > **说明:** 在单个源文件中,最多可以使用10个@Preview装饰自定义组件,更多说明请参考[查看eTS组件预览效果](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596#section146052489820)。 + > **说明:** 在单个源文件中,最多可以使用10个@Preview装饰自定义组件,更多说明请参考[查看ArkTS组件预览效果](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596#section146052489820)。 - 链式调用:以 "." 链式调用的方式配置UI结构及其属性、事件等。 diff --git a/zh-cn/application-dev/quick-start/ets-dynamic-ui-elememt-building.md b/zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md similarity index 94% rename from zh-cn/application-dev/quick-start/ets-dynamic-ui-elememt-building.md rename to zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md index be7c8c0a783e48503e951bda57398b22dab6662d..83f0be992b6547d997e2723b4fb29f44a65141c3 100644 --- a/zh-cn/application-dev/quick-start/ets-dynamic-ui-elememt-building.md +++ b/zh-cn/application-dev/quick-start/arkts-dynamic-ui-elememt-building.md @@ -1,6 +1,6 @@ # 动态构建UI元素 -前面章节介绍的是如何创建一个组件内部UI结构固定的自定义组件,为了满足开发者自定义组件内部UI结构的需求,eTS同时提供了动态构建UI元素的能力。 +前面章节介绍的是如何创建一个组件内部UI结构固定的自定义组件,为了满足开发者自定义组件内部UI结构的需求,ArkTS同时提供了动态构建UI元素的能力。 ## @Builder @@ -192,7 +192,7 @@ struct CustomContainerUser { ## @Styles -eTS为了避免开发者对重复样式的设置,通过@Styles装饰器可以将多条样式设置提炼成一个方法,直接在组件声明的位置使用。@Styles装饰器将新的属性函数添加到基本组件上,如Text、Column、Button等。当前@Styles仅支持通用属性。通过@Styles装饰器可以快速定义并复用组件的自定义样式。 +ArkTS为了避免开发者对重复样式的设置,通过@Styles装饰器可以将多条样式设置提炼成一个方法,直接在组件声明的位置使用。@Styles装饰器将新的属性函数添加到基本组件上,如Text、Column、Button等。当前@Styles仅支持通用属性。通过@Styles装饰器可以快速定义并复用组件的自定义样式。 @Styles可以定义在组件内或组件外,在组件外定义时需在方法前添加function关键字,组件内定义时不需要添加function关键字。 diff --git a/zh-cn/application-dev/quick-start/arkts-get-started.md b/zh-cn/application-dev/quick-start/arkts-get-started.md new file mode 100644 index 0000000000000000000000000000000000000000..af17ba43f336ceb42634fe7636de55978fba0939 --- /dev/null +++ b/zh-cn/application-dev/quick-start/arkts-get-started.md @@ -0,0 +1,30 @@ +# 初识ArkTS语言 + +ArkTS是OpenHarmony优选的主力应用开发语言。ArkTS基于TypeScript(简称TS)语言扩展而来,是TS的超集。 + +- ArkTS继承了TS的所有特性。 + +- 当前,ArkTS在TS基础上主要扩展了[声明式UI](arkts-basic-ui-description.md)能力,让开发者以更简洁、更自然的方式开发高性能应用。 + + 当前扩展的声明式UI包括如下特性。 + + - [基本UI描述](arkts-basic-ui-description.md):ArkTS定义了各种装饰器、自定义组件、UI描述机制,再配合UI开发框架中的UI内置组件、事件方法、属性方法等共同构成了UI开发的主体。 + - [状态管理](arkts-state-mgmt-page-level.md):ArkTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之间,也可以是全局范围内的传递,还可以是 跨设备传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。 + - [动态构建UI元素](arkts-dynamic-ui-elememt-building.md):ArkTS提供了动态构建UI元素的能力,不仅可以自定义组件内部的UI结构,还可复用组件样式,扩展原生组件。 + - [渲染控制](arkts-rendering-control.md):ArkTS提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 + - [使用限制与扩展](arkts-restrictions-and-extensions.md):ArkTS在使用过程中存在限制与约束,同时也扩展了双向绑定等能力。 + +- 未来,ArkTS会结合应用开发/运行的需求持续演进,逐步提供并行和并发能力增强、类型系统增强、分布式开发范式等更多特性。 + +下面我们以一个具体的示例来说明ArkTS的基本组成。如下图所示的代码示例,UI界面会两段文本和一个按钮,当开发者点击按钮时,文本内容会从'Hello World'变为 'Hello ArkUI'。 + +![arkts-get-started](figures/arkts-get-started.png) + +这个示例中所包含的ArkTS声明式开发范式的基本组成说明如下: + +- 装饰器: 用于装饰类、结构、方法以及变量,赋予其特殊的含义,如上述示例中@Entry、@Component和@State都是装饰器。 具体而言,@Component表示这是个自定义组件;@Entry则表示这是个入口组件;@State表示组件中的状态变量,这个状态变换会引起UI变更。 +- 自定义组件:可复用的UI单元,可组合其他组件,如上述被@Component装饰的struct Hello。 +- UI描述:声明式的方法来描述UI的结构,例如build()方法中的代码块。 +- 内置组件:ArkTS中默认内置的基本组件和布局组件,开发者可以直接调用,如Column、Text、Divider、Button等。 +- 属性方法:用于组件属性的配置,如fontSize()、width()、height()、color()等,可通过链式调用的方式设置多项属性。 +- 事件方法:用于添加组件对事件的响应逻辑,统一通过事件方法进行设置,如跟随在Button后面的onClick()。 diff --git a/zh-cn/application-dev/quick-start/ets-rendering-control.md b/zh-cn/application-dev/quick-start/arkts-rendering-control.md similarity index 97% rename from zh-cn/application-dev/quick-start/ets-rendering-control.md rename to zh-cn/application-dev/quick-start/arkts-rendering-control.md index d6b632e98b904e33b5a199a4864d4bfed15e7626..71210480f08d4059409107f24d786d51e4da663f 100644 --- a/zh-cn/application-dev/quick-start/ets-rendering-control.md +++ b/zh-cn/application-dev/quick-start/arkts-rendering-control.md @@ -1,6 +1,6 @@ # 渲染控制 -eTS也提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 +ArkTS也提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 ## 条件渲染 diff --git a/zh-cn/application-dev/quick-start/ets-restrictions-and-extensions.md b/zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md similarity index 91% rename from zh-cn/application-dev/quick-start/ets-restrictions-and-extensions.md rename to zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md index 9cfdc30e912f5324c78fec14783db0a31208da68..0d7caec54ab82007b88df7d4c6684a19d9670c4f 100644 --- a/zh-cn/application-dev/quick-start/ets-restrictions-and-extensions.md +++ b/zh-cn/application-dev/quick-start/arkts-restrictions-and-extensions.md @@ -2,7 +2,7 @@ ## 在生成器函数中的使用限制 -eTS语言的使用在生成器函数中存在一定的限制: +ArkTS语言的使用在生成器函数中存在一定的限制: - 表达式仅允许在字符串(${expression})、if条件、ForEach的参数和组件的参数中使用; - 任何表达式都不能导致任何应用程序状态变量(@State、@Link、@Prop)的改变,否则会导致未定义和潜在不稳定的框架行为; @@ -12,7 +12,7 @@ eTS语言的使用在生成器函数中存在一定的限制: ## 变量的双向绑定 -eTS支持通过$$双向绑定变量,通常应用于状态值频繁改变的变量。 +ArkTS支持通过$$双向绑定变量,通常应用于状态值频繁改变的变量。 - 当前$$支持基础类型变量,以及@State、@Link和@Prop装饰的变量。 - 当前$$仅支持[bindPopup](../reference/arkui-ts/ts-universal-attributes-popup.md)属性的show参数和@State变量之间的渲染,Radio组件的checked属性。 diff --git a/zh-cn/application-dev/quick-start/ets-state-mgmt-application-level.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md similarity index 100% rename from zh-cn/application-dev/quick-start/ets-state-mgmt-application-level.md rename to zh-cn/application-dev/quick-start/arkts-state-mgmt-application-level.md diff --git a/zh-cn/application-dev/quick-start/ets-state-mgmt-concepts.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-concepts.md similarity index 86% rename from zh-cn/application-dev/quick-start/ets-state-mgmt-concepts.md rename to zh-cn/application-dev/quick-start/arkts-state-mgmt-concepts.md index 52d66dc7b834f15710e040d0e6cf52f4246c2188..b4a1c095ed531dec3796b3133673d96243b05906 100644 --- a/zh-cn/application-dev/quick-start/ets-state-mgmt-concepts.md +++ b/zh-cn/application-dev/quick-start/arkts-state-mgmt-concepts.md @@ -1,6 +1,6 @@ # 基本概念 -eTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之前,也可以时全局范围内的传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。 +ArkTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之前,也可以时全局范围内的传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。 ![](figures/CoreSpec_figures_state-mgmt-overview.png) diff --git a/zh-cn/application-dev/quick-start/ets-state-mgmt-page-level.md b/zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md similarity index 100% rename from zh-cn/application-dev/quick-start/ets-state-mgmt-page-level.md rename to zh-cn/application-dev/quick-start/arkts-state-mgmt-page-level.md diff --git a/zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md b/zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md index 9dda93f56193bdb7494d8e25e265342356742ed8..365503a1dbec87bf575f75465aa7593dc0d9c5cd 100644 --- a/zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md +++ b/zh-cn/application-dev/quick-start/deveco-studio-user-guide-for-openharmony.md @@ -6,10 +6,10 @@ HUAWEI DevEco Studio For OpenHarmony(以下简称DevEco Studio)是基于Inte [DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio/) 作为支撑OpenHarmony应用和服务开发的IDE,具有以下能力特点: -- **高效智能代码编辑**:支持eTS、JavaScript、C/C++等语言的代码高亮、代码智能补齐、代码错误检查、代码自动跳转、代码格式化、代码查找等功能,提升代码编写效率。更多详细信息,请参考[编辑器使用技巧](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-editor-usage-tips-0000001263360493)。 +- **高效智能代码编辑**:支持ArkTS、JavaScript、C/C++等语言的代码高亮、代码智能补齐、代码错误检查、代码自动跳转、代码格式化、代码查找等功能,提升代码编写效率。更多详细信息,请参考[编辑器使用技巧](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-editor-usage-tips-0000001263360493)。 - **低代码可视化开发**:丰富的UI界面编辑能力,支持自由拖拽组件和可视化数据绑定,可快速预览效果,所见即所得;同时支持卡片的零代码开发,降低开发门槛和提升界面开发效率。更多详细信息,请参考使用[低代码开发应用/服务](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-low-code-development-0000001218440652)。 - **多端双向实时预览**:支持UI界面代码的双向预览、实时预览、动态预览、组件预览以及多端设备预览,便于快速查看代码运行效果。更多详细信息,请参考[使用预览器预览应用/服务界面效果](https://developer.harmonyos.com/cn/docs/documentation/doc-guides/ohos-previewing-app-service-0000001218760596)。 -- **全新构建体系**:通过Hvigor编译构建工具,一键完成应用及服务的编译和打包,更好地支持eTS/JS开发。 +- **全新构建体系**:通过Hvigor编译构建工具,一键完成应用及服务的编译和打包,更好地支持ArkTS/JS开发。 - **一站式信息获取**:基于开发者了解、学习、开发、求助的用户旅程,在DevEco Studio中提供一站式的信息获取平台,高效支撑开发者活动。 - **高效代码调试**:提供TS、JS 、C/C++代码的断点设置,单步执行、变量查看等调试能力,提升应用及服务的问题分析效率。 diff --git a/zh-cn/application-dev/quick-start/ets-get-started.md b/zh-cn/application-dev/quick-start/ets-get-started.md deleted file mode 100644 index f00694cf57a65b67e0865305fbd868b93a0618eb..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/quick-start/ets-get-started.md +++ /dev/null @@ -1,30 +0,0 @@ -# 初识eTS语言 - -eTS(extended TypeScript)是OpenHarmony优选的主力应用开发语言。eTS基于TypeScript(简称TS)语言扩展而来,是TS的超集。 - -- eTS继承了TS的所有特性。 - -- 当前,eTS在TS基础上主要扩展了[声明式UI](ets-basic-ui-description.md)能力,让开发者以更简洁、更自然的方式开发高性能应用。 - - 当前扩展的声明式UI包括如下特性。 - - - [基本UI描述](ets-basic-ui-description.md):eTS定义了各种装饰器、自定义组件、UI描述机制,再配合UI开发框架中的UI内置组件、事件方法、属性方法等共同构成了UI开发的主体。 - - [状态管理](ets-state-mgmt-page-level.md):eTS提供了多维度的状态管理机制,在UI开发框架中,和UI相关联的数据,不仅可以在组件内使用,还可以在不同组件层级间传递,比如父子组件之间、爷孙组件之间,也可以是全局范围内的传递,还可以是 跨设备传递。另外,从数据的传递形式来看,可分为只读的单向传递和可变更的双向传递。开发者可以灵活的利用这些能力来实现数据和UI的联动。 - - [动态构建UI元素](ets-dynamic-ui-elememt-building.md):eTS提供了动态构建UI元素的能力,不仅可以自定义组件内部的UI结构,还可复用组件样式,扩展原生组件。 - - [渲染控制](ets-rendering-control.md):eTS提供了渲染控制的能力。条件渲染可根据应用的不同状态,渲染对应状态下的部分内容。循环渲染可从数据源中迭代获取数据,并在每次迭代过程中创建相应的组件。 - - [使用限制与扩展](ets-restrictions-and-extensions.md):eTS在使用过程中存在限制与约束,同时也扩展了双向绑定等能力。 - -- 未来,eTS会结合应用开发/运行的需求持续演进,逐步提供并行和并发能力增强、类型系统增强、分布式开发范式等更多特性。 - -下面我们以一个具体的示例来说明eTS的基本组成。如下图所示的代码示例,UI界面会两段文本和一个按钮,当开发者点击按钮时,文本内容会从'Hello World'变为 'Hello ArkUI'。 - -![ets-get-started](figures/ets-get-started.png) - -这个示例中所包含的eTS声明式开发范式的基本组成说明如下: - -- 装饰器: 用于装饰类、结构、方法以及变量,赋予其特殊的含义,如上述示例中@Entry、@Component和@State都是装饰器。 具体而言,@Component表示这是个自定义组件;@Entry则表示这是个入口组件;@State表示组件中的状态变量,这个状态变换会引起UI变更。 -- 自定义组件:可复用的UI单元,可组合其他组件,如上述被@Component装饰的struct Hello。 -- UI描述:声明式的方法来描述UI的结构,例如build()方法中的代码块。 -- 内置组件:eTS中默认内置的基本组件和布局组件,开发者可以直接调用,如Column、Text、Divider、Button等。 -- 属性方法:用于组件属性的配置,如fontSize()、width()、height()、color()等,可通过链式调用的方式设置多项属性。 -- 事件方法:用于添加组件对事件的响应逻辑,统一通过事件方法进行设置,如跟随在Button后面的onClick()。 diff --git a/zh-cn/application-dev/quick-start/figures/ets-get-started.png b/zh-cn/application-dev/quick-start/figures/arkts-get-started.png similarity index 100% rename from zh-cn/application-dev/quick-start/figures/ets-get-started.png rename to zh-cn/application-dev/quick-start/figures/arkts-get-started.png diff --git a/zh-cn/application-dev/reference/Readme-CN.md b/zh-cn/application-dev/reference/Readme-CN.md index c6b9716ee49861922570a40f60f2e1fd59a6756a..8f418c7d5b60e0926e4dd14e7480a7c44827ab7b 100644 --- a/zh-cn/application-dev/reference/Readme-CN.md +++ b/zh-cn/application-dev/reference/Readme-CN.md @@ -1,6 +1,6 @@ # 开发参考 - [Syscap列表](syscap-list.md) -- [组件参考(基于eTS的声明式开发范式)](arkui-ts/Readme-CN.md) +- [组件参考(基于ArkTS的声明式开发范式)](arkui-ts/Readme-CN.md) - [组件参考(兼容JS的类Web开发范式)](arkui-js/Readme-CN.md) - [JS服务卡片UI组件参考](js-service-widget-ui/Readme-CN.md) - [接口参考(JS及TS API)](apis/Readme-CN.md) diff --git a/zh-cn/application-dev/reference/apis/Readme-CN.md b/zh-cn/application-dev/reference/apis/Readme-CN.md index 87e2bda0fe1883722417ab38523d266e87ef168e..d73f1acb0377259dfdf7e07ec9794546eb7484a9 100755 --- a/zh-cn/application-dev/reference/apis/Readme-CN.md +++ b/zh-cn/application-dev/reference/apis/Readme-CN.md @@ -87,8 +87,9 @@ - bundle/[ModuleInfo (ModuleInfo)](js-apis-bundle-ModuleInfo.md) - bundle/[PermissionDef (PermissionDef)](js-apis-bundle-PermissionDef.md) - bundle/[RemoteAbilityInfo (RemoteAbilityInfo)](js-apis-bundle-remoteAbilityInfo.md) - - bundle/[ShortcutInfo (ShortcutInfo)](js-apis-bundle-ShortcutInfo.md) + - bundle/[ShortcutInfo(deprecated) (ShortcutInfo)](js-apis-bundle-ShortcutInfo.md) - bundle/[PackInfo (PackInfo)](js-apis-bundle-PackInfo.md) + - bundleManager/[ShortcutInfo (ShortcutInfo)](js-apis-bundleManager-shortcutInfo.md) - UI界面 - [@ohos.animator (动画)](js-apis-animator.md) - [@ohos.curves (插值计算)](js-apis-curve.md) @@ -148,8 +149,9 @@ - 文件管理 - [@ohos.document (文件交互)](js-apis-document.md) - [@ohos.environment (目录环境能力)](js-apis-environment.md) + - [@ohos.fileAccess (公共文件访问与管理)](js-apis-fileAccess.md) + - [@ohos.fileExtensionInfo (公共文件访问与管理属性信息)](js-apis-fileExtensionInfo.md) - [@ohos.fileio (文件管理)](js-apis-fileio.md) - - [@ohos.fileManager (公共文件访问与管理)](js-apis-filemanager.md) - [@ohos.filemanagement.userfile_manager (用户数据管理)](js-apis-userfilemanager.md) - [@ohos.multimedia.medialibrary (媒体库管理)](js-apis-medialibrary.md) - [@ohos.securityLabel (数据标签)](js-apis-securityLabel.md) diff --git a/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md b/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md index a32fdcc7d7e01ff4e05ce885ec2cdfeee288c6dc..33cd88b59c5953e0687672264df84eac590f6efb 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md +++ b/zh-cn/application-dev/reference/apis/js-apis-Bundle-distributedBundle.md @@ -24,7 +24,9 @@ SystemCapability.BundleManager.DistributedBundleFramework 权限等级参考[权限等级说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md#%E6%9D%83%E9%99%90%E7%AD%89%E7%BA%A7%E8%AF%B4%E6%98%8E) -## distributedBundle.getRemoteAbilityInfo +## distributedBundle.getRemoteAbilityInfodeprecated + +> 从API version 9开始不再维护,建议使用[getRemoteAbilityInfo](js-apis-distributedBundle.md)替代。 getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback<RemoteAbilityInfo>): void; @@ -51,7 +53,9 @@ SystemCapability.BundleManager.DistributedBundleFramework -## distributedBundle.getRemoteAbilityInfo +## distributedBundle.getRemoteAbilityInfodeprecated + +> 从API version 9开始不再维护,建议使用[getRemoteAbilityInfo](js-apis-distributedBundle.md)替代。 getRemoteAbilityInfo(elementName: ElementName): Promise<RemoteAbilityInfo> @@ -81,7 +85,9 @@ SystemCapability.BundleManager.DistributedBundleFramework | ------------------------------------------------------------ | --------------------------------- | | Promise\<[RemoteAbilityInfo](js-apis-bundle-remoteAbilityInfo.md)> | Promise形式返回远程基本能力信息。 | -## distributedBundle.getRemoteAbilityInfos +## distributedBundle.getRemoteAbilityInfosdeprecated + +> 从API version 9开始不再维护,建议使用[getRemoteAbilityInfo](js-apis-distributedBundle.md)替代。 getRemoteAbilityInfos(elementNames: Array<ElementName>, callback: AsyncCallback<Array<RemoteAbilityInfo>>): void; @@ -108,7 +114,9 @@ SystemCapability.BundleManager.DistributedBundleFramework -## distributedBundle.getRemoteAbilityInfos +## distributedBundle.getRemoteAbilityInfosdeprecated + +> 从API version 9开始不再维护,建议使用[getRemoteAbilityInfo](js-apis-distributedBundle.md)替代。 getRemoteAbilityInfos(elementNames: Array<ElementName>): Promise<Array<RemoteAbilityInfo>> diff --git a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md index a21beb5ccc2834c52f2b415b23c891bed0ae3834..5d9652b9b8b19146444f6e689ba415becf2288e3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md +++ b/zh-cn/application-dev/reference/apis/js-apis-abilityAccessCtrl.md @@ -40,7 +40,7 @@ var AtManager = abilityAccessCtrl.createAtManager(); checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> -校验应用是否授予权限,使用Promise方式异步返回结果。 +校验应用是否授予权限。使用Promise异步回调。 **系统能力:** SystemCapability.Security.AccessToken @@ -57,10 +57,17 @@ checkAccessToken(tokenID: number, permissionName: string): Promise<GrantStatu | :------------ | :---------------------------------- | | Promise<GrantStatus> | Promise对象。返回授权状态结果。 | +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | + **示例:** ```js -import privacyManager from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId @@ -96,6 +103,13 @@ verifyAccessTokenSync(tokenID: number, permissionName: string): GrantStatus | :------------ | :---------------------------------- | | [GrantStatus](#grantstatus) | 枚举实例,返回授权状态。 | +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | + **示例:** ```js @@ -109,11 +123,11 @@ console.log(`data->${JSON.stringify(data)}`); grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> -授予应用user grant权限,使用Promise方式异步返回结果。 +授予应用user grant权限。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS +**需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -131,10 +145,20 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl | :------------ | :---------------------------------- | | Promise<void> | Promise对象。无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | + **示例:** ```js -import privacyManager from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId @@ -154,11 +178,11 @@ try { grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void -授予应用user grant权限,使用callback回调异步返回结果。 +授予应用user grant权限。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS +**需要权限:** ohos.permission.GRANT_SENSITIVE_PERMISSIONS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -169,18 +193,28 @@ grantUserGrantedPermission(tokenID: number, permissionName: string, permissionFl | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | | permissionName | string | 是 | 被授予的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | -| callback | AsyncCallback<void> | 是 | 检查授予应用user grant权限的操作结果同步的回调。 | +| callback | AsyncCallback<void> | 是 | 授予应用user grant权限。当授予权限成功时,err为undefine;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | **示例:** ```js -import privacyManager from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let permissionFlag = 1; try { - AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (data, err) => { + AtManager.grantUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { if (err) { console.log(`grantUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -196,11 +230,11 @@ try { revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number): Promise<void> -撤销应用user grant权限,使用Promise方式异步返回结果。 +撤销应用user grant权限。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS +**需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -218,10 +252,20 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF | :------------ | :---------------------------------- | | Promise<void> | Promise对象。无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | + **示例:** ```js -import privacyManager from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId @@ -241,11 +285,11 @@ try { revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionFlag: number, callback: AsyncCallback<void>): void -撤销应用user grant权限,使用callback回调异步返回结果。 +撤销应用user grant权限。使用callback异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS +**需要权限:** ohos.permission.REVOKE_SENSITIVE_PERMISSIONS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -256,18 +300,28 @@ revokeUserGrantedPermission(tokenID: number, permissionName: string, permissionF | tokenID | number | 是 | 目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | | permissionName | string | 是 | 被撤销的权限名称。 | | permissionFlag | number | 是 | 授权选项,1表示下次仍需弹窗,2表示允许、禁止后不再提醒,3表示系统授权不允许更改。 | -| callback | AsyncCallback<void> | 是 | 检查撤销应用user grant权限的操作结果同步的回调。 | +| callback | AsyncCallback<void> | 是 | 撤销应用user grant权限。当撤销权限成功时,err为undefine;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | **示例:** ```js -import privacyManager from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId let permissionFlag = 1; try { - AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (data, err) => { + AtManager.revokeUserGrantedPermission(tokenID, "ohos.permission.GRANT_SENSITIVE_PERMISSIONS", permissionFlag, (err, data) => { if (err) { console.log(`revokeUserGrantedPermission fail, err->${JSON.stringify(err)}`); } else { @@ -283,11 +337,11 @@ try { getPermissionFlags(tokenID: number, permissionName: string): Promise<number> -获取指定应用的指定权限的flag,使用Promise方式异步返回结果。 +获取指定应用的指定权限的flag。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS or ohos.permission.GRANT_SENSITIVE_PERMISSIONS or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS +**需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS or ohos.permission.GRANT_SENSITIVE_PERMISSIONS or ohos.permission.REVOKE_SENSITIVE_PERMISSIONS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -304,10 +358,20 @@ getPermissionFlags(tokenID: number, permissionName: string): Promise<number&g | :------------ | :---------------------------------- | | Promise<number> | Promise对象。返回查询结果。 | +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100006 | The specified application does not support the permissions granted or ungranted as specified. | + **示例:** ```js -import privacyManager from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; let AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId @@ -327,9 +391,9 @@ try { getVersion(): Promise<number> -获取当前权限管理的数据版本,使用Promise方式异步返回结果。 +获取当前权限管理的数据版本。使用Promise异步回调。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 **系统能力:** SystemCapability.Security.AccessToken @@ -353,11 +417,11 @@ promise.then(data => { on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNameList: Array<string>, callback: Callback<PermissionStateChangeInfo>): void; -订阅指定tokenId列表与权限列表的权限状态变更事件,使用callback回调异步返回结果。 +订阅指定tokenId列表与权限列表的权限状态变更事件。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS +**需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -370,6 +434,15 @@ on(type: 'permissionStateChange', tokenIDList: Array<number>, permissionNa | permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化。 | | callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | 是 | 订阅指定tokenId与指定权限名状态变更事件的回调。| +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100004 | The listener interface is not used together. | +| 12100005 | The number of listeners exceeds the limit. | + **示例:** ```js @@ -393,9 +466,9 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionN 取消订阅指定tokenId列表与权限列表的权限状态变更事件,使用callback回调异步返回结果。 -此接口为系统接口。 +**系统接口:** 此接口为系统接口。 -**需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS +**需要权限:** ohos.permission.GET_SENSITIVE_PERMISSIONS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -408,6 +481,14 @@ off(type: 'permissionStateChange', tokenIDList: Array<number>, permissionN | permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | | callback | Callback<[PermissionStateChangeInfo](#permissionstatechangeinfo9)> | 否 | 取消订阅指定tokenId与指定权限名状态变更事件的回调。| +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100004 | The listener interface is not used together. | + **示例:** ```js @@ -427,7 +508,7 @@ try { verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStatus> -校验应用是否授予权限,使用Promise方式异步返回结果。 +校验应用是否授予权限。使用Promise异步回调。 > **说明:** 从API version 9开始不再维护,建议使用[checkAccessToken](#checkaccesstoken9)替代。 @@ -437,7 +518,7 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | -| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得 | +| tokenID | number | 是 | 要校验的目标应用的身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | string | 是 | 需要校验的权限名称。 | **返回值:** @@ -449,7 +530,7 @@ verifyAccessToken(tokenID: number, permissionName: string): Promise<GrantStat **示例:** ```js -import privacyManager from '@ohos.abilityAccessCtrl'; +import abilityAccessCtrl from '@ohos.abilityAccessCtrl'; var AtManager = abilityAccessCtrl.createAtManager(); let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId @@ -489,7 +570,7 @@ promise.then(data => { **系统接口:** 此接口为系统接口。 - **系统能力:** SystemCapability.Security.AccessToken +**系统能力:** SystemCapability.Security.AccessToken | 名称 | 类型 | 可读 | 可写 | 说明 | | -------------- | ------------------------- | ---- | ---- | ------------------ | diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md new file mode 100644 index 0000000000000000000000000000000000000000..738f1d435cc9b122042735559b2232af370c21ab --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePath.md @@ -0,0 +1,49 @@ +# 手势路径 + +GesturePath表示手势路径信息。 + +本模块用于创建辅助功能注入手势所需的手势路径信息。 + +>![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> +>本模块首批接口从API version 9开始支持,后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```ts +import GesturePath from "@ohos.accessibility.GesturePath"; +``` + +## GesturePath + +表示手势路径信息。 + +**系统能力**:以下各项对应的系统能力均为 SystemCapability.BarrierFree.Accessibility.Core + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ------------ | ---------------------------------------- | ---- | ---- | ------ | +| points | Array<[GesturePoint](js-apis-accessibility-GesturePoint.md#gesturepoint)> | 是 | 是 | 手势触摸点。 | +| durationTime | number | 是 | 是 | 手势总耗时, 单位为毫秒。 | + +### constructor + +constructor(durationTime: number); + +构造函数。 + +**系统能力**:SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| durationTime | number | 是 | 手势总耗时,单位为毫秒。 | + +**示例:** + +```typescript +let durationTime = 20; +let gesturePath = new GesturePath(durationTime); +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md new file mode 100644 index 0000000000000000000000000000000000000000..b5a2cd1a6c1315b6d20e1cafbde2440f14880849 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-GesturePoint.md @@ -0,0 +1,51 @@ +# 手势触摸点 + +GesturePoint表示手势触摸点。 + +本模块用于创建辅助功能注入手势所需的手势路径的触摸点信息。 + +>![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> +>本模块首批接口从API version 9开始支持,后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## 导入模块 + +```ts +import GesturePoint from "@ohos.accessibility.GesturePoint"; +``` + +## GesturePoint + +表示手势触摸点。 + +**系统能力**:以下各项对应的系统能力均为 SystemCapability.BarrierFree.Accessibility.Core + +### 属性 + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| --------- | ------ | ---- | ---- | ------- | +| positionX | number | 是 | 是 | 触摸点X坐标。 | +| positionY | number | 是 | 是 | 触摸点Y坐标。 | + +### constructor + +constructor(positionX: number, positionY: number); + +构造函数。 + +**系统能力**:SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| positionX | number | 是 | 触摸点X坐标。 | +| positionY | number | 是 | 触摸点Y坐标。 | + +**示例:** + +```typescript +let positionX = 1; +let positionY = 2; +let gesturePoint = new GesturePoint(positionX, positionY); +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md index a8fbb343f2b44e1e20e6be71a3005c773861774a..b82d3dfc5a8937c8c5af571e5c8088dc89415b2f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility-extension-context.md @@ -1,8 +1,8 @@ -# AccessibilityExtensionContext +# 辅助功能扩展上下文 AccessibilityExtensionContext是AccessibilityExtensionAbility上下文环境,继承自ExtensionContext。 -AccessibilityExtensionContext模块提供扩展的上下文的能力,包括允许配置辅助应用关注信息类型、查询节点信息、手势注入等。 +辅助功能扩展上下文模块提供辅助功能扩展的上下文环境的能力,包括允许配置辅助应用关注信息类型、查询节点信息、手势注入等。 > **说明:** > @@ -17,7 +17,7 @@ AccessibilityExtensionContext模块提供扩展的上下文的能力,包括允 import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtensionAbility' class MainAbility extends AccessibilityExtensionAbility { onConnect(): void { - console.log("AxExtensionAbility onConnect"); + console.log('AxExtensionAbility onConnect'); let axContext = this.context; } } @@ -77,7 +77,7 @@ class MainAbility extends AccessibilityExtensionAbility { setTargetBundleName(targetNames: Array\): Promise\; -设置关注的事件类型。 +设置关注的目标包名,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -91,19 +91,52 @@ setTargetBundleName(targetNames: Array\): Promise\; | 类型 | 说明 | | ---------------------- | --------------------- | -| Promise<boolean> | Promise对象。返回当前设置是否成功。 | +| Promise<void> | 无返回结果的Promise对象。 | **示例:** ```ts -this.context.setTargetBundleName(['com.ohos.mms']); +let targetNames = ['com.ohos.xyz']; +this.context.setTargetBundleName().then(() => { + console.info('set target bundle names success'); +}).catch((err) => { + console.error('failed to set target bundle names because ' + JSON.stringify(err)); +}); +``` + +## AccessibilityExtensionContext.setTargetBundleName + +setTargetBundleName(targetNames: Array\, callback: AsyncCallback\): void; + +设置关注的目标包名,使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ------------------- | ---- | -------- | +| targetNames | Array<string> | 是 | 关注的目标包名。 | +| callback | AsyncCallback<void> | 是 | 回调函数,如果设置关注的目标包名失败,则AsyncCallback中err有数据返回。 | + +**示例:** + +```ts +let targetNames = ['com.ohos.xyz']; +this.context.setTargetBundleName().then((err, data) => { + if (err) { + console.error('failed to set target bundle names because ' + JSON.stringify(err)); + return; + } + console.info('set target bundle names success'); +}); ``` ## AccessibilityExtensionContext.getFocusElement getFocusElement(isAccessibilityFocus?: boolean): Promise\; -获取焦点元素。 +获取焦点元素, 使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -117,77 +150,296 @@ getFocusElement(isAccessibilityFocus?: boolean): Promise\; | 类型 | 说明 | | ----------------------------------- | ---------------------- | -| Promise<AccessibilityElement> | Promise对象。返回当前对应的焦点元素。 | +| Promise<AccessibilityElement> | Promise对象,返回当前对应的焦点元素。 | **示例:** ```ts -this.context.getFocusElement().then(focusElement => { - console.log("AxExtensionAbility getFocusElement success"); -}) +let focusElement; +this.context.getFocusElement().then((data) => { + focusElement = data; + console.log('get focus element success'); +}).catch((err) => { + console.error('failed to get focus element because ' + JSON.stringify(err)); +}); ``` +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(callback: AsyncCallback\): void; + +获取焦点元素, 使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回当前对应的焦点元素。 | + +**示例:** + +```ts +let focusElement; +this.context.getFocusElement().then((err, data) => { + if (err) { + console.error('failed to get focus element because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); +}); +``` + +## AccessibilityExtensionContext.getFocusElement + +getFocusElement(isAccessibilityFocus: boolean, callback: AsyncCallback\): void; + +获取焦点元素, 使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------------------- | ------- | ---- | ------------------- | +| isAccessibilityFocus | boolean | 是 | 获取的是否是无障碍焦点元素。 | +| callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回当前对应的焦点元素。 | + +**示例:** + +```ts +let isAccessibilityFocus = true; +this.context.getFocusElement(isAccessibilityFocus).then((err, data) => { + if (err) { + console.error('failed to get focus element because ' + JSON.stringify(err)); + return; + } + focusElement = data; + console.info('get focus element success'); +}); +``` ## AccessibilityExtensionContext.getWindowRootElement getWindowRootElement(windowId?: number): Promise\; -获取窗口的根节点元素。 +获取指定窗口的根节点元素, 使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | -| -------- | ------ | ---- | --------------------------- | -| windowId | number | 否 | 指定获取根节点元素的窗口,未指定则从当前活跃窗口获取。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------------------- | ------- | ---- | ------------------- | +| windowId | number | 否 | 指定窗口的编号,未指定则从当前活跃窗口获取。 | **返回值:** -| 类型 | 说明 | -| ----------------------------------- | ----------------------- | -| Promise<AccessibilityElement> | Promise对象。返回当前对应的根节点元素。 | +| 类型 | 说明 | +| ----------------------------------- | ---------------------- | +| Promise<AccessibilityElement> | Promise对象,返回指定屏幕的所有窗口。 | + +**示例:** + +```ts +let rootElement; +this.context.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)); +}); +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(callback: AsyncCallback\): void; + +获取指定窗口的根节点元素, 使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回指定窗口的根节点元素。 | + +**示例:** + +```ts +let rootElement; +this.context.getWindowRootElement().then((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'); +}); +``` + +## AccessibilityExtensionContext.getWindowRootElement + +getWindowRootElement(windowId: number, callback: AsyncCallback\): void; + +获取指定屏幕中的所有窗口, 使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------------------- | ------- | ---- | ------------------- | +| windowId | number | 是 | 指定窗口的编号,未指定则从当前活跃窗口获取。 | +| callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回指定窗口的根节点元素。 | **示例:** ```ts -this.context.getWindowRootElement().then(rootElement => { - console.log("AxExtensionAbility getWindowRootElement success"); -}) +let displayId = 10; +let rootElement; +this.context.getWindowRootElement(displayId).then((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'); +}); ``` ## AccessibilityExtensionContext.getWindows -getWindows(displayId?: number): Promise>; +getWindows(displayId?: number): Promise\>; -获取用户可见的窗口列表。 +获取指定屏幕中的所有窗口, 使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core **参数:** -| 参数名 | 参数类型 | 必填 | 说明 | -| --------- | ------ | ---- | ------------------------- | -| displayId | number | 否 | 指定获取窗口信息的屏幕,未指定则从默认主屏幕获取。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | 否 | 指定的屏幕编号,未指定则从默认主屏幕获取。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------------- | ------------------------ | -| Promise<Array<AccessibilityElement>> | Promise对象。返回当前对应的窗口列表信息。 | +| 类型 | 说明 | +| ----------------------------------- | ---------------------- | +| Promise<Array<AccessibilityElement>> | Promise对象,返回指定屏幕的所有窗口。 | **示例:** ```ts -this.context.getWindows().then(windows => { - console.log("AxExtensionAbility getWindows success"); -}) +let windows; +this.context.getWindows().then((data) => { + windows = data; + console.log('get windows success'); +}).catch((err) => { + console.error('failed to get windows because ' + JSON.stringify(err)); +}); +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(callback: AsyncCallback\>): void; + +获取指定屏幕中的所有窗口, 使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<Array<AccessibilityElement>> | 是 | 回调函数,返回指定屏幕的所有窗口。 | + +**示例:** + +```ts +let windows; +this.context.getWindows().then((err, data) => { + if (err) { + console.error('failed to get windows because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); +}); +``` + +## AccessibilityExtensionContext.getWindows + +getWindows(displayId: number, callback: AsyncCallback\>): void; + +获取指定屏幕中的所有窗口, 使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------------------- | ------- | ---- | ------------------- | +| displayId | number | 是 | 指定的屏幕编号,未指定则从默认主屏幕获取。 | +| callback | AsyncCallback<Array<AccessibilityElement>> | 是 | 回调函数,返回指定屏幕的所有窗口。 | + +**示例:** + +```ts +let displayId = 10; +let windows; +this.context.getWindows(displayId).then((err, data) => { + if (err) { + console.error('failed to get windows because ' + JSON.stringify(err)); + return; + } + windows = data; + console.info('get windows success'); +}); ``` ## AccessibilityExtensionContext.injectGesture +injectGesture(gesturePath: GesturePath): Promise\; + +注入手势,使用Promise异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | 是 | 表示手势的路径信息。 | + +**返回值:** + +| 类型 | 说明 | +| ----------------------------------- | ---------------------- | +| Promise<void> | 无返回结果的Promise对象。 | + +**示例:** + +```ts +import { GesturePath } from "../@ohos.accessibility.GesturePath"; +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, () => { + console.info('inject gesture success'); +}).catch((err) => { + console.error('failed to inject gesture because ' + JSON.stringify(err)); +}); +``` +## AccessibilityExtensionContext.injectGesture + injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void -注入手势。 +注入手势,使用callback异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -195,8 +447,8 @@ injectGesture(gesturePath: GesturePath, callback: AsyncCallback\): void | 参数名 | 参数类型 | 必填 | 说明 | | ----------- | ---------------------------------------- | ---- | -------------- | -| gesturePath | [GesturePath](js-apis-application-AccessibilityExtensionAbility.md#GesturePath) | 是 | 表示手势的路径信息。 | -| callback | AsyncCallback<void> | 是 | 表示注入手势执行结果的回调。 | +| gesturePath | [GesturePath](js-apis-accessibility-GesturePath.md#gesturepath) | 是 | 表示手势的路径信息。 | +| callback | AsyncCallback<void> | 是 | 回调函数,表示注入手势执行结果的回调。 | **示例:** @@ -206,15 +458,25 @@ 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); -}) +this.context.gestureInject(gesturePath, (err, data) => { + if (err) { + console.error('failed to inject gesture because ' + JSON.stringify(err)); + return; + } + console.info('inject gesture success'); +}); ``` -## AccessibilityElement.attributeNames +## AccessibilityElement9 + +无障碍节点元素。 + +**系统能力**:以下各项对应的系统能力均为SystemCapability.BarrierFree.Accessibility.Core + +## attributeNames attributeNames\(): Promise\>; -获取节点元素的所有属性名称。 +获取节点元素的所有属性名称,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -222,28 +484,61 @@ attributeNames\(): Promise\>; | 类型 | 说明 | | ---------------------------------------- | ------------------------ | -| Promise<Array<T>> | Promise对象。返回获取元素所有属性名称的调用结果。 | +| Promise<Array<T>> | Promise对象,返回节点元素的所有属性名称。 | **示例:** ```ts let accessibilityElement; +let attributeNames; try { - accessibilityElement.attributeNames().then((values) => { - console.log("get attribute names success"); + accessibilityElement.attributeNames().then((data) => { + console.log('get attribute names success'); + attributeNames = data; }).catch((err) => { - console.log("get attribute names err: " + JSON.stringify(err)); + console.log('get attribute names err: ' + JSON.stringify(err)); }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log('An unexpected error occurred. Error:' + e); } ``` +## attributeNames + +attributeNames\(callback: AsyncCallback\>): void; + +获取节点元素的所有属性名称,使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<T>> | 是 | 回调函数,返回节点元素的所有属性名称。 | + +**示例:** +```ts +let accessibilityElement; +let attributeNames; +try { + accessibilityElement.attributeNames().then((err, data) => { + if (err) { + console.error('failed to get attribute names because ' + JSON.stringify(err)); + return; + } + attributeNames = data; + console.info('get attribute names success'); + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` ## AccessibilityElement.attributeValue attributeValue\(attributeName: T): Promise\; -根据属性名称获取属性值。 +根据属性名称获取属性值,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -257,29 +552,65 @@ attributeValue\(attributeName: T): Promi | 类型 | 说明 | | ---------------------------------------- | ------------------------ | -| Promise<Array<ElementAttributeValues[T]>> | Promise对象。返回根据属性名称获取属性值的调用结果。 | +| Promise<ElementAttributeValues[T]> | Promise对象,返回根据节点属性名称获取的属性值。 | **示例:** ```ts let accessibilityElement; +let attributeValue; try { let attributeName = 'name'; - accessibilityElement.attributeValue(attributeName).then((value) => { - console.log("get attribute value by name success"); + accessibilityElement.attributeValue(attributeName).then((data) => { + console.log('get attribute value by name success'); + attribtueValue = data; }).catch((err) => { - console.log("get attribute value by name err: " + JSON.stringify(err)); + console.log('get attribute value by name err: ' + JSON.stringify(err)); }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log('An unexpected error occurred. Error:' + e); } ``` +## AccessibilityElement.attributeValue + +attributeValue\(attributeName: T, + callback: AsyncCallback\): void; + +根据属性名称获取属性值,使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| attributeName | T | 是 | 表示属性的名称。 | +| callback | AsyncCallback<ElementAttributeValues[T]> | 是 | 回调函数,返回根据节点属性名称获取的属性值。 | + +**示例:** -## AccessibilityElement.actionNames +```ts +let accessibilityElement; +let attributeValue; +try { + let attributeName = 'name'; + accessibilityElement.attributeValue(attributeName).then((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 (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## actionNames actionNames(): Promise\>; -获取节点元素支持的所有操作名称。 +获取节点元素支持的所有操作名称,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -287,28 +618,61 @@ actionNames(): Promise\>; | 类型 | 说明 | | ---------------------------------------- | ------------------------ | -| Promise<Array<string>> | Promise对象。返回获取节点元素支持的所有操作名称的调用结果。 | +| Promise<Array<string>> | Promise对象,返回节点元素支持的所有操作名称。 | **示例:** ```ts let accessibilityElement; +let actionNames; try { - accessibilityElement.actionNames().then((values) => { - console.log("get action names success"); + accessibilityElement.actionNames().then((data) => { + console.log('get action names success'); + actionNames = data; }).catch((err) => { - console.log("get action names err: " + JSON.stringify(err)); + console.log('get action names err: ' + JSON.stringify(err)); }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log('An unexpected error occurred. Error:' + e); } ``` +## actionNames -## AccessibilityElement.performAction +actionNames(callback: AsyncCallback\>): void; + +获取节点元素支持的所有操作名称,使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数,返回节点元素支持的所有操作名称。 | + +**示例:** + +```ts +let accessibilityElement; +let actionNames; +try { + accessibilityElement.actionNames().then((err, data) => { + if (err) { + console.error('failed to get action names because ' + JSON.stringify(err)); + return; + } + actionNames = data; + console.info('get action names success'); + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## performAction performAction(actionName: string, parameters?: object): Promise\; -根据操作名称执行某个操作。 +根据操作名称执行某个操作,使用Promise异步回调。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -323,29 +687,139 @@ performAction(actionName: string, parameters?: object): Promise\; | 类型 | 说明 | | ---------------------------------------- | ------------------------ | -| Promise<Array<boolean>> | Promise对象。返回获取元素所有属性名的调用结果。 | +| Promise<boolean> | Promise对象,返回执行指定操作后的回调结果,true为执行成功,false为执行失败。 | **示例:** ```ts let accessibilityElement; +let performActionRes; try { - - accessibilityElement.performAction('action').then((result) => { - console.info('perform action result: ' + result); + accessibilityElement.performAction('action').then((data) => { + console.info('perform action success'); + performActionRes = data; }).catch((err) => { - console.log("perform action err: " + JSON.stringify(err)); + console.log('failed to perform action because ' + JSON.stringify(err)); }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log('An unexpected error occurred. Error:' + e); } ``` +## performAction + +performAction(actionName: string, callback: AsyncCallback\): void; + +根据操作名称执行某个操作,使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** -## AccessibilityElement.findElement +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | 是 | 表示属性的名称。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数,返回执行指定操作后的回调结果,true为执行成功,false为执行失败。 | + +**示例:** + +```ts +let accessibilityElement; +let performActionRes; +try { + accessibilityElement.performAction('action').then((err, data) => { + if (err) { + console.error('failed to perform action because ' + JSON.stringify(err)); + return; + } + performActionRes = data; + console.info('perform action success'); + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## performAction + +performAction(actionName: string, parameters: object, callback: AsyncCallback\): void; + +根据操作名称执行某个操作,使用callback异步回调。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| actionName | string | 是 | 表示属性的名称。 | +| parameters | object | 是 | 表示执行操作时所需要的参数。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数,返回执行指定操作后的回调结果,true为执行成功,false为执行失败。 | + +**示例:** + +```ts +let accessibilityElement; +let actionName = 'action'; +let parameters = { + 'setText': 'test text' +}; +let performActionRes; +try { + accessibilityElement.performAction(actionName, parameters).then((err, data) => { + if (err) { + console.error('failed to perform action because ' + JSON.stringify(err)); + return; + } + performActionRes = data; + console.info('perform action success'); + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## findElement('content') findElement(type: 'content', condition: string): Promise\>; -查询节点元素的指定内容。 +根据节点内容查询所有节点元素。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | 是 | 固定为'content', 表示查找的类型为节点元素内容。 | +| condition | string | 是 | 表示查找的条件。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | ------------------------ | +| Promise<Array<AccessibilityElement>> | Promise对象,返回满足指定查询关键字的所有节点元素。 | + +**示例:** + +```ts +let accessibilityElement; +let type = 'content'; +let condition = 'keyword'; +let elements; +try { + accessibilityElement.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 (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## findElement('content') + +findElement(type: 'content', condition: string, callback: AsyncCallback\>): void; + +根据节点内容查询所有节点元素。 **系统能力:** SystemCapability.BarrierFree.Accessibility.Core @@ -355,25 +829,175 @@ findElement(type: 'content', condition: string): Promise\ { + if (err) { + console.error('failed to find element because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType): Promise\; + +根据焦点元素类型查询节点元素。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | 是 | 固定为'focusType', 表示查询的类型为节点的焦点元素类型。 | +| condition | [FocusType](#focustype) | 是 | 表示查询焦点元素的类型。 | **返回值:** | 类型 | 说明 | | ---------------------------------------- | ------------------------ | -| Promise<Array<T>> | Promise对象。返回获取元素所有属性名的调用结果。 | +| Promise<AccessibilityElement> | Promise对象,返回满足指定查询焦点元素类型的节点元素。 | **示例:** ```ts let accessibilityElement; +let type = 'focusType'; +let condition = 'normal'; +let elements; try { - let condition = 'keyword'; - accessibilityElement.findElement('content', condition).then((values) => { - console.log("find element success"); + accessibilityElement.findElement(type, condition).then((data) => { + elements = data; + console.log('find element success'); }).catch((err) => { - console.log("find element err: " + JSON.stringify(err)); + console.log('failed to find element because ' + JSON.stringify(err)); + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## findElement('focusType') + +findElement(type: 'focusType', condition: FocusType, callback: AsyncCallback\): void; + +根据焦点元素类型查询节点元素。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | 是 | 固定为'focusType', 表示查询的类型为节点的焦点元素类型。 | +| condition | [FocusType](#focustype) | 是 | 表示查询焦点元素的类型。 | +| callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回满足指定查询焦点元素类型的节点元素。 | + +**示例:** + +```ts +let accessibilityElement; +let type = 'focusType'; +let condition = 'normal'; +let elements; +try { + accessibilityElement.findElement(type, condition).then((err, data) => { + if (err) { + console.error('failed to find element because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); + }); +} catch (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection): Promise\; + +根据下一焦点元素方向查询节点元素。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | 是 | 固定为'focusDirection', 表示查询的类型为节点的下一焦点元素方向。 | +| condition | [FocusDirection](#focusdirection) | 是 | 表示查询下一焦点元素的方向。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | ------------------------ | +| Promise<AccessibilityElement> | Promise对象,返回满足指定查询下一焦点元素方向的节点元素。 | + +**示例:** + +```ts +let accessibilityElement; +let type = 'focusDirection'; +let condition = 'up'; +let elements; +try { + accessibilityElement.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 (e) { + console.log('An unexpected error occurred. Error:' + e); +} +``` +## findElement('focusDirection') + +findElement(type: 'focusDirection', condition: FocusDirection, callback: AsyncCallback\): void; + +根据下一焦点元素方向查询所有节点元素。 + +**系统能力:** SystemCapability.BarrierFree.Accessibility.Core + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| ----------- | ---------------------------------------- | ---- | -------------- | +| type | string | 是 | 固定为'focusDirection', 表示查询的类型为节点的下一焦点元素方向。 | +| condition | [FocusDirection](#focusdirection) | 是 | 表示下一查询焦点元素的方向。 | +| callback | AsyncCallback<AccessibilityElement> | 是 | 回调函数,返回满足指定查询下一焦点元素方向的节点元素。 | + +**示例:** + +```ts +let accessibilityElement; +let type = 'focusDirection'; +let condition = 'up'; +let elements; +try { + accessibilityElement.findElement(type, condition).then((err, data) => { + if (err) { + console.error('failed to find element because ' + JSON.stringify(err)); + return; + } + elements = data; + console.info('find element success'); }); } catch (e) { - console.log("An unexpected error occurred. Error:" + e); + console.log('An unexpected error occurred. Error:' + e); } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-accessibility.md b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md index de981f480adff501aedf34b43da4e74b905d01f9..77311ac0c1b9cc3f9c26db1b916ef21dc3d1f10f 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-accessibility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-accessibility.md @@ -144,7 +144,7 @@ import accessibility from '@ohos.accessibility'; ## CaptionsManager8+ -字幕配置。 +字幕配置管理,在调用CaptionsManager的方法前,需要先通过 [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8)获取 captionsManager实例。 **系统能力**:以下各项对应的系统能力均为SystemCapability.BarrierFree.Accessibility.Hearing @@ -155,90 +155,92 @@ import accessibility from '@ohos.accessibility'; | enabled | boolean | 是 | 否 | 表示是否启用字幕配置。 | | style | [CaptionsStyle](#captionsstyle8) | 是 | 否 | 表示字幕风格。 | -下列 API 示例中都需要使用 [accessibility.getCaptionsManager()](#accessibilitygetcaptionsmanager8) 获取 captionsManager 实例,再通过此实例调用对应的方法。 - ### on('enableChange') on(type: 'enableChange', callback: Callback<boolean>): void; -注册字幕配置启用的监听函数。 +监听字幕配置启用状态变化事件。 -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 监听字幕配置启用状态。 | - | callback | Callback<boolean> | 是 | 回调函数,在启用状态变化时将状态通过此函数进行通知。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 监听的事件名,固定为‘enableChange’,即字幕配置启用状态变化事件。 | +| callback | Callback<boolean> | 是 | 回调函数,在启用状态变化时将状态通过此函数进行通知。 | -- **示例:** +**示例:** ```typescript - let captionsManager = accessibility.getCaptionsManager(); + let captionsManager = accessibility.getCaptionsManager(); captionsManager.on('enableChange',(data) => { console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) + }); ``` ### on('styleChange') on(type: 'styleChange', callback: Callback<CaptionsStyle>): void; -注册字幕风格变化的监听函数。 +监听字幕风格变化事件。 -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 监听字幕风格变化。 | - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | 是 | 回调函数,在字幕风格变化时通过此函数进行通知。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 监听的事件名,固定为‘styleChange’,即字幕风格变化事件。 | +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | 是 | 回调函数,在字幕风格变化时通过此函数进行通知。 | -- **示例:** +**示例:** ```typescript - let captionsManager = accessibility.getCaptionsManager(); + let captionsManager = accessibility.getCaptionsManager(); captionsManager.on('styleChange',(data) => { console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) + }); ``` ### off('enableChange') off(type: 'enableChange', callback?: Callback<boolean>): void; -移除字幕配置启用的监听函数。 +取消监听字幕配置启用状态变化事件。 -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 监听字幕配置启用状态。 | - | callback | Callback<boolean> | 否 | 回调函数,在启用状态变化时将状态通过此函数进行通知。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 取消监听的事件名,固定为‘enableChange’,即字幕配置启用状态变化事件。 | +| callback | Callback<boolean> | 否 | 回调函数,在字幕配置启用状态变化时将状态通过此函数进行通知。 | -- **示例:** +**示例:** ```typescript - let captionsManager = accessibility.getCaptionsManager(); - captionsManager.off('enableChange') + let captionsManager = accessibility.getCaptionsManager(); + captionsManager.off('enableChange',(data) => { + console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) + }); ``` ### off('styleChange') off(type: 'styleChange', callback?: Callback<CaptionsStyle>): void; -移除字幕风格变化的监听函数。 +取消字幕风格变化监听事件。 -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 字幕风格变化。 | - | callback | Callback<[CaptionsStyle](#captionsstyle8)> | 否 | 回调函数,在字幕风格变化时通过此函数进行通知。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 取消监听的事件名,固定为‘styleChange’,即字幕风格变化事件。 | +| callback | Callback<[CaptionsStyle](#captionsstyle8)> | 否 | 回调函数,在字幕风格变化时通过此函数进行通知。 | -- **示例:** +**示例:** ```typescript - let captionsManager = accessibility.getCaptionsManager(); - captionsManager.off('styleChange') + let captionsManager = accessibility.getCaptionsManager(); + captionsManager.off('styleChange',(data) => { + console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) + }); ``` ## EventInfo @@ -274,16 +276,20 @@ constructor(jsonObject) **系统能力**:SystemCapability.BarrierFree.Accessibility.Core -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | jsonObject | string | 是 | 创建对象所需要的 JSON 格式字符串。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| jsonObject | string | 是 | 创建对象所需要的 JSON 格式字符串。 | -- **示例:** +**示例:** ```typescript - let eventInfo = new accessibility.EventInfo({"type":"click","bundleName":"com.example.MyApplication","triggerAction":"click"}) + let eventInfo = new accessibility.EventInfo({ + "type":"click", + "bundleName":"com.example.MyApplication", + "triggerAction":"click" + }); ``` ## EventType @@ -338,306 +344,348 @@ constructor(jsonObject) getAbilityLists(abilityType: AbilityType, stateType: AbilityState): Promise<Array<AccessibilityAbilityInfo>> -查询辅助应用列表。 +查询辅助应用列表,使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | - | stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | +| stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | -- **返回值:** +**返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | 返回辅助应用信息列表。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | Promise对象,返回辅助应用信息列表。 | -- **示例:** +**示例:** - ```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.bundleName); - } - }).catch((error) => { - console.error('failed to getAbilityList1 because ' + JSON.stringify(error)); - }) - ``` +```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.bundleName); + } +}).catch((err) => { + console.error('failed to getAbilityList1 because ' + JSON.stringify(err)); +}); +``` ## accessibility.getAbilityLists getAbilityLists(abilityType: AbilityType, stateType: AbilityState,callback: AsyncCallback<Array<AccessibilityAbilityInfo>>): void -查询辅助应用列表。 +查询辅助应用列表,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | - | stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | - | callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | 是 | 回调函数,返回辅助应用信息列表。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| abilityType | [AbilityType](#abilitytype) | 是 | 辅助应用的类型。 | +| stateType | [AbilityState](#abilitystate) | 是 | 辅助应用的状态。 | +| callback | AsyncCallback<Array<[AccessibilityAbilityInfo](#accessibilityabilityinfo)>> | 是 | 回调函数,返回辅助应用信息列表。 | -- **示例:** +**示例:** - ```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.bundleName); - } - }) +```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.bundleName); + } +}); ``` ## accessibility.getCaptionsManager8+ getCaptionsManager(): CaptionsManager -获取无障碍字幕配置。 +获取无障碍字幕配置管理实例。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Hearing -- **返回值:** +**返回值:** - | 类型 | 说明 | - | -------- | -------- | - | [CaptionsManager](#captionsmanager8) | 无障碍字幕配置管理。 | +| 类型 | 说明 | +| -------- | -------- | +| [CaptionsManager](#captionsmanager8) | 无障碍字幕配置管理。 | -- **示例:** +**示例:** - ```typescript - let captionsManager = accessibility.getCaptionsManager() - ``` +```typescript +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 -启用辅助应用和触摸浏览功能的状态变化监听。 +监听辅助应用启用状态变化事件。 **系统能力**:以下各项对应的系统能力有所不同,详见下表。 -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 是 | 监听的事件类型。
- type 为'accessibilityStateChange'时表示监听类型为辅助功能启用状态变化监听;
**系统能力**:SystemCapability.BarrierFree.Accessibility.Core
- type 为'touchGuideStateChange'时表示监听类型为触摸浏览启用状态变化监听。
**系统能力**:SystemCapability.BarrierFree.Accessibility.Vision | - | callback | Callback<boolean> | 是 | 回调函数,在启用状态变化时将状态通过此函数进行通知。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 监听的事件名,固定为‘accessibilityStateChange’,即辅助应用启用状态变化事件。 | +| callback | Callback<boolean> | 是 | 回调函数,在辅助应用启用状态变化时将状态通过此函数进行通知。 | -- **示例:** +**示例:** - ```typescript - accessibility.on('accessibilityStateChange',(data) => { - console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```typescript +accessibility.on('accessibilityStateChange',(data) => { + console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) +}); +``` -## accessibility.off('accessibilityStateChange' | 'touchGuideStateChange') +## accessibility.on('touchGuideStateChange') -off(type: ‘accessibilityStateChange ’ | ‘touchGuideStateChange’, callback?: Callback<boolean>): void +on(type: 'touchGuideStateChange', callback: Callback<boolean>): void -关闭辅助应用和触摸浏览功能的状态变化监听。 +监听触摸浏览功能启用状态变化事件。 **系统能力**:以下各项对应的系统能力有所不同,详见下表。 -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | type | string | 否 | 监听的事件类型。
- type 为'accessibilityStateChange'时表示监听类型为辅助功能启用状态变化监听;
**系统能力**:SystemCapability.BarrierFree.Accessibility.Core
- type 为'touchGuideStateChange'时表示监听类型为触摸浏览启用状态变化监听。
**系统能力**:SystemCapability.BarrierFree.Accessibility.Vision | - | callback | Callback<boolean> | 否 | 要取消的监听回调函数。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 是 | 监听的事件名,固定为‘touchGuideStateChange’,即触摸浏览启用状态变化事件。 | +| callback | Callback<boolean> | 是 | 回调函数,在触摸浏览启用状态变化时将状态通过此函数进行通知。 | -- **示例:** +**示例:** - ```typescript - accessibility.off('accessibilityStateChange',(data) => { - console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) - }) - ``` +```typescript +accessibility.on('touchGuideStateChange',(data) => { + console.info('success data:subscribeStateObserver : ' + JSON.stringify(data)) +}); +``` + +## accessibility.off('accessibilityStateChange') + +off(type: 'accessibilityStateChange', callback?: Callback<boolean>): void + +取消监听辅助应用启用状态变化事件。 + +**系统能力**:以下各项对应的系统能力有所不同,详见下表。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 否 | 取消监听的事件名,固定为‘accessibilityStateChange’,即辅助应用启用状态变化事件。 | +| callback | Callback<boolean> | 否 | 回调函数,在辅助应用启用状态变化时将状态通过此函数进行通知。 | + +**示例:** + +```typescript +accessibility.off('accessibilityStateChange',(data) => { + console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) +}); +``` + +## accessibility.off('touchGuideStateChange') + +off(type: 'touchGuideStateChange', callback?: Callback<boolean>): void + +取消监听触摸浏览启用状态变化事件。 + +**系统能力**:以下各项对应的系统能力有所不同,详见下表。 + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| type | string | 否 | 取消监听的事件名,固定为‘touchGuideStateChange’,即触摸浏览启用状态变化事件。 | +| callback | Callback<boolean> | 否 | 回调函数,在触摸浏览启用状态变化时将状态通过此函数进行通知。 | + +**示例:** + +```typescript +accessibility.off('touchGuideStateChange',(data) => { + console.info('success data:unSubscribeStateObserver : ' + JSON.stringify(data)) +}); +``` ## accessibility.isOpenAccessibility isOpenAccessibility(): Promise<boolean> -判断是否启用了辅助功能。 +判断是否启用了辅助功能, 使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core -- **返回值:** +**返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<boolean> | 如果辅助功能已启用,则返回 true;否则返回 false。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<boolean> | Promise对象,如果辅助功能已启用,则返回 true;否则返回 false。 | -- **示例:** +**示例:** - ```typescript - accessibility.isOpenAccessibility() - .then((data) => { - console.info('success data:isOpenAccessibility : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenAccessibility because ' + JSON.stringify(error)); - }) - ``` +```typescript +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 isOpenAccessibility(callback: AsyncCallback<boolean>): void -判断是否启用了辅助功能。 +判断是否启用了辅助功能,使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | 是 | 回调函数,如果辅助功能已启用,则返回 true;否则返回 false。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | 是 | 回调函数,如果辅助功能已启用,则返回 true;否则返回 false。 | -- **示例:** +**示例:** - ```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)) - }) - ``` +```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)) +}); +``` ## accessibility.isOpenTouchGuide isOpenTouchGuide(): Promise<boolean> -判断触摸浏览模式是否开启。 +判断触摸浏览模式是否开启, 使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Vision -- **返回值:** +**返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<boolean> | 如果触摸浏览模式已开启,则返回 true;否则返回 false。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<boolean> | Promise对象,如果触摸浏览模式已开启,则返回 true;否则返回 false。 | -- **示例:** +**示例:** - ```typescript - accessibility.isOpenTouchGuide() - .then((data) => { - console.info('success data:isOpenTouchGuide : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to isOpenTouchGuide because ' + JSON.stringify(error)); - }) - ``` +```typescript +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 isOpenTouchGuide(callback: AsyncCallback<boolean>): void -判断触摸浏览模式是否开启。 +判断触摸浏览模式是否开启, 使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Vision -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<boolean> | 是 | 回调函数,如果触摸浏览模式已开启,则返回 true;否则返回 false。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | 是 | 回调函数,如果触摸浏览模式已开启,则返回 true;否则返回 false。 | -- **示例:** +**示例:** - ```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)) - }) +```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)) +}); ``` ## accessibility.sendEvent sendEvent(event: EventInfo): Promise<void> -发送无障碍事件。 +发送无障碍事件, 使用Promise异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | 是 | 无障碍事件对象。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | 是 | 无障碍事件对象。 | -- **返回值:** +**返回值:** - | 类型 | 说明 | - | -------- | -------- | - | Promise<void> | 以 Promise 形式返回结果,如果发送无障碍事件成功,则 data 有数据返回;如果发送无障碍事件失败,则 err 有数据返回。 | +| 类型 | 说明 | +| -------- | -------- | +| Promise<void> | 无返回结果的Promise对象。 | -- **示例:** +**示例:** - ```typescript - let eventInfo : accessibility.EventInfo = { - type: 'focus', - bundleName: 'bundle', - triggerAction: 'focus' - } - accessibility.sendEvent(eventInfo) - .then((data) => { - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }).catch((error) => { - console.error('failed to sendEvent because ' + JSON.stringify(error)); - }) - ``` +```typescript +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 sendEvent(event: EventInfo, callback: AsyncCallback<void>): void -发送无障碍事件。 +发送无障碍事件, 使用callback异步回调。 **系统能力**:SystemCapability.BarrierFree.Accessibility.Core -- **参数:** +**参数:** - | 参数名 | 参数类型 | 必填 | 说明 | - | -------- | -------- | -------- | -------- | - | event | [EventInfo](#eventinfo) | 是 | 辅助事件对象。 | - | callback | AsyncCallback<void> | 是 | 回调函数,如果发送无障碍事件成功,则 AsyncCallback 中 data 有数据返回;如果发送无障碍事件失败,则 AsyncCallback 中 err 有数据返回。 | +| 参数名 | 参数类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| event | [EventInfo](#eventinfo) | 是 | 辅助事件对象。 | +| callback | AsyncCallback<void> | 是 | 回调函数,如果发送无障碍事件失败,则 AsyncCallback中err有数据返回。 | -- **示例:** +**示例:** - ```typescript - let eventInfo : accessibility.EventInfo = { - type: 'focus', - bundleName: 'bundle', - triggerAction: 'focus' - } - accessibility.sendEvent(eventInfo,(err, data) => { - if (err) { - console.error('failed to sendEvent because ' + JSON.stringify(err)); - return; - } - console.info('success data:sendEvent : ' + JSON.stringify(data)) - }) +```typescript +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'); +}); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md index cbe6af5410c204f20bcfbe623b95bf7d71be0117..a11141d837c647265bb39b925f4d3a54d5cf6d28 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-appAccount.md +++ b/zh-cn/application-dev/reference/apis/js-apis-appAccount.md @@ -40,7 +40,7 @@ createAppAccountManager(): AppAccountManager createAccount(name: string, callback: AsyncCallback<void>): void; -将此应用的帐号名添加到帐号管理服务中,使用callback回调异步返回结果。 +将此应用的帐号名添加到帐号管理服务中。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -49,7 +49,16 @@ createAccount(name: string, callback: AsyncCallback<void>): void; | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | -------------------- | | name | string | 是 | 要添加的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 将此应用的帐号名添加到帐号管理服务回调。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当此应用的帐号名添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or options. | + | 12300008 | the account indicated by name already exist. | + | 12300011 | the account number has reached the upper limit. | **示例:** @@ -66,9 +75,9 @@ createAccount(name: string, callback: AsyncCallback<void>): void; ### createAccount9+ -createAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void +createAccount(name: string, options: CreateAccountOptions, callback: AsyncCallback<void>): void -将此应用程序的帐号名和额外信息(能转换string类型的其它信息,如token)添加到帐号管理服务中,使用callback回调异步返回结果。 +将此应用程序的帐号名和额外信息(能转换string类型的其它信息,如token)添加到帐号管理服务中。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -77,15 +86,29 @@ createAccount(name: string, extraInfo: string, callback: AsyncCallback<void&g | 参数名 | 类型 | 必填 | 说明 | | --------- | ------------------------- | ---- | ---------------------------------------- | | name | string | 是 | 要添加的应用帐号名称。 | -| extraInfo | string | 是 | 要添加的应用帐号的额外信息(能转换string类型的其它信息,如token等),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | -| callback | AsyncCallback<void> | 是 | 将此应用程序的帐号名和额外信息添加到帐号管理服务中回调。 | +| options | [CreateAccountOptions](#createaccountoptions9) | 是 | 要添加的应用帐号的选项,选项中不能包含应用帐号的敏感信息(如应用帐号密码)。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当此应用程序的帐号名和额外信息添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or options. | + | 12300008 | the account indicated by name already exist. | + | 12300011 | the account number has reached the upper limit. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.createAccount("LiSi", "token101", (err) => { + var option : CreateAccountOptions = { + customData: { + "age":10 + } + } + appAccountManager.createAccount("LiSi", option, (err) => { console.log("createAccount err: " + JSON.stringify(err)); }); } catch (err) { @@ -97,7 +120,7 @@ createAccount(name: string, extraInfo: string, callback: AsyncCallback<void&g createAccount(name: string, extraInfo?: string): Promise<void> -将此应用的帐号名或额外信息(能转换成string类型的其它信息)添加到帐号管理服务中,使用Promise方式异步返回结果。 +将此应用的帐号名或额外信息(能转换成string类型的其它信息)添加到帐号管理服务中。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -106,20 +129,34 @@ createAccount(name: string, extraInfo?: string): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------------------------------------- | | name | string | 是 | 要添加的应用帐号名称。 | -| extraInfo | string | 否 | 要添加的应用帐号的额外信息(能转换成string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | +| options | [CreateAccountOptions](#createaccountoptions9) | 否 | 要添加的应用帐号的选项,选项中不能包含应用帐号的敏感信息(如应用帐号密码),不填写不附带选项信息。 | **返回值:** | 类型 | 说明 | | ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or options. | + | 12300008 | the account indicated by name already exist. | + | 12300011 | the account number has reached the upper limit. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.createAccount("LiSi", "token101").then(()=> { + var option : CreateAccountOptions = { + customData: { + "age":10 + } + } + appAccountManager.createAccount("LiSi", option).then(()=> { console.log('createAccount Success'); }).catch((err) => { console.log("createAccount err: " + JSON.stringify(err)); @@ -129,98 +166,6 @@ createAccount(name: string, extraInfo?: string): Promise<void> } ``` -### addAccount(deprecated) - -addAccount(name: string, callback: AsyncCallback<void>): void - -将此应用的帐号名添加到帐号管理服务中,使用callback回调异步返回结果。 - -> **说明:** -> 从API version 9开始废弃, 建议使用[createAccount](#createaccount9)替代 -> -> 从 API version 7开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | -------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 将此应用的帐号名添加到帐号管理服务回调。 | - -**示例:** - - ```js - const 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 - -将此应用程序的帐号名和额外信息(能转换string类型的其它信息,如token)添加到帐号管理服务中,使用callback回调异步返回结果。 - -> **说明:** > 从API version 9开始废弃, 建议使用[createAccount](#createaccount9-1)替代 -> 从 API version 7开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | ---------------------------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| extraInfo | string | 是 | 要添加的应用帐号的额外信息(能转换string类型的其它信息,如token等),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | -| callback | AsyncCallback<void> | 是 | 将此应用程序的帐号名和额外信息添加到帐号管理服务中回调。 | - -**示例:** - - ```js - const 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> - -将此应用的帐号名或额外信息(能转换成string类型的其它信息)添加到帐号管理服务中,使用Promise方式异步返回结果。 - -> **说明:** > 从API version 9开始废弃, 建议使用[createAccount](#createaccount9-2)替代 -> 从 API version 7开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | ---------------------------------------- | -| name | string | 是 | 要添加的应用帐号名称。 | -| extraInfo | string | 否 | 要添加的应用帐号的额外信息(能转换成string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | - -**示例:** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccount("LiSi", "token101").then(()=> { - console.log('addAccount Success'); - }).catch((err) => { - console.log("addAccount err: " + JSON.stringify(err)); - }); - ``` - ### createAccountImplicitly9+ createAccountImplicitly(owner: string, callback: AuthCallback): void @@ -236,6 +181,15 @@ createAccountImplicitly(owner: string, callback: AuthCallback): void | owner | string | 是 | 要添加的应用帐号所有者包名。 | | callback | [AuthCallback](#authcallback9) | 是 | 认证回调,用于返回鉴权结果。 | +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or options. | + | 12300011 | the account number has reached the upper limit. | + | 12300008 | the account authenticator service does not exist. | + **示例:** ```js @@ -280,6 +234,15 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, | options | [CreateAccountImplicitlyOptions](#createaccountimplicitlyoptions9) | 是 | 隐式创建账号的选项。 | | callback | [AuthCallback](#authcallback9) | 是 | 认证回调,用于返回鉴权结果。 | +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or options. | + | 12300011 | the account number has reached the upper limit. | + | 12300008 | the account authenticator service does not exist. | + **示例:** ```js @@ -310,56 +273,11 @@ createAccountImplicitly(owner: string, options: CreateAccountImplicitlyOptions, ``` -### addAccountImplicitly(deprecated) - -addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void - -根据指定的帐号所有者、鉴权类型和可选项隐式地添加应用帐号,并使用callback回调异步返回结果。 - -> **说明:** 从API version 9开始废弃, 建议使用[createAccountImplicitly](#createaccountimplicitly9)替代。 -> -> 从 API version 8开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ---- | ----------------------- | -| owner | string | 是 | 要添加的应用帐号所有者包名。 | -| authType | string | 是 | 要添加的应用帐号鉴权类型。鉴权类型为自定义。 | -| options | {[key: string]: any} | 是 | 鉴权所需要的可选项。可选项可根据自己需要设置。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回鉴权结果。 | - -**示例:** - - ```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)); - }); - } - - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); - ``` - ### removeAccount9+ removeAccount(name: string, callback: AsyncCallback<void>): void -从帐号管理服务中移除应用帐号,使用callback回调异步返回结果。 +从帐号管理服务中移除应用帐号。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -368,7 +286,15 @@ removeAccount(name: string, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------------- | ---- | ---------------- | | name | string | 是 | 要删除的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 帐号管理服务中移除应用帐号的回调。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当帐号管理服务中移除应用帐号成功时,err为undefined,否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name. | + | 12300003 | the account indicated by name dose not exist. | **示例:** @@ -388,7 +314,7 @@ removeAccount(name: string, callback: AsyncCallback<void>): void deleteAccount(name: string): Promise<void> -从帐号管理服务中移除应用帐号,使用Promise方式异步返回结果。 +从帐号管理服务中移除应用帐号。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -402,7 +328,15 @@ deleteAccount(name: string): Promise<void> | 类型 | 说明 | | :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name. | + | 12300003 | the account indicated by name dose not exist. | **示例:** @@ -420,69 +354,6 @@ deleteAccount(name: string): Promise<void> ``` -### deleteAccount(deprecated) - -deleteAccount(name: string, callback: AsyncCallback<void>): void - -从帐号管理服务中删除应用帐号,使用callback回调异步返回结果。 - -> **说明:** 从API version 9开始废弃, 建议使用[removeAccount](#removeaccount9)替代。 -> -> 从 API version 7开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ---------------- | -| name | string | 是 | 要删除的应用帐号名称。 | -| callback | AsyncCallback<void> | 是 | 帐号管理服务中删除应用帐号回调。 | - -**示例:** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccount("ZhaoLiu", (err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); - }); - ``` - -### deleteAccount(deprecated) - -deleteAccount(name: string): Promise<void> - -从帐号管理服务中删除应用帐号,使用Promise方式异步返回结果。 - -> **说明:** 从API version 9开始废弃, 建议使用[removeAccount](#removeaccount9)替代。 -> -> 从 API version 7开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | ----------- | -| name | string | 是 | 要删除的应用帐号名称。 | - -**返回值:** - -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | - -**示例:** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteAccount("ZhaoLiu").then(() => { - console.log('deleteAccount Success'); - }).catch((err) => { - console.log("deleteAccount err: " + JSON.stringify(err)); - }); - ``` - ### setAppAccess9+ setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback: AsyncCallback<void>): void @@ -500,6 +371,15 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback: | isAccessible | boolean | 是 | 访问控制,允许访问或禁止访问。 | | callback | AsyncCallback<void> | 是 | 访问权限设置的回调。 | +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or bundlename. | + | 12300003 | the account indicated by localId dose not exist. | + | 12400001 | the application indicated by bundlename does not exist. | + **示例:** ```js @@ -518,7 +398,7 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean, callback: setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise<void> -设置指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,由isAccessible指明是允许访问还是禁止访问,使用Promise方式异步返回结果。 +设置指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,由isAccessible指明是允许访问还是禁止访问。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -534,7 +414,16 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise&l | 类型 | 说明 | | :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or bundlename. | + | 12300003 | the account indicated by localId dose not exist. | + | 12400001 | the application indicated by bundlename does not exist. | **示例:** @@ -551,15 +440,11 @@ setAppAccess(name: string, bundleName: string, isAccessible: boolean): Promise&l } ``` -### disableAppAccess(deprecated) - -disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void +### checkAppAccess9+ -禁止指定第三方应用帐号名称对指定的第三方应用进行访问,使用callback回调异步返回结果。 +checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<boolean>): void -> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9)替代。 -> -> 从 API version 7开始支持。 +查看指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,callback回调异步返回结果。 **系统能力:** SystemCapability.Account.AppAccount @@ -567,170 +452,62 @@ disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<vo | 参数名 | 类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | 是 | 要禁用访问的第三方应用帐号名称。 | +| name | string | 是 | 应用帐号名称。 | | bundleName | string | 是 | 第三方应用的包名。 | -| callback | AsyncCallback<void> | 是 | 禁止指定第三方应用帐号名称对指定包名称的第三方应用进行访问的回调。 | +| callback | AsyncCallback<void> | 是 | 查看访问权限的回调。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or bundlename. | + | 12300003 | the account indicated by localId dose not exist. | + | 12400001 | the application indicated by bundlename does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("disableAppAccess err: " + JSON.stringify(err)); - }); - ``` + try { + appAccountManager.checkAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { + console.log("checkAppAccess: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("checkAppAccess: " + JSON.stringify(err)); + } -### disableAppAccess(deprecated) + ``` -disableAppAccess(name: string, bundleName: string): Promise<void> +### checkAppAccess9+ -禁止指定第三方应用帐号名称对指定包名称的第三方应用进行访问,使用Promise方式异步返回结果。 +checkAppAccess(name: string, bundleName: string): Promise<void> -> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9-1)替代。 -> -> 从 API version 7开始支持。 +查看指定第三方应用帐号名称对指定包名称的第三方应用的访问权限。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | ---------------- | -| name | string | 是 | 要禁用访问的第三方应用帐号名称。 | -| bundleName | string | 是 | 第三方应用的包名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号名称。 | +| bundleName | string | 是 | 第三方应用的包名。 | **返回值:** | 类型 | 说明 | | :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | -**示例:** +**错误码:** - ```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)); - }); - ``` - -### enableAppAccess(deprecated) - -enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void - -允许指定第三方应用帐号名称对指定包名称的第三方应用进行访问,使用callback回调异步返回结果。 - -> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9)替代。 -> -> 从 API version 7开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | 是 | 应用帐号名称。 | -| bundleName | string | 是 | 第三方应用的包名。 | -| callback | AsyncCallback<void> | 是 | 允许指定第三方应用帐号名称对指定包名称的第三方应用进行访问的回调。 | - -**示例:** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("enableAppAccess: " + JSON.stringify(err)); - }); - ``` - -### enableAppAccess(deprecated) - -enableAppAccess(name: string, bundleName: string): Promise<void> - -允许指定第三方应用帐号的名称对指定包名称的第三方应用进行访问,使用Promise方式异步返回结果。 - -> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9-1)替代。 -> -> 从 API version 7开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| bundleName | string | 是 | 第三方应用的包名。 | - -**返回值:** - -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | - -**示例:** - - ```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)); - }); - ``` - -### checkAppAccess9+ - -checkAppAccess(name: string, bundleName: string, callback: AsyncCallback<boolean>): void - -查看指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,callback回调异步返回结果。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | --------------------------------- | -| name | string | 是 | 应用帐号名称。 | -| bundleName | string | 是 | 第三方应用的包名。 | -| callback | AsyncCallback<void> | 是 | 查看访问权限的回调。 | - -**示例:** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.checkAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { - console.log("checkAppAccess: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("checkAppAccess: " + JSON.stringify(err)); - } - - ``` - -### checkAppAccess9+ - -checkAppAccess(name: string, bundleName: string): Promise<void> - -查看指定第三方应用帐号名称对指定包名称的第三方应用的访问权限,使用Promise方式异步返回结果。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| bundleName | string | 是 | 第三方应用的包名。 | - -**返回值:** - -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or bundlename. | + | 12300003 | the account indicated by localId dose not exist. | + | 12400001 | the application indicated by bundlename does not exist. | **示例:** @@ -752,7 +529,7 @@ checkAppAccess(name: string, bundleName: string): Promise<void> checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void -检查指定应用帐号是否允许应用数据同步,使用callback回调异步返回结果。 +检查指定应用帐号是否允许应用数据同步。使用callback异步回调。 **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC @@ -763,7 +540,15 @@ checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------- | ---- | --------------------- | | name | string | 是 | 应用帐号名称。 | -| callback | AsyncCallback<boolean> | 是 | 检查指定应用帐号是否允许应用数据同步回调。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。返回true表示指定应用帐号允许应用数据同步;返回false表示指定应用帐号不允许应用数据同步。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name. | + | 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -784,7 +569,7 @@ checkDataSyncEnabled(name: string, callback: AsyncCallback<boolean>): void checkDataSyncEnabled(name: string): Promise<boolean> -检查指定应用帐号是否允许应用数据同步,使用Promise方式异步返回结果。 +检查指定应用帐号是否允许应用数据同步。使用Promise异步回调。 **需要权限:** ohos.permission.DISTRIBUTED_DATASYNC @@ -800,7 +585,15 @@ checkDataSyncEnabled(name: string): Promise<boolean> | 类型 | 说明 | | :--------------------- | :-------------------- | -| Promise<boolean> | Promise实例,用于获取异步返回结果。 | +| Promise<boolean> | Promise对象。返回true表示允许应用数据同步;返回false表示不允许应用数据同步。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name. | + | 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -818,79 +611,11 @@ checkDataSyncEnabled(name: string): Promise<boolean> ``` -### checkAppAccountSyncEnable(deprecated) - -checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void - -检查指定应用帐号是否允许应用数据同步,使用callback回调异步返回结果。 - -> **说明:** 从API version 9开始废弃。建议使用[checkDataSyncEnabled](#checkdatasyncenabled9)替代。 -> -> 从 API version 7开始支持。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------- | ---- | --------------------- | -| name | string | 是 | 应用帐号名称。 | -| callback | AsyncCallback<boolean> | 是 | 检查指定应用帐号是否允许应用数据同步回调。 | - -**示例:** - - ```js - const 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> - -检查指定应用帐号是否允许应用数据同步,使用Promise方式异步返回结果。 - -> **说明:** 从API version 9开始废弃。建议使用[checkDataSyncEnabled](#checkdatasyncenabled9-1)替代。 -> -> 从 API version 7开始支持。 - -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | ------- | -| name | string | 是 | 应用帐号名称。 | - -**返回值:** - -| 类型 | 说明 | -| :--------------------- | :-------------------- | -| Promise<boolean> | Promise实例,用于获取异步返回结果。 | - -**示例:** - - ```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)); - }); - ``` - ### setCredential9+ setCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void -设置此应用程序帐号的凭据,使用callback回调异步返回结果。 +设置此应用程序帐号的凭据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount @@ -901,7 +626,15 @@ setCredential(name: string, credentialType: string, credential: string,callback: | name | string | 是 | 应用程序帐号名称。 | | credentialType | string | 是 | 要设置的凭据类型。 | | credential | string | 是 | 要设置的凭据。 | -| callback | AsyncCallback<void> | 是 | 设置此应用帐号的凭据回调。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置此应用程序帐号的凭据成功时,err为undefined,否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or credentialType. | + | 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -920,7 +653,7 @@ setCredential(name: string, credentialType: string, credential: string,callback: setCredential(name: string, credentialType: string, credential: string): Promise<void> -设置此应用程序帐号的凭据,使用Promise方式异步返回结果。 +设置此应用程序帐号的凭据。使用Promise异步回调。 > **说明:** 从API version 9开始废弃。 > @@ -940,7 +673,15 @@ setCredential(name: string, credentialType: string, credential: string): Promise | 类型 | 说明 | | :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or credentialType. | + | 12300003 | the account indicated by localId dose not exist. | **示例:** @@ -957,2908 +698,3708 @@ setCredential(name: string, credentialType: string, credential: string): Promise } ``` + +### setDataSyncEnabled9+ -### setAccountCredential(deprecated) - -setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void +setDataSyncEnabled(name: string, isEnable: boolean, callback: AsyncCallback<void>): void -设置此应用程序帐号的凭据,使用callback回调异步返回结果。 +设置指定的应用程序帐号是否允许应用程序数据同步。使用callback异步回调。 -> **说明:** 从API version 9开始废弃,建议使用[setCredential](#setcredential9)替代。 -> -> 从 API version 7开始支持。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------------------------- | ---- | ------------- | -| name | string | 是 | 应用程序帐号名称。 | -| credentialType | string | 是 | 要设置的凭据类型。 | -| credential | string | 是 | 要设置的凭据。 | -| callback | AsyncCallback<void> | 是 | 设置此应用帐号的凭据回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | 是 | 应用帐号名称。 | +| isEnable | boolean | 是 | 是否允许应用数据同步。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当指定的应用帐号是否允许应用程序数据设置成功时,err为undefined,否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name. | + | 12300003 | the account indicated by name dose not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { - console.log("setAccountCredential err: " + JSON.stringify(err)); - }); + try { + appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + } ``` -### setAccountCredential(deprecated) +### setDataSyncEnabled9+ -setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> +setDataSyncEnabled(name: string, isEnable: boolean): Promise<void> -设置此应用程序帐号的凭据,使用Promise方式异步返回结果。 +设置指定的应用程序帐号是否允许应用程序数据同步。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃,建议使用[setCredential](#setcredential9-1)替代。 -> -> 从 API version 7开始支持。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------ | ---- | ---------- | -| name | string | 是 | 应用帐号的名称。 | -| credentialType | string | 是 | 要设置的凭据的类型。 | -| credential | string | 是 | 要设置的凭据。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------- | ---- | ----------- | +| name | string | 是 | 应用帐号名称。 | +| isEnable | boolean | 是 | 是否允许应用数据同步。 | **返回值:** | 类型 | 说明 | | :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name. | + | 12300003 | the account indicated by name dose not exist. | **示例:** ```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)); - }); + 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)); + } ``` -### setAccountExtraInfo(deprecated) +### setCustomData9+ -setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void - -设置此应用程序帐号的额外信息,使用callback回调异步返回结果。 - -> **说明:** 从API version 9开始废弃。 -> -> 从 API version 7开始支持。 +setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void +设置与此应用程序帐号关联的数据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------------------------- | ---- | --------------- | -| name | string | 是 | 应用帐号名称。 | -| extraInfo | string | 是 | 要设置的额外信息。 | -| callback | AsyncCallback<void> | 是 | 设置此应用帐号的额外信息回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | +| value | string | 是 | 要设置的数据的值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置与此应用帐号关联的数据成功时,err为undefined,否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, key or value. | + | 12300003 | the account indicated by name dose not exist. | + | 12400008 | the number of customized data has reached the upper limit. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); - }); + try { + appAccountManager.setCustomData("ZhangSan", "k001", "v001", (err) => { + console.log("setCustomData err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setCustomData err: " + JSON.stringify(err)); + } ``` -### setAccountExtraInfo(deprecated) - -setAccountExtraInfo(name: string, extraInfo: string): Promise<void> - -设置此应用程序帐号的额外信息,使用Promise方式异步返回结果。 +### setCustomData9+ -> **说明:** 从API version 9开始废弃。 -> -> 从 API version 7开始支持。 +setAssociatedData(name: string, key: string, value: string): Promise<void> +设置与此应用程序帐号关联的数据。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| extraInfo | string | 是 | 要设置的额外信息。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | +| value | string | 是 | 要设置的数据的值。 | **返回值:** | 类型 | 说明 | | :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, key or value. | + | 12300003 | the account indicated by name dose not exist. | + | 12400008 | the number of customized data has reached the upper limit. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { - console.log('setAccountExtraInfo Success'); - }).catch((err) => { - console.log("setAccountExtraInfo err: " + JSON.stringify(err)); - }); + try { + appAccountManager.setCustomData("ZhangSan", "k001", "v001").then(() => { + console.log('setCustomData Success'); + }).catch((err) => { + console.log("setCustomData err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("setCustomData err: " + JSON.stringify(err)); + } ``` - -### setDataSyncEnabled9+ -setDataSyncEnabled(name: string, isEnable: boolean, callback: AsyncCallback<void>): void +### getAllAccounts9+ -设置指定的应用程序帐号是否允许应用程序数据同步,使用callback回调异步返回结果。 +getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +获取全部应用已授权帐号信息。 + +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | -| callback | AsyncCallback<void> | 是 | 设置指定的应用帐号是否允许应用程序数据同步的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setDataSyncEnabled("ZhangSan", true, (err) => { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + appAccountManager.getAllAccounts((err, data)=>{ + console.debug("getAllAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccounts data:" + JSON.stringify(data)); }); } catch (err) { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.debug("getAllAccounts err:" + JSON.stringify(err)); } ``` -### setDataSyncEnabled9+ +### getAllAccounts9+ -setDataSyncEnabled(name: string, isEnable: boolean): Promise<void> +getAllAccounts(): Promise<Array<AppAccountInfo>> -设置指定的应用程序帐号是否允许应用程序数据同步,使用Promise方式异步返回结果。 +获取全部应用已授权帐号信息。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 **系统能力:** SystemCapability.Account.AppAccount -**参数:** +**返回值:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------- | ---- | ----------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回全部应用已授权帐号信息对象。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager .setDataSyncEnabled("ZhangSan", true).then(() => { - console.log('setDataSyncEnabled Success'); + appAccountManager.getAllAccounts().then((data) => { + console.log('getAllAccounts: ' + data); }).catch((err) => { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.log("getAllAccounts err: " + JSON.stringify(err)); }); } catch (err) { - console.log("setDataSyncEnabled err: " + JSON.stringify(err)); + console.log("getAllAccounts err: " + JSON.stringify(err)); } ``` -### setAppAccountSyncEnable(deprecated) - -setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void +### getAccountsByOwner9+ -设置指定的应用程序帐号是否允许应用程序数据同步,使用callback回调异步返回结果。 +getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void -> **说明:** 从API version 9开始废弃, 建议使用[setDataSyncEnabled](#setdatasyncenabled9)替代。 -> -> 从 API version 7开始支持。 +获取指定应用全部帐号信息。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | -| callback | AsyncCallback<void> | 是 | 设置指定的应用帐号是否允许应用程序数据同步的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | --------- | +| owner | string | 是 | 应用包名称。 | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid owner. | + | 12300003 | the account indicated by owner dose not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + const selfBundle = "com.example.actsgetallaaccounts"; + try { + appAccountManager.getAccountsByOwner(selfBundle, (err, data)=>{ + console.debug("getAccountsByOwner err:" + JSON.stringify(err)); + console.debug("getAccountsByOwner data:" + JSON.stringify(data)); + }); + } catch (err) { + console.debug("getAccountsByOwner err:" + JSON.stringify(err)); + } ``` -### setAppAccountSyncEnable(deprecated) - -setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> +### getAccountsByOwner9+ -设置指定的应用程序帐号是否允许应用程序数据同步,使用Promise方式异步返回结果。 +getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> -> **说明:** 从API version 9开始废弃, 建议使用[setDataSyncEnabled](#setdatasyncenabled9-1)替代。 -> -> 从 API version 7开始支持。 +获取指定应用全部帐号信息。 -**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------- | ---- | ----------- | -| name | string | 是 | 应用帐号名称。 | -| isEnable | boolean | 是 | 是否允许应用数据同步。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ------ | +| owner | string | 是 | 应用包名称。 | **返回值:** -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回指定应用全部帐号信息对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid owner. | + | 12300003 | the account indicated by owner dose not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { - console.log('setAppAccountSyncEnable Success'); - }).catch((err) => { - console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); - }); + const selfBundle = "com.example.actsgetallaaccounts"; + try { + appAccountManager.getAccountsByOwner(selfBundle).then((data) => { + console.log('getAccountsByOwner: ' + data); + }).catch((err) => { + console.log("getAccountsByOwner err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAccountsByOwner err: " + JSON.stringify(err)); + } ``` -### setCustomData9+ +### getCredential9+ -setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void +getCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void -设置与此应用程序帐号关联的数据,使用callback回调异步返回结果。 +获取此应用帐号的凭据(如数字密码、人脸和PIN码等)。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | -| callback | AsyncCallback<void> | 是 | 设置与此应用帐号关联的数据的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | 是 | 应用帐号名称。 | +| credentialType | string | 是 | 获取此应用帐号的凭据的类型。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取此应用帐号的凭据成功时,err为undefined,data返回此应用帐号的凭据对象;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or credentialType. | + | 12300003 | the account indicated by name dose not exist. | + | 12300019 | credential does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setCustomData("ZhangSan", "k001", "v001", (err) => { - console.log("setCustomData err: " + JSON.stringify(err)); - }); + appAccountManager.getCredential("ZhangSan", "credentialType001", (err, result) => { + console.log("getCredential err: " + JSON.stringify(err)); + console.log('getCredential result: ' + result); + }); } catch (err) { - console.log("setCustomData err: " + JSON.stringify(err)); + console.log("getCredential err: " + JSON.stringify(err)); } ``` -### setCustomData9+ +### getCredential9+ -setAssociatedData(name: string, key: string, value: string): Promise<void> +getCredential(name: string, credentialType: string): Promise<string> -设置与此应用程序帐号关联的数据,使用Promise方式异步返回结果。 +获取此应用程序帐号的凭据。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------ | ---- | ---------- | +| name | string | 是 | 应用帐号名称。 | +| credentialType | string | 是 | 要获取的凭据的类型。 | **返回值:** -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :-------------------- | :-------------------- | +| Promise<string> | Promise对象。返回此应用程序帐号的凭据对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or credentialType. | + | 12300003 | the account indicated by name dose not exist. | + | 12300019 | credential does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.setCustomData("ZhangSan", "k001", "v001").then(() => { - console.log('setCustomData Success'); + appAccountManager.getCredential("ZhangSan", "credentialType001").then((data) => { + console.log('getCredential, result: ' + data); }).catch((err) => { - console.log("setCustomData err: " + JSON.stringify(err)); + console.log("getCredential err: " + JSON.stringify(err)); }); } catch (err) { - console.log("setCustomData err: " + JSON.stringify(err)); + console.log("getCredential err: " + JSON.stringify(err)); } ``` -### setAssociatedData(deprecated) - -setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void - -设置与此应用程序帐号关联的数据,使用callback回调异步返回结果。 +### getCustomData9+ -> **说明:** 从API version 9开始废弃, 建议使用[setCustomData](#setcustomdata9)替代。 -> -> 从 API version 7开始支持。 +getCustomData(name: string, key: string, callback: AsyncCallback<string>): void +获取与此应用程序帐号关联的数据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | -| callback | AsyncCallback<void> | 是 | 设置与此应用帐号关联的数据的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ----------------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要获取的数据的键。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取与此应用程序帐号关联的数据成功时,err为undefined,data返回与此应用程序帐号关联的数据对象;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or key. | + | 12300003 | the account indicated by name dose not exist. | + | 12400009 | the customData does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { - console.log("setAssociatedData err: " + JSON.stringify(err)); - }); + try { + appAccountManager.getCustomData("ZhangSan", "k001", (err, result) => { + console.log("getCustomData err: " + JSON.stringify(err)); + console.log('getCustomData result: ' + result); + }); + } catch (err) { + console.log("getCustomData err: " + JSON.stringify(err)); + } ``` -### setAssociatedData(deprecated) - -setAssociatedData(name: string, key: string, value: string): Promise<void> - -设置与此应用程序帐号关联的数据,使用Promise方式异步返回结果。 +### getCustomData9+ -> **说明:** 从API version 9开始废弃, 建议使用[setCustomData](#setcustomdata9-1)替代。 -> -> 从 API version 7开始支持。 +getCustomData(name: string, key: string): Promise<string> +获取与此应用程序帐号关联的数据。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | -| value | string | 是 | 要设置的数据的值。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要获取的数据的键。 | **返回值:** -| 类型 | 说明 | -| :------------------ | :-------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | - -**示例:** - - ```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)); - }); - ``` - -### getAllAccounts9+ - -getAllAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void - -获取全部应用已授权帐号信息。 - -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 - -**系统能力:** SystemCapability.Account.AppAccount +| 类型 | 说明 | +| :-------------------- | :-------------------- | +| Promise<string> | Promise对象。返回与此应用程序帐号关联的数据对象。 | -**参数:** +**错误码:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or key. | + | 12300003 | the account indicated by name dose not exist. | + | 12400009 | the customData does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAllAccounts((err, data)=>{ - console.debug("getAllAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccounts data:" + JSON.stringify(data)); + appAccountManager.getCustomData("ZhangSan", "k001").then((data) => { + console.log('getCustomData: ' + data); + }).catch((err) => { + console.log("getCustomData err: " + JSON.stringify(err)); }); } catch (err) { - console.debug("getAllAccounts err:" + JSON.stringify(err)); + console.log("getCustomData err: " + JSON.stringify(err)); } ``` -### getAllAccounts9+ - -getAllAccounts(): Promise<Array<AppAccountInfo>> +### getCustomDataSync9+ -获取全部应用已授权帐号信息。 +getCustomDataSync(name: string, key: string): string; -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +获取与此应用程序帐号关联的数据,使用同步方式返回结果。 **系统能力:** SystemCapability.Account.AppAccount +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要获取的数据的键。 | + **返回值:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :-------------------- | :-------------------- | +| string | 目标关联数据的取值。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or key. | + | 12300003 | the account indicated by name dose not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAllAccounts().then((data) => { - console.log('getAllAccounts: ' + data); - }).catch((err) => { - console.log("getAllAccounts err: " + JSON.stringify(err)); - }); + var backData = appAccountManager.getCustomDataSync("ZhangSan", "k001"); + console.info("getCustomDataSync backData:" + JSON.stringify(backData)); } catch (err) { - console.log("getAllAccounts err: " + JSON.stringify(err)); + console.error(`getCustomDataSync err, code is ${e.code}, message is ${e.message}`); } ``` -### getAllAccessibleAccounts(deprecated) - -getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void - -获取全部应用已授权帐号信息。 +### on('accountChange')9+ -> **说明:** 从API version 9开始废弃, 建议使用[getAllAccounts](#getallaccounts9)替代。 -> -> 从 API version 7开始支持。 +on(type: 'accountChange', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +订阅指定帐号所有者的帐户变更事件。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------- | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'accountChange' | 是 | 事件回调类型,支持的事件为'accountChange',当帐号所有者更新帐号时,触发该事件。 | +| owners | Array<string> | 是 | 指示帐号的所有者。 | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数。返回指定帐号所有者更新的帐号信息对象数组。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid type or owners. | + | 12300003 | the account indicated by owners dose not exist. | + | 12300005 | the listener has been registered. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllAccessibleAccounts((err, data)=>{ - console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); - console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); - }); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + } + try{ + appAccountManager.on('accountChange', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } ``` -### getAllAccessibleAccounts(deprecated) +### off('accountChange')9+ -getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> +off(type: 'accountChange', callback?: Callback>): void -获取全部应用已授权帐号信息。 +取消订阅帐号事件。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[getAllAccounts](#getallaccounts9-1)替代。 -> -> 从 API version 7开始支持。 +**系统能力:** SystemCapability.Account.AppAccount -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +**参数:** -**系统能力:** SystemCapability.Account.AppAccount +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'accountChange' | 是 | 事件回调类型,支持的事件为'accountChange',当帐号所有者更新帐号时,触发该事件。 | +| callback | Callback> | 否 | 回调函数,返回指定帐号所有者更新的帐号信息数组。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise实例,用于获取异步返回结果。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid type. | + | 12300005 | the listener has been registered. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllAccessibleAccounts().then((data) => { - console.log('getAllAccessibleAccounts: ' + data); - }).catch((err) => { - console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); - }); + function changeOnCallback(data){ + console.debug("receive change data:" + JSON.stringify(data)); + appAccountManager.off('accountChange', function(){ + console.debug("off finish"); + }) + } + try{ + appAccountManager.on('accountChange', ["com.example.actsaccounttest"], changeOnCallback); + } + catch(err){ + console.error("on accountOnOffDemo err:" + JSON.stringify(err)); + } ``` -### getAccountsByOwner9+ - -getAccountsByOwner(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void +### auth9+ -获取指定应用全部帐号信息。 +auth(name: string, owner: string, authType: string, callback: AuthCallback): void -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +对应用帐户进行鉴权以获取Auth令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------- | -| owner | string | 是 | 应用包名称。 | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | --------------- | +| name | string | 是 | 要鉴权的应用帐号名称。 | +| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调函数。返回鉴权结果对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner, authType or options. | + | 12300003 | the account indicated by owner dose not exist. | + | 12300016 | authentication timeout. | + | 12300017 | authentication service is busy. | + | 12300018 | authentication service is locked. | + | 12400001 | the application indicated by name does not exist. | **示例:** ```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)); + }); + } + const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; try { - appAccountManager.getAccountsByOwner(selfBundle, (err, data)=>{ - console.debug("getAccountsByOwner err:" + JSON.stringify(err)); - console.debug("getAccountsByOwner data:" + JSON.stringify(data)); + appAccountManager.auth("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback }); } catch (err) { - console.debug("getAccountsByOwner err:" + JSON.stringify(err)); + console.log("auth err: " + JSON.stringify(err)); } ``` -### getAccountsByOwner9+ - -getAccountsByOwner(owner: string): Promise<Array<AppAccountInfo>> +### auth9+ -获取指定应用全部帐号信息。 +auth(name: string, owner: string, authType: string, options: {[key: string]: Object}, callback: AuthCallback): void -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +对应用帐户进行鉴权以获取OAuth令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ------ | -| owner | string | 是 | 应用包名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | --------------- | +| name | string | 是 | 要鉴权的应用帐号名称。 | +| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| options | {[key: string]: Object} | 是 | 鉴权所需的可选项。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调函数。返回鉴权结果对象。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise实例,用于获取异步返回结果。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner, authType or options. | + | 12300003 | the account indicated by owner dose not exist. | + | 12300016 | authentication timeout. | + | 12300017 | authentication service is busy. | + | 12300018 | authentication service is locked. | + | 12400001 | the application indicated by name does not exist. | **示例:** ```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)); + }); + } + const appAccountManager = account_appAccount.createAppAccountManager(); - const selfBundle = "com.example.actsgetallaaccounts"; try { - appAccountManager.getAccountsByOwner(selfBundle).then((data) => { - console.log('getAccountsByOwner: ' + data); - }).catch((err) => { - console.log("getAccountsByOwner err: " + JSON.stringify(err)); + appAccountManager.auth("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback }); } catch (err) { - console.log("getAccountsByOwner err: " + JSON.stringify(err)); + console.log("auth err: " + JSON.stringify(err)); } ``` -### getAllAccounts(deprecated) - -getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void - -获取指定应用全部帐号信息。 +### getAuthToken9+ -> **说明:** 从API version 9开始废弃, 建议使用[getAccountsByOwner]替代。 -> -> 从 API version 7开始支持。 +getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +获取指定应用帐号和鉴权类型的Auth令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | --------- | -| owner | string | 是 | 应用包名称。 | -| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取指定应用帐号和鉴权类型的Auth令牌成功时,err为undefined,data返回Auth令牌对象;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner or authType. | + | 12300003 | the account indicated by owner dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12400001 | the application indicated by name does not exist. | **示例:** ```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)); - }); + try { + appAccountManager.getAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { + console.log('getAuthToken err: ' + JSON.stringify(err)); + console.log('getAuthToken token: ' + data); + }); + } catch (err) { + console.log('getAuthToken err: ' + JSON.stringify(err)); + } ``` -### getAllAccounts(deprecated) - -getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> - -获取指定应用全部帐号信息。 +### getAuthToken9+ -> **说明:** 从API version 9开始废弃, 建议使用[getAccountsByOwner](#getaccountsbyowner9-1)替代。 -> -> 从 API version 7开始支持。 +getAuthToken(name: string, owner: string, authType: string): Promise<string> -**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 +获取指定应用帐户和鉴权类型的Auth令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ------ | -| owner | string | 是 | 应用包名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| --------------------- | --------------------- | +| Promise<string> | Promise对象。返回指定应用帐户和鉴权类型的Auth令牌对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner or authType. | + | 12300003 | the account indicated by owner dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12400001 | the application indicated by name does not exist. | **示例:** ```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)); - }); + try { + appAccountManager.getAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { + console.log('getAuthToken token: ' + data); + }).catch((err) => { + console.log("getAuthToken err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthToken err: " + JSON.stringify(err)); + } ``` -### getCredential9+ +### setAuthToken9+ -getCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void +setAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void -获取此应用帐号的凭据(如数字密码、人脸和PIN码等),使用callback回调异步返回结果。 +设置指定应用帐号和鉴权类型的Auth令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | --------------------------- | ---- | -------------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 获取此应用帐号的凭据的类型。 | -| callback | AsyncCallback<string> | 是 | 获取此应用帐号的凭据的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | -------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | Auth令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定应用帐号和鉴权类型的Auth令牌成功时,err为undefined;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner, authType or token. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | + | 12400007 | the number of token has reached the upper limit. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCredential("ZhangSan", "credentialType001", (err, result) => { - console.log("getCredential err: " + JSON.stringify(err)); - console.log('getCredential result: ' + result); + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + console.log('setAuthToken err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getCredential err: " + JSON.stringify(err)); + console.log('setAuthToken err: ' + JSON.stringify(err)); } ``` -### getCredential9+ +### setAuthToken9+ -getCredential(name: string, credentialType: string): Promise<string> +setAuthToken(name: string, authType: string, token: string): Promise<void> -获取此应用程序帐号的凭据,使用Promise方式异步返回结果。 +设置指定应用帐户和鉴权类型的Auth令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------ | ---- | ---------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 要获取的凭据的类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | -------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | Auth令牌。 | **返回值:** -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| Promise<string> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ------------------- | --------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner, authType or token. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | + | 12400007 | the number of token has reached the upper limit. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCredential("ZhangSan", "credentialType001").then((data) => { - console.log('getCredential, result: ' + data); + appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { + console.log('setAuthToken successfully'); }).catch((err) => { - console.log("getCredential err: " + JSON.stringify(err)); + console.log('setAuthToken err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getCredential err: " + JSON.stringify(err)); + console.log('setAuthToken err: ' + JSON.stringify(err)); } ``` -### getAccountCredential(deprecated) - -getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void +### deleteAuthToken9+ -获取此应用帐号的凭据(如数字密码、人脸和PIN码等),使用callback回调异步返回结果。 +deleteAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void -> **说明:** 从API version 9开始废弃, 建议使用[getCredential](#getcredential9)替代。 -> -> 从 API version 7开始支持。 +删除指定应用帐户和鉴权类型的Auth令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | --------------------------- | ---- | -------------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 获取此应用帐号的凭据的类型。 | -| callback | AsyncCallback<string> | 是 | 获取此应用帐号的凭据的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------ | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | 要删除的Auth令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除指定应用帐户和鉴权类型的Auth令牌成功时,err为undefined;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner, authType or token. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { - console.log("getAccountCredential err: " + JSON.stringify(err)); - console.log('getAccountCredential result: ' + result); - }); + try { + appAccountManager.deleteAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { + console.log('deleteAuthToken err: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('deleteAuthToken err: ' + JSON.stringify(err)); + } ``` -### getAccountCredential(deprecated) - -getAccountCredential(name: string, credentialType: string): Promise<string> +### deleteAuthToken9+ -获取此应用程序帐号的凭据,使用Promise方式异步返回结果。 +deleteAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> -> **说明:** 从API version 9开始废弃, 建议使用[getCredential](#getcredential9-1)替代。 -> -> 从 API version 7开始支持。 +删除指定应用帐户和鉴权类型的Auth令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------ | ---- | ---------- | -| name | string | 是 | 应用帐号名称。 | -| credentialType | string | 是 | 要获取的凭据的类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------ | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | 要删除的Auth令牌。 | **返回值:** -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| Promise<string> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ------------------- | --------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner, authType or token. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | **示例:** ```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)); - }); + try { + appAccountManager.deleteAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { + console.log('deleteAuthToken successfully'); + }).catch((err) => { + console.log("deleteAuthToken err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("deleteAuthToken err: " + JSON.stringify(err)); + } ``` -### getAccountExtraInfo(deprecated) - -getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void +### setAuthTokenVisibility9+ -获取此应用帐号的额外信息(能转换成string类型的其它信息),使用callback回调异步返回结果。 +setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void -> **说明:** 从API version 9开始废弃。 -> -> 从 API version 7开始支持。 +设置指定鉴权类型的Auth令牌对特定应用的可见性。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | --------------- | -| name | string | 是 | 应用帐号名称。 | -| callback | AsyncCallback<string> | 是 | 获取此应用帐号的额外信息回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ------------------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 被设置可见性的应用包名。 | +| isVisible | boolean | 是 | 是否可见。当设置成true可见,false不可见。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定鉴权类型的Auth令牌对特定应用的可见性成功时,err为undefined;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, authType or bundleName. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { - console.log("getAccountExtraInfo err: " + JSON.stringify(err)); - console.log('getAccountExtraInfo result: ' + result); - }); + try { + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { + console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + } ``` -### getAccountExtraInfo(deprecated) - -getAccountExtraInfo(name: string): Promise<string> +### setAuthTokenVisibility9+ -获取此应用程序帐号的额外信息,使用Promise方式异步返回结果。 +setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> -> **说明:** 从API version 9开始废弃。 -> -> 从 API version 7开始支持。 +设置指定鉴权类型的OAuth令牌对特定应用的可见性。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | ------- | -| name | string | 是 | 应用帐号名称。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------- | ---- | ------------ | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 被设置可见性的应用包名。 | +| isVisible | boolean | 是 | 是否可见。 | **返回值:** -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| Promise<string> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ------------------- | --------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, authType or bundleName. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | **示例:** ```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)); - }); + try { + appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { + console.log('setAuthTokenVisibility successfully'); + }).catch((err) => { + console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + }); + } catch (err) { + console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + } ``` -### getCustomData9+ +### checkAuthTokenVisibility9+ -getCustomData(name: string, key: string, callback: AsyncCallback<string>): void +checkAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void -获取与此应用程序帐号关联的数据,使用callback回调异步返回结果。 +检查指定鉴权类型的Auth令牌对特定应用的可见性。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | -| callback | AsyncCallback<string> | 是 | 获取与此应用帐号关联的数据的回调。 | - +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------- | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 检查可见性的应用包名。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查指定鉴权类型的Auth令牌对特定应用的可见性时,err为undefined,data为true表示可见,data为false表示不可见;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, authType or bundleName. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | + **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCustomData("ZhangSan", "k001", (err, result) => { - console.log("getCustomData err: " + JSON.stringify(err)); - console.log('getCustomData result: ' + result); + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { + console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log('checkAuthTokenVisibility isVisible: ' + data); }); } catch (err) { - console.log("getCustomData err: " + JSON.stringify(err)); + console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); } ``` -### getCustomData9+ +### checkAuthTokenVisibility9+ -getCustomData(name: string, key: string): Promise<string> +checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> -获取与此应用程序帐号关联的数据,使用Promise方式异步返回结果。 +检查指定鉴权类型的Auth令牌对特定应用的可见性。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 用于检查可见性的应用包名。 | **返回值:** -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| Promise<string> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ---------------------- | --------------------- | +| Promise<boolean> | Promise对象。返回true表示指定鉴权类型的Auth令牌对特定应用的可见,返回false表示不可见。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, authType or bundleName. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getCustomData("ZhangSan", "k001").then((data) => { - console.log('getCustomData: ' + data); + appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { + console.log('checkAuthTokenVisibility isVisible: ' + data); }).catch((err) => { - console.log("getCustomData err: " + JSON.stringify(err)); + console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); }); } catch (err) { - console.log("getCustomData err: " + JSON.stringify(err)); + console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); } ``` -### getAssociatedData(deprecated) - -getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void +### getAllAuthTokens9+ -获取与此应用程序帐号关联的数据,使用callback回调异步返回结果。 +getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void -> **说明:** 从API version 9开始废弃, 建议使用[getCustomData](#getcustomdata9)替代。 -> -> 从 API version 7开始支持。 +获取指定应用对调用方全部可见的Auth令牌。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ----------------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | -| callback | AsyncCallback<string> | 是 | 获取与此应用帐号关联的数据的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| callback | AsyncCallback<Array< [AuthTokenInfo](#authtokeninfo9)>> | 是 | 回调函数。当获取指定应用对调 +用方全部可见的Auth令牌成功时,err为undefined,data为全部可见的Auth令牌数组;否则为错误对象。 | -**示例:** +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or owner. | + | 12300003 | the account indicated by name dose not exist. | + +**示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { - console.log("getAssociatedData err: " + JSON.stringify(err)); - console.log('getAssociatedData result: ' + result); - }); + try { + appAccountManager.getAllAuthTokens("LiSi", "com.example.ohos.accountjsdemo", (err, data) => { + console.log("getAllAuthTokens err: " + JSON.stringify(err)); + console.log('getAllAuthTokens data: ' + JSON.stringify(data)); + }); + } catch (err) { + console.log("getAllAuthTokens err: " + JSON.stringify(err)); + } ``` -### getAssociatedData(deprecated) - -getAssociatedData(name: string, key: string): Promise<string> +### getAllAuthTokens9+ -获取与此应用程序帐号关联的数据,使用Promise方式异步返回结果。 +getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo>> -> **说明:** 从API version 9开始废弃, 建议使用[getCustomData](#getcustomdata9-1)替代。 -> -> 从 API version 7开始支持。 +获取指定应用帐户对调用方可见的全部Auth令牌。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | **返回值:** -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| Promise<string> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array< [AuthTokenInfo](#authtokeninfo9)>> | Promise对象。返回指定应用帐户对调用方可见的全部Auth令牌对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or owner. | + | 12300003 | the account indicated by name dose not exist. | **示例:** ```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)); - }); + try { + appAccountManager.getAllAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { + console.log('getAllAuthTokens data: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getAllAuthTokens err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAllAuthTokens err: " + JSON.stringify(err)); + } ``` -### getAssociatedDataSync9+ +### getAuthList9+ -getAssociatedDataSync(name: string, key: string): string; +getAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void -获取与此应用程序帐号关联的数据,使用同步方式返回结果。 +获取指定应用帐户和鉴权类型的Auth令牌的授权列表。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---- | ------ | ---- | --------- | -| name | string | 是 | 应用帐号名称。 | -| key | string | 是 | 要获取的数据的键。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ----------------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 应用帐号的鉴权类型的Auth令牌的授权列表。 | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当获取指定应用帐户和鉴权类型的Auth令牌的授权列表成功时,err为undefined,data为Auth令牌的授权列表;否则为错误对象。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| :-------------------- | :-------------------- | -| string | 目标关联数据的取值。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or authType. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - var backData = appAccountManager.getAssociatedDataSync("ZhangSan", "k001"); - console.info("getAssociatedDataSync backData:" + JSON.stringify(backData)); + appAccountManager.getAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { + console.log('getAuthList err: ' + JSON.stringify(err)); + console.log('getAuthList data: ' + JSON.stringify(data)); + }); } catch (err) { - console.error(`getAssociatedDataSync err, code is ${e.code}, message is ${e.message}`); + console.log('getAuthList err: ' + JSON.stringify(err)); } ``` -### on('accountChange')9+ +### getAuthList9+ -on(type: 'accountChange', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void +getAuthList(name: string, authType: string): Promise<Array<string>> -订阅指定帐号所有者的帐户变更事件,使用callback回调异步返回结果。 +获取指定应用帐户和鉴权类型的Auth令牌的授权列表。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | 'accountChange' | 是 | 关于帐号更改事件,当帐号所有者更新帐号时,订阅者将收到通知。 | -| owners | Array<string> | 是 | 指示帐号的所有者。 | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 订阅指定帐号所有者的帐号变更事件的回调。 | - -**示例:** - - ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); - } - try{ - appAccountManager.on('accountChange', ["com.example.actsaccounttest"], changeOnCallback); - } - catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); - } - ``` - -### on('change')(deprecated) - -on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void - -订阅指定帐号所有者的帐户变更事件,使用callback回调异步返回结果。 +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ----------------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 应用帐号的鉴权类型的Auth令牌的授权列表。 | -> **说明:** 从API version 9开始废弃, 建议使用[on('accountChange')](#onaccountchange9)替代。 -> -> 从 API version 7开始支持。 +**返回值:** -**系统能力:** SystemCapability.Account.AppAccount +| 类型 | 说明 | +| ---------------------------------- | --------------------- | +| Promise<Array<string>> | Promise对象。返回指定应用帐户和鉴权类型的Auth令牌的授权列表对象。 | -**参数:** +**错误码:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ------------------------------ | -| type | 'change' | 是 | 关于帐号更改事件,当帐号所有者更新帐号时,订阅者将收到通知。 | -| owners | Array<string> | 是 | 指示帐号的所有者。 | -| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 订阅指定帐号所有者的帐号变更事件的回调。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or authType. | + | 12300003 | the account indicated by name dose not exist. | + | 12300015 | the authType is not supported on current device. | + | 12300019 | credential does not exist. | **示例:** ```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)); + try { + appAccountManager.getAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { + console.log('getAuthList data: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getAuthList err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("getAuthList err: " + JSON.stringify(err)); } ``` -### off('accountChange')9+ +### getAuthCallback9+ -off(type: 'accountChange', callback?: Callback>): void +getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): void -取消订阅帐号事件,使用callback回调异步返回结果。 +获取鉴权会话的认证器回调。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------- | ---- | ------------ | -| type | 'accountChange' | 是 | 关于帐号更改事件。 | -| callback | Callback> | 否 | 取消订阅帐号事件的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | 是 | 鉴权会话的标识。 | +| callback | AsyncCallback<[AuthCallback](#authcallback9)> | 是 | 回调函数。当获取鉴权会话的认证器回调函数成功时,err为undefined,data为认证器回调函数;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12400005 | the session indicated by sessionId does not exist. | **示例:** ```js + import featureAbility from '@ohos.ability.featureAbility'; const appAccountManager = account_appAccount.createAppAccountManager(); - function changeOnCallback(data){ - console.debug("receive change data:" + JSON.stringify(data)); - appAccountManager.off('accountChange', function(){ - console.debug("off finish"); - }) - } - try{ - appAccountManager.on('accountChange', ["com.example.actsaccounttest"], changeOnCallback); - } - catch(err){ - console.error("on accountOnOffDemo err:" + JSON.stringify(err)); - } + 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 = {[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("getAuthCallback err: " + JSON.stringify(err)); + } + }); ``` -### off('change')(deprecated) - -off(type: 'change', callback?: Callback>): void +### getAuthCallback9+ -取消订阅帐号事件,使用callback回调异步返回结果。 +getAuthCallback(sessionId: string): Promise<AuthCallback> -> **说明:** 从API version 9开始废弃, 建议使用[off('accountChange')](#offaccountchange9)替代。 -> -> 从 API version 7开始支持。 +获取鉴权会话的认证器回调。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------- | ---- | ------------ | -| type | 'change' | 是 | 关于帐号更改事件。 | -| callback | Callback> | 否 | 取消订阅帐号事件的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | -------- | +| sessionId | string | 是 | 鉴权会话的标识。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------ | --------------------- | +| Promise<[AuthCallback](#authcallback9)> | Promise对象。返回鉴权会话的认证器回调对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12400005 | the session indicated by sessionId does not exist. | **示例:** ```js + import featureAbility from '@ohos.ability.featureAbility'; + 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)); - } + featureAbility.getWant().then((want) => { + var sessionId = want.parameters[account_appAccount.Constants.KEY_SESSION_ID]; + try { + appAccountManager.getAuthCallback(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("getAuthCallback err: " + JSON.stringify(err)); + }); + } + }).catch((err) => { + console.log("getWant err: " + JSON.stringify(err)); + }); ``` -### auth9+ +### queryAuthenticatorInfo9+ -auth(name: string, owner: string, authType: string, callback: AuthCallback): void +queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void -对应用帐户进行鉴权以获取Auth令牌,使用callback回调异步返回结果。 +获取指定应用帐号的认证器信息。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ---- | --------------- | -| name | string | 是 | 要鉴权的应用帐号名称。 | -| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,用于返回鉴权结果。 | - -**示例:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | 是 | 应用帐号的所有者包名。 | +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 回调函数。当获取指定应用帐号的认证器信息成功时,err为undefined,data为认证器信息对象;否则为错误对象。 | - ```js - import featureAbility from '@ohos.ability.featureAbility'; +**错误码:** - function onResultCallback(code, result) { - console.log("resultCode: " + code); - console.log("result: " + JSON.stringify(result)); - } + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid owner. | + | 12300003 | the account indicated by owner dose not exist. | - function onRequestRedirectedCallback(request) { - let abilityStartSetting = {want: request}; - featureAbility.startAbility(abilityStartSetting, (err)=>{ - console.log("startAbility err: " + JSON.stringify(err)); - }); - } +**示例:** + ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.auth("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback + appAccountManager.queryAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { + console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); + console.log('queryAuthenticatorInfo data: ' + JSON.stringify(data)); }); } catch (err) { - console.log("auth err: " + JSON.stringify(err)); + console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); } ``` -### auth9+ +### queryAuthenticatorInfo9+ -auth(name: string, owner: string, authType: string, options: {[key: string]: Object}, callback: AuthCallback): void +queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> -对应用帐户进行鉴权以获取OAuth令牌,使用callback回调异步返回结果。 +获取指定应用帐户的认证器信息。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ---- | --------------- | -| name | string | 是 | 要鉴权的应用帐号名称。 | -| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| options | {[key: string]: Object} | 是 | 鉴权所需的可选项。 | -| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,用于返回鉴权结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------- | +| owner | string | 是 | 应用帐号的所有者包名。 | -**示例:** +**返回值:** - ```js - import featureAbility from '@ohos.ability.featureAbility'; +| 类型 | 说明 | +| -------------------------------- | --------------------- | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise对象。返回指定应用帐户的认证器信息对象。 | - 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)); - }); - } + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid owner. | + | 12300003 | the account indicated by owner dose not exist. | + +**示例:** + ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.auth("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback + appAccountManager.queryAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { + console.log('queryAuthenticatorInfo: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); }); } catch (err) { - console.log("auth err: " + JSON.stringify(err)); + console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); } ``` -### authenticate(deprecated) - -authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void +### checkAccountLabels9+ -对应用帐户进行鉴权以获取OAuth令牌,使用callback回调异步返回结果。 +checkAccountLabels(name: string, owner: string, labels: Array<string>, callback: AsyncCallback<boolean>): void; -> **说明:** 从API version 9开始废弃, 建议使用[auth](#auth9)替代。 -> -> 从 API version 8开始支持。 +检查指定帐户是否具有特定的标签集合。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ---- | --------------- | -| name | string | 是 | 要鉴权的应用帐号名称。 | -| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| options | {[key: string]: any} | 是 | 鉴权所需的可选项。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回鉴权结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------------------------- | ----- | --------------- | +| name | string | 是 | 应用帐户的名称。 | +| owner | string | 是 | 应用帐户的所有者。| +| labels | Array<string> | 是 | 标签数组。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查指定帐户是否具有特定的标签集合成功时,err为undefined,data为true表示具有特定标签,data为false表示不具有特定标签;否则为错误对象。 | -**示例:** +**错误码:** - ```js - import featureAbility from '@ohos.ability.featureAbility'; + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or owner. | + | 12300003 | the account indicated by owner dose not exist. | + | 12400001 | the application indicated by name does not exist. | - 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)); + ```js + const appAccountManager = account_appAccount.createAppAccountManager(); + var labels = ["student"]; + try { + appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels, (err, data) => { + console.log('checkAccountLabels: ' + JSON.stringify(data)); + console.log("checkAccountLabels err: " + JSON.stringify(err)); }); + } catch (err) { + console.log("checkAccountLabels err: " + JSON.stringify(err)); } - - const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { - onResult: onResultCallback, - onRequestRedirected: onRequestRedirectedCallback - }); ``` -### getAuthToken9+ +### checkAccountLabels9+ -getAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void +checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> -获取指定应用帐号和鉴权类型的Auth令牌,使用callback回调异步返回结果。 +检查指定帐户是否具有特定的标签集合。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| callback | AsyncCallback<string> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------------------------- | ----- | --------------- | +| name | string | 是 | 应用帐户的名称。 | +| owner | string | 是 | 应用帐户的所有者。| +| labels | Array<string> | 是 | 标签数组。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| Promise<boolean> | Promise对象。返回true表示指定帐户具有特定的标签集合,返回false表示不具有特性的标签集合。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or owner. | + | 12300003 | the account indicated by owner dose not exist. | + | 12400001 | the application indicated by name does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); + var labels = ["student"]; try { - appAccountManager.getAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getAuthToken err: ' + JSON.stringify(err)); - console.log('getAuthToken token: ' + data); + appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels).then((data) => { + console.log('checkAccountLabels: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("checkAccountLabels err: " + JSON.stringify(err)); }); } catch (err) { - console.log('getAuthToken err: ' + JSON.stringify(err)); + console.log("checkAccountLabels err: " + JSON.stringify(err)); } ``` -### getAuthToken9+ +### deleteCredential9+ -getAuthToken(name: string, owner: string, authType: string): Promise<string> +deleteCredential(name: string, credentialType: string, callback: AsyncCallback<void>): void -获取指定应用帐户和鉴权类型的Auth令牌,使用Promise方式异步返回结果。 +删除指定应用帐户的指定类型的凭据信息。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------------------------- | ----- | -------------- | +| name | string | 是 | 应用帐户的名称。 | +| credentialType | string | 是 | 凭据类型。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除指定应用帐户的指定类型的凭据信息成功时,err为undefined;否则为错误对象。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| --------------------- | --------------------- | -| Promise<string> | Promise实例,用于获取异步返回结果。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or credentialType. | + | 12300019 | credential does not exist. | + | 12400001 | the application indicated by name does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.getAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getAuthToken token: ' + data); - }).catch((err) => { - console.log("getAuthToken err: " + JSON.stringify(err)); + appAccountManager.deleteCredential("zhangsan", "pin", (err, data) => { + console.log('deleteCredential: ' + JSON.stringify(data)); + console.log("deleteCredential err: " + JSON.stringify(err)); }); } catch (err) { - console.log("getAuthToken err: " + JSON.stringify(err)); + console.log("deleteCredential err: " + JSON.stringify(err)); } ``` -### getOAuthToken(deprecated) - -getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void +### deleteCredential9+ -获取指定应用帐号和鉴权类型的OAuth令牌,使用callback回调异步返回结果。 +deleteCredential(name: string, credentialType: string): Promise<void> -> **说明:** 从API version 9开始废弃, 建议使用[getAuthToken](#getauthtoken9)替代。 -> -> 从 API version 8开始支持。 +删除指定应用帐户的指定类型的凭据信息。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------------- | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| callback | AsyncCallback<string> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------ | ----- | --------------- | +| name | string | 是 | 应用帐户的名称。 | +| credentialType | string | 是 | 凭据类型。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name or credentialType. | + | 12300019 | credential does not exist. | + | 12400001 | the application indicated by name does not exist. | **示例:** ```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); - }); + try { + appAccountManager.deleteCredential("zhangsan", "pin").then((data) => { + console.log('deleteCredential: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("deleteCredential err: " + JSON.stringify(err)); + }); + } catch (err) { + console.log("deleteCredential err: " + JSON.stringify(err)); + } ``` -### getOAuthToken(deprecated) - -getOAuthToken(name: string, owner: string, authType: string): Promise<string> +### selectAccountsByOptions9+ -获取指定应用帐户和鉴权类型的OAuth令牌,使用Promise方式异步返回结果。 +selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>); -> **说明:** 从API version 9开始废弃, 建议使用[getAuthToken](#getauthtoken9-1)替代。 -> -> 从 API version 8开始支持。 +根据选项选择请求方可访问的帐号列表。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ----------------------------------- | ----- | --------------- | +| options | SelectAccountsOptions | 是 | 选择帐户的选项。 | +| callback | AsyncCallback<[AppAccountInfo](#appaccountinfo)> | 是 | 回调函数。当根据选项选择请求方可访问的帐号列表时,err为undefined,data为可访问的帐号信息对象;否则为错误对象。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| --------------------- | --------------------- | -| Promise<string> | Promise实例,用于获取异步返回结果。 | - -**示例:** - - ```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)); - }); - ``` - -### setAuthToken9+ - -setAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void - -设置指定应用帐号和鉴权类型的Auth令牌,使用callback回调异步返回结果。 - -**系统能力:** SystemCapability.Account.AppAccount - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | -------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | Auth令牌。 | -| callback | AsyncCallback<void> | 是 | 设置结果的回调。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid options. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); + var options = { + allowedOwners: ["com.example.ohos.accountjsdemo"] + }; try { - appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx", (err) => { - console.log('setAuthToken err: ' + JSON.stringify(err)); + appAccountManager.selectAccountsByOptions(options, (err, data) => { + console.log('selectAccountsByOptions: ' + JSON.stringify(data)); + console.log("selectAccountsByOptions err: " + JSON.stringify(err)); }); } catch (err) { - console.log('setAuthToken err: ' + JSON.stringify(err)); + console.log("selectAccountsByOptions err: " + JSON.stringify(err)); } ``` -### setAuthToken9+ +### selectAccountsByOptions9+ -setAuthToken(name: string, authType: string, token: string): Promise<void> +selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> -设置指定应用帐户和鉴权类型的Auth令牌,使用Promise方式异步返回结果。 +根据选项选择请求方可访问的帐户列表。使用Promise异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | -------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | Auth令牌。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------------------------- | ----- | --------------- | +| options | [SelectAccountsOptions](#selectaccountsoptions9) | 是 | 选择帐户的选项。 | **返回值:** -| 类型 | 说明 | -| ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ------------------- | -------------------------------- | +| Promise<[AppAccountInfo](#appaccountinfo)> | Promise对象。返回请求方可访问的帐户对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid options. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); + var options = { + allowedOwners: ["com.example.ohos.accountjsdemo"] + }; try { - appAccountManager.setAuthToken("LiSi", "getSocialData", "xxxx").then(() => { - console.log('setAuthToken successfully'); + appAccountManager.selectAccountsByOptions(options).then((data) => { + console.log('selectAccountsByOptions: ' + JSON.stringify(data)); }).catch((err) => { - console.log('setAuthToken err: ' + JSON.stringify(err)); + console.log("selectAccountsByOptions err: " + JSON.stringify(err)); }); } catch (err) { - console.log('setAuthToken err: ' + JSON.stringify(err)); + console.log("selectAccountsByOptions err: " + JSON.stringify(err)); } ``` -### setOAuthToken(deprecated) - -setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void +### verifyCredential9+ -设置指定应用帐号和鉴权类型的OAuth令牌,使用callback回调异步返回结果。 +verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): void; -> **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9)替代。 -> -> 从 API version 8开始支持。 +验证用户凭据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | -------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | OAuth令牌。 | -| callback | AsyncCallback<void> | 是 | 设置结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ----- | ----------------------- | +| name | string | 是 | 应用帐户的名称。 | +| owner | string | 是 | 应用帐户的所有者。 | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 回调函数。返回认证结果回调函数。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner or options. | + | 12300003 | the account indicated by owner dose not exist. | + | 12400001 | the application indicated by name does not exist. | + | 12400002 | the account authenticator service does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { - console.log('setOAuthToken err: ' + JSON.stringify(err)); - }); + try { + 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)); + } + }); + } catch (err) { + console.log("verifyCredential err: " + JSON.stringify(err)); + } ``` -### setOAuthToken(deprecated) - -setOAuthToken(name: string, authType: string, token: string): Promise<void> +### verifyCredential9+ -设置指定应用帐户和鉴权类型的OAuth令牌,使用Promise方式异步返回结果。 +verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; -> **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9-1)替代。 -> -> 从 API version 8开始支持。 +验证用户凭据。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | -------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | OAuth令牌。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ----------------------- | ----- | ----------------------- | +| name | string | 是 | 应用帐户的名称。 | +| owner | string | 是 | 应用帐户的所有者。 | +| options | [VerifyCredentialOptions](#verifycredentialoptions9) | 是 | 验证凭据的选项。 | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 回调函数。返回认证结果回调函数。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid name, owner or options. | + | 12300003 | the account indicated by owner dose not exist. | + | 12400001 | the application indicated by name does not exist. | + | 12400002 | the account authenticator service does not exist. | **示例:** ```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)); - }); + var options = { + credentialType: "pin", + credential: "123456" + }; + try { + 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)); + } + }); + } catch (err) { + console.log("verifyCredential err: " + JSON.stringify(err)); + } ``` -### deleteAuthToken9+ +### setAuthenticatorProperties9+ -deleteAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void +setAuthenticatorProperties(owner: string, callback: AuthCallback): void; -删除指定应用帐户和鉴权类型的Auth令牌,使用callback回调异步返回结果。 +设置认证器属性。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------ | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的Auth令牌。 | -| callback | AsyncCallback<void> | 是 | 删除结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ----- | ----------------------- | +| owner | string | 是 | 认证器的所有者。 | +| callback | [AuthCallback](#authcallback9) | 是 | 回调函数。返回设置属性结果回调函数。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid owner or options. | + | 12300003 | the account indicated by owner dose not exist. | + | 12400002 | the account authenticator service does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); try { - appAccountManager.deleteAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { - console.log('deleteAuthToken err: ' + JSON.stringify(err)); + 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)); + } }); } catch (err) { - console.log('deleteAuthToken err: ' + JSON.stringify(err)); + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); } ``` -### deleteAuthToken9+ +### setAuthenticatorProperties9+ -deleteAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> +setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callback: AuthCallback): void; -删除指定应用帐户和鉴权类型的Auth令牌,使用Promise方式异步返回结果。 +设置认证器属性。使用callback异步回调。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------ | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的Auth令牌。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ----- | ----------------------- | +| owner | string | 是 | 认证器的所有者。 | +| options | [SetPropertiesOptions](#setpropertiesoptions9) | 是 | 设置属性的选项。 | +| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,返回设置属性结果回调函数。 | -**返回值:** +**错误码:** -| 类型 | 说明 | -| ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | + | 错误码ID | 错误信息| + | ------- | -------| + | 12300001 | system service exception. | + | 12300002 | invalid owner or options. | + | 12300003 | the account indicated by owner dose not exist. | + | 12400002 | the account authenticator service does not exist. | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); + var options = { + properties: {"prop1": "value1"} + }; try { - appAccountManager.deleteAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx").then(() => { - console.log('deleteAuthToken successfully'); - }).catch((err) => { - console.log("deleteAuthToken err: " + JSON.stringify(err)); - }); + 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)); + } + }); } catch (err) { - console.log("deleteAuthToken err: " + JSON.stringify(err)); - } + console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); + } + ``` -### deleteOAuthToken(deprecated) +### addAccount(deprecated) -deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void +addAccount(name: string, callback: AsyncCallback<void>): void -删除指定应用帐户和鉴权类型的OAuth令牌,使用callback回调异步返回结果。 +将此应用的帐号名添加到帐号管理服务中。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[deleteAuthToken](#deleteauthtoken9)替代。 +> **说明:** +> 从API version 9开始废弃, 建议使用[createAccount](#createaccount9)替代 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------ | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的OAuth令牌。 | -| callback | AsyncCallback<void> | 是 | 删除结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | -------------------- | +| name | string | 是 | 要添加的应用帐号名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当此应用的帐号名添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { - console.log('deleteOAuthToken err: ' + JSON.stringify(err)); + appAccountManager.addAccount("WangWu", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); }); ``` -### deleteOAuthToken(deprecated) +### addAccount(deprecated) -deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> +addAccount(name: string, extraInfo: string, callback: AsyncCallback<void>): void -删除指定应用帐户和鉴权类型的OAuth令牌,使用Promise方式异步返回结果。 +将此应用程序的帐号名和额外信息(能转换string类型的其它信息,如token)添加到帐号管理服务中。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9-1)替代。 -> -> 从 API version 8开始支持。 +> **说明:** > 从API version 9开始废弃, 建议使用[createAccount](#createaccount9-1)替代 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ------------ | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| authType | string | 是 | 鉴权类型。 | -| token | string | 是 | 要删除的OAuth令牌。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | ---------------------------------------- | +| name | string | 是 | 要添加的应用帐号名称。 | +| extraInfo | string | 是 | 要添加的应用帐号的额外信息(能转换string类型的其它信息,如token等),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当此应用程序的帐号名和额外信息添加到帐号管理服务成功时,err为undefined,否则为错误对象。 | **示例:** ```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)); + appAccountManager.addAccount("LiSi", "token101", (err) => { + console.log("addAccount err: " + JSON.stringify(err)); }); ``` -### setAuthTokenVisibility9+ +### addAccount(deprecated) -setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void +addAccount(name: string, extraInfo?: string): Promise<void> + +将此应用的帐号名或额外信息(能转换成string类型的其它信息)添加到帐号管理服务中。使用Promise异步回调。 -设置指定鉴权类型的Auth令牌对特定应用的可见性,使用callback回调异步返回结果。 +> **说明:** > 从API version 9开始废弃, 建议使用[createAccount](#createaccount9-2)替代 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | ------------------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。当设置成true可见,false不可见。 | -| callback | AsyncCallback<void> | 是 | 设置结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | ---------------------------------------- | +| name | string | 是 | 要添加的应用帐号名称。 | +| extraInfo | string | 否 | 要添加的应用帐号的额外信息(能转换成string类型的其它信息),额外信息不能是应用帐号的敏感信息(如应用账号密码)。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | --------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); - }); - } catch (err) { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); - } + appAccountManager.addAccount("LiSi", "token101").then(()=> { + console.log('addAccount Success'); + }).catch((err) => { + console.log("addAccount err: " + JSON.stringify(err)); + }); ``` -### setAuthTokenVisibility9+ +### addAccountImplicitly(deprecated) -setAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> +addAccountImplicitly(owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void + +根据指定的帐号所有者、鉴权类型和可选项隐式地添加应用帐号,并使用callback回调异步返回结果。 -设置指定鉴权类型的OAuth令牌对特定应用的可见性,使用Promise方式异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[createAccountImplicitly](#createaccountimplicitly9)替代。 +> +> 从 API version 8开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------- | ---- | ------------ | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | ----------------------- | +| owner | string | 是 | 要添加的应用帐号所有者包名。 | +| authType | string | 是 | 要添加的应用帐号鉴权类型。鉴权类型为自定义。 | +| options | {[key: string]: any} | 是 | 鉴权所需要的可选项。可选项可根据自己需要设置。 | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,用于返回鉴权结果。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.setAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true).then(() => { - console.log('setAuthTokenVisibility successfully'); - }).catch((err) => { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); + 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)); }); - } catch (err) { - console.log('setAuthTokenVisibility err: ' + JSON.stringify(err)); } + + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.addAccountImplicitly("com.example.ohos.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); ``` -### setOAuthTokenVisibility(deprecated) +### deleteAccount(deprecated) -setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void +deleteAccount(name: string, callback: AsyncCallback<void>): void -设置指定鉴权类型的Auth令牌对特定应用的可见性,使用callback回调异步返回结果。 +从帐号管理服务中删除应用帐号。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[setAuthTokenVisibility](#setauthtokenvisibility9)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[removeAccount](#removeaccount9)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | ------------------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。当设置成true可见,false不可见。 | -| callback | AsyncCallback<void> | 是 | 设置结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ---------------- | +| name | string | 是 | 要删除的应用帐号名称。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当帐号管理服务中删除应用帐号成功时,err为undefined,否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { - console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); - }); + appAccountManager.deleteAccount("ZhaoLiu", (err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); + }); ``` -### setOAuthTokenVisibility(deprecated) +### deleteAccount(deprecated) -setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> +deleteAccount(name: string): Promise<void> -设置指定鉴权类型的OAuth令牌对特定应用的可见性,使用Promise方式异步返回结果。 +从帐号管理服务中删除应用帐号。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[setAuthTokenVisibility](#setauthtokenvisibility9-1)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[removeAccount](#removeaccount9)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------- | ---- | ------------ | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 被设置可见性的应用包名。 | -| isVisible | boolean | 是 | 是否可见。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ----------- | +| name | string | 是 | 要删除的应用帐号名称。 | **返回值:** | 类型 | 说明 | -| ------------------- | --------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```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)); + appAccountManager.deleteAccount("ZhaoLiu").then(() => { + console.log('deleteAccount Success'); + }).catch((err) => { + console.log("deleteAccount err: " + JSON.stringify(err)); }); ``` +### disableAppAccess(deprecated) -### checkAuthTokenVisibility9+ +disableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void -checkAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void +禁止指定第三方应用帐号名称对指定的第三方应用进行访问。使用callback异步回调。 -检查指定鉴权类型的Auth令牌对特定应用的可见性,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9)替代。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ---------------------------- | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 检查可见性的应用包名。 | -| callback | AsyncCallback<boolean> | 是 | 检查结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | --------------------------------- | +| name | string | 是 | 要禁用访问的第三方应用帐号名称。 | +| bundleName | string | 是 | 第三方应用的包名。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当禁止指定第三方应用帐号名称对指定包名称的第三方应用进行访问设置成功时,err为undefined,否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", (err, data) => { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); - console.log('checkAuthTokenVisibility isVisible: ' + data); - }); - } catch (err) { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); - } + appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); ``` -### checkAuthTokenVisibility9+ +### disableAppAccess(deprecated) -checkAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> +disableAppAccess(name: string, bundleName: string): Promise<void> + +禁止指定第三方应用帐号名称对指定包名称的第三方应用进行访问。使用Promise异步回调。 -检查指定鉴权类型的Auth令牌对特定应用的可见性,使用Promise方式异步返回结果。 +> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9-1)替代。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | ------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 用于检查可见性的应用包名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ---------------- | +| name | string | 是 | 要禁用访问的第三方应用帐号名称。 | +| bundleName | string | 是 | 第三方应用的包名。 | **返回值:** -| 类型 | 说明 | -| ---------------------- | --------------------- | -| Promise<boolean> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.checkAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { - console.log('checkAuthTokenVisibility isVisible: ' + data); - }).catch((err) => { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); - }); - } catch (err) { - console.log('checkAuthTokenVisibility err: ' + JSON.stringify(err)); - } + appAccountManager.disableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { + console.log('disableAppAccess Success'); + }).catch((err) => { + console.log("disableAppAccess err: " + JSON.stringify(err)); + }); ``` -### checkOAuthTokenVisibility(deprecated) +### enableAppAccess(deprecated) -checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void +enableAppAccess(name: string, bundleName: string, callback: AsyncCallback<void>): void -检查指定鉴权类型的OAuth令牌对特定应用的可见性,使用callback回调异步返回结果。 +允许指定第三方应用帐号名称对指定包名称的第三方应用进行访问。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[checkAuthTokenVisibility](#checkauthtokenvisibility9)替代。 +> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ---------------------------- | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 检查可见性的应用包名。 | -| callback | AsyncCallback<boolean> | 是 | 检查结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | --------------------------------- | +| name | string | 是 | 应用帐号名称。 | +| bundleName | string | 是 | 第三方应用的包名。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当允许指定第三方应用帐号名称对指定包名称的第三方应用进行访问设置成功时,err为undefined,否则为错误对象。 | **示例:** ```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); - }); + appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo", (err) => { + console.log("enableAppAccess: " + JSON.stringify(err)); + }); ``` +### enableAppAccess(deprecated) -### checkOAuthTokenVisibility(deprecated) - -checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> +enableAppAccess(name: string, bundleName: string): Promise<void> -检查指定鉴权类型的OAuth令牌对特定应用的可见性,使用Promise方式异步返回结果。 +允许指定第三方应用帐号的名称对指定包名称的第三方应用进行访问。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[checkAuthTokenVisibility](#checkauthtokenvisibility9-1)替代。 +> **说明:** 从API version 9开始废弃。建议使用[setAppAccess](#setappaccess9-1)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ---------- | ------ | ---- | ------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 鉴权类型。 | -| bundleName | string | 是 | 用于检查可见性的应用包名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号名称。 | +| bundleName | string | 是 | 第三方应用的包名。 | **返回值:** -| 类型 | 说明 | -| ---------------------- | --------------------- | -| Promise<boolean> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.checkOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo").then((data) => { - console.log('checkOAuthTokenVisibility isVisible: ' + data); + appAccountManager.enableAppAccess("ZhangSan", "com.example.ohos.accountjsdemo").then(() => { + console.log('enableAppAccess Success'); }).catch((err) => { - console.log('checkOAuthTokenVisibility err: ' + JSON.stringify(err)); + console.log("enableAppAccess err: " + JSON.stringify(err)); }); ``` -### getAllAuthTokens9+ +### checkAppAccountSyncEnable(deprecated) -getAllAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void +checkAppAccountSyncEnable(name: string, callback: AsyncCallback<boolean>): void + +检查指定应用帐号是否允许应用数据同步。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃。建议使用[checkDataSyncEnabled](#checkdatasyncenabled9)替代。 +> +> 从 API version 7开始支持。 -获取指定应用对调用方全部可见的Auth令牌,使用callback回调异步返回结果。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<Array< [AuthTokenInfo](#authtokeninfo9)>> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------- | ---- | --------------------- | +| name | string | 是 | 应用帐号名称。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。当检查指定应用帐号是否允许应用数据同步成功,err为undefined,data返回true表示指定应用帐号允许应用数据同步,data返回false表示指定应用帐号不允许应用数据同步;否则为错误对象。 | -**示例:** +**示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.getAllAuthTokens("LiSi", "com.example.ohos.accountjsdemo", (err, data) => { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); - console.log('getAllAuthTokens data: ' + JSON.stringify(data)); - }); - } catch (err) { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); - } + appAccountManager.checkAppAccountSyncEnable("ZhangSan", (err, result) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + console.log('checkAppAccountSyncEnable result: ' + result); + }); ``` -### getAllAuthTokens9+ +### checkAppAccountSyncEnable(deprecated) -getAllAuthTokens(name: string, owner: string): Promise<Array<AuthTokenInfo>> +checkAppAccountSyncEnable(name: string): Promise<boolean> + +检查指定应用帐号是否允许应用数据同步。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃。建议使用[checkDataSyncEnabled](#checkdatasyncenabled9-1)替代。 +> +> 从 API version 7开始支持。 -获取指定应用帐户对调用方可见的全部Auth令牌,使用Promise方式异步返回结果。 +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ------- | +| name | string | 是 | 应用帐号名称。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array< [AuthTokenInfo](#authtokeninfo9)>> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :--------------------- | :-------------------- | +| Promise<boolean> | Promise对象。返回true表示允许应用数据同步;返回false表示不允许应用数据同步。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.getAllAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { - console.log('getAllAuthTokens data: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("getAllAuthTokens err: " + JSON.stringify(err)); - } + appAccountManager.checkAppAccountSyncEnable("ZhangSan").then((data) => { + console.log('checkAppAccountSyncEnable, result: ' + data); + }).catch((err) => { + console.log("checkAppAccountSyncEnable err: " + JSON.stringify(err)); + }); ``` -### getAllOAuthTokens(deprecated) +### setAccountCredential(deprecated) -getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void +setAccountCredential(name: string, credentialType: string, credential: string,callback: AsyncCallback<void>): void -获取指定应用对调用方全部可见的OAuth令牌,使用callback回调异步返回结果。 +设置此应用程序帐号的凭据。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[getAllAuthTokens](#getallauthtokens9)替代。 +> **说明:** 从API version 9开始废弃,建议使用[setCredential](#setcredential9)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------------------------- | ---- | ------------- | +| name | string | 是 | 应用程序帐号名称。 | +| credentialType | string | 是 | 要设置的凭据类型。 | +| credential | string | 是 | 要设置的凭据。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置此应用程序帐号的凭据成功时,err为undefined,否则为错误对象。 | -**示例:** +**示例:** ```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)); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001", (err) => { + console.log("setAccountCredential err: " + JSON.stringify(err)); }); ``` -### getAllOAuthTokens(deprecated) +### setAccountCredential(deprecated) -getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> +setAccountCredential(name: string, credentialType: string, credential: string): Promise<void> -获取指定应用帐户对调用方可见的全部OAuth令牌,使用Promise方式异步返回结果。 +设置此应用程序帐号的凭据。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[getAllAuthTokens](#getallauthtokens9-1)替代。 +> **说明:** 从API version 9开始废弃,建议使用[setCredential](#setcredential9-1)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------- | -| name | string | 是 | 应用帐号的名称。 | -| owner | string | 是 | 应用帐号的所有者包名。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------ | ---- | ---------- | +| name | string | 是 | 应用帐号的名称。 | +| credentialType | string | 是 | 要设置的凭据的类型。 | +| credential | string | 是 | 要设置的凭据。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------------- | --------------------- | -| Promise<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAllOAuthTokens("LiSi", "com.example.ohos.accountjsdemo").then((data) => { - console.log('getAllOAuthTokens data: ' + JSON.stringify(data)); + appAccountManager.setAccountCredential("ZhangSan", "credentialType001", "credential001").then(() => { + console.log('setAccountCredential Success'); }).catch((err) => { - console.log("getAllOAuthTokens err: " + JSON.stringify(err)); + console.log("setAccountCredential err: " + JSON.stringify(err)); }); ``` -### getAuthList9+ +### setAccountExtraInfo(deprecated) -getAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void +setAccountExtraInfo(name: string, extraInfo: string, callback: AsyncCallback<void>): void + +设置此应用程序帐号的额外信息。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃。 +> +> 从 API version 7开始支持。 -获取指定应用帐户和鉴权类型的Auth令牌的授权列表,使用callback回调异步返回结果。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ----------------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的Auth令牌的授权列表。 | -| callback | AsyncCallback<Array<string>> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------------------------- | ---- | --------------- | +| name | string | 是 | 应用帐号名称。 | +| extraInfo | string | 是 | 要设置的额外信息。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置此应用程序帐号的额外信息成功时,err为undefined,否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.getAuthList("com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { - console.log('getAuthList err: ' + JSON.stringify(err)); - console.log('getAuthList data: ' + JSON.stringify(data)); - }); - } catch (err) { - console.log('getAuthList err: ' + JSON.stringify(err)); - } + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002", (err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); ``` -### getAuthList9+ +### setAccountExtraInfo(deprecated) -getAuthList(name: string, authType: string): Promise<Array<string>> +setAccountExtraInfo(name: string, extraInfo: string): Promise<void> + +设置此应用程序帐号的额外信息。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃。 +> +> 从 API version 7开始支持。 -获取指定应用帐户和鉴权类型的Auth令牌的授权列表,使用Promise方式异步返回结果。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ----------------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的Auth令牌的授权列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号名称。 | +| extraInfo | string | 是 | 要设置的额外信息。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------- | --------------------- | -| Promise<Array<string>> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.getAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getAuthList data: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("getAuthList err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("getAuthList err: " + JSON.stringify(err)); - } + appAccountManager.setAccountExtraInfo("ZhangSan", "Tk002").then(() => { + console.log('setAccountExtraInfo Success'); + }).catch((err) => { + console.log("setAccountExtraInfo err: " + JSON.stringify(err)); + }); ``` -### getOAuthList(deprecated) +### setAppAccountSyncEnable(deprecated) -getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void +setAppAccountSyncEnable(name: string, isEnable: boolean, callback: AsyncCallback<void>): void -获取指定应用帐户和鉴权类型的OAuth令牌的授权列表,使用callback回调异步返回结果。 +设置指定的应用程序帐号是否允许应用程序数据同步。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[getAuthList](#getauthlist9)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[setDataSyncEnabled](#setdatasyncenabled9)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------- | ---- | ----------------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的OAuth令牌的授权列表。 | -| callback | AsyncCallback<Array<string>> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------------------- | +| name | string | 是 | 应用帐号名称。 | +| isEnable | boolean | 是 | 是否允许应用数据同步。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定的应用帐号是否允许应用程序数据同步成功时,err为undefined,否则为错误对象。 | **示例:** ```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)); + appAccountManager.setAppAccountSyncEnable("ZhangSan", true, (err) => { + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); }); ``` -### getOAuthList(deprecated) +### setAppAccountSyncEnable(deprecated) -getOAuthList(name: string, authType: string): Promise<Array<string>> +setAppAccountSyncEnable(name: string, isEnable: boolean): Promise<void> -获取指定应用帐户和鉴权类型的OAuth令牌的授权列表,使用Promise方式异步返回结果。 +设置指定的应用程序帐号是否允许应用程序数据同步。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[getAuthList](#getauthlist9-1)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[setDataSyncEnabled](#setdatasyncenabled9-1)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 + +**需要权限:** ohos.permission.DISTRIBUTED_DATASYNC **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------ | ---- | ----------------------- | -| name | string | 是 | 应用帐号的名称。 | -| authType | string | 是 | 应用帐号的鉴权类型的OAuth令牌的授权列表。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------- | ---- | ----------- | +| name | string | 是 | 应用帐号名称。 | +| isEnable | boolean | 是 | 是否允许应用数据同步。 | **返回值:** -| 类型 | 说明 | -| ---------------------------------- | --------------------- | -| Promise<Array<string>> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { - console.log('getOAuthList data: ' + JSON.stringify(data)); + appAccountManager .setAppAccountSyncEnable("ZhangSan", true).then(() => { + console.log('setAppAccountSyncEnable Success'); }).catch((err) => { - console.log("getOAuthList err: " + JSON.stringify(err)); + console.log("setAppAccountSyncEnable err: " + JSON.stringify(err)); }); ``` -### getAuthCallback9+ +### setAssociatedData(deprecated) -getAuthCallback(sessionId: string, callback: AsyncCallback<AuthCallback>): void +setAssociatedData(name: string, key: string, value: string, callback: AsyncCallback<void>): void + +设置与此应用程序帐号关联的数据。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[setCustomData](#setcustomdata9)替代。 +> +> 从 API version 7开始支持。 -获取鉴权会话的认证器回调,使用callback回调异步返回结果。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ---------------------------------------- | ---- | -------- | -| sessionId | string | 是 | 鉴权会话的标识。 | -| callback | AsyncCallback<[AuthCallback](#authcallback9)> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ----------------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | +| value | string | 是 | 要设置的数据的值。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置与此应用帐号关联的数据成功时,err为undefined,否则为错误对象。 | **示例:** ```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]; - try { - appAccountManager.getAuthCallback(sessionId, (err, callback) => { - if (err.code != account_appAccount.ResultCode.SUCCESS) { - console.log("getAuthCallback 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); - }); - } catch (err) { - console.log("getAuthCallback err: " + JSON.stringify(err)); - } + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001", (err) => { + console.log("setAssociatedData err: " + JSON.stringify(err)); }); ``` -### getAuthCallback9+ +### setAssociatedData(deprecated) -getAuthCallback(sessionId: string): Promise<AuthCallback> +setAssociatedData(name: string, key: string, value: string): Promise<void> + +设置与此应用程序帐号关联的数据。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[setCustomData](#setcustomdata9-1)替代。 +> +> 从 API version 7开始支持。 -获取鉴权会话的认证器回调,使用Promise方式异步返回结果。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | -------- | -| sessionId | string | 是 | 鉴权会话的标识。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要设置的数据的键,密钥可以自定义。 | +| value | string | 是 | 要设置的数据的值。 | **返回值:** -| 类型 | 说明 | -| ------------------------------------ | --------------------- | -| Promise<[AuthCallback](#authcallback9)> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :------------------ | :-------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```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]; - try { - appAccountManager.getAuthCallback(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("getAuthCallback err: " + JSON.stringify(err)); - }); - } + appAccountManager.setAssociatedData("ZhangSan", "k001", "v001").then(() => { + console.log('setAssociatedData Success'); }).catch((err) => { - console.log("getWant err: " + JSON.stringify(err)); + console.log("setAssociatedData err: " + JSON.stringify(err)); }); ``` -### getAuthenticatorCallback(deprecated) +### getAllAccessibleAccounts(deprecated) -getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void +getAllAccessibleAccounts(callback: AsyncCallback<Array<AppAccountInfo>>): void -获取鉴权会话的认证器回调,使用callback回调异步返回结果。 +获取全部应用已授权帐号信息。 -> **说明:** 从API version 9开始废弃, 建议使用[getAuthCallback](#getauthcallback9)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[getAllAccounts](#getallaccounts9)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 + +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ---------------------------------------- | ---- | -------- | -| sessionId | string | 是 | 鉴权会话的标识。 | -| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | --------- | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | **示例:** ```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); - }); + appAccountManager.getAllAccessibleAccounts((err, data)=>{ + console.debug("getAllAccessibleAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccessibleAccounts data:" + JSON.stringify(data)); }); ``` -### getAuthenticatorCallback(deprecated) +### getAllAccessibleAccounts(deprecated) -getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> +getAllAccessibleAccounts(): Promise<Array<AppAccountInfo>> -获取鉴权会话的认证器回调,使用Promise方式异步返回结果。 +获取全部应用已授权帐号信息。 -> **说明:** 从API version 9开始废弃, 建议使用[getAuthCallback](#getauthcallback9-1)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[getAllAccounts](#getallaccounts9-1)替代。 > -> 从 API version 8开始支持。 - -**系统能力:** SystemCapability.Account.AppAccount +> 从 API version 7开始支持。 -**参数:** +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 -| 参数名 | 类型 | 必填 | 说明 | -| --------- | ------ | ---- | -------- | -| sessionId | string | 是 | 鉴权会话的标识。 | +**系统能力:** SystemCapability.Account.AppAccount **返回值:** -| 类型 | 说明 | -| ------------------------------------ | --------------------- | -| Promise<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回全部应用已授权帐号信息对象。 | **示例:** ```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)); - }); + appAccountManager.getAllAccessibleAccounts().then((data) => { + console.log('getAllAccessibleAccounts: ' + data); }).catch((err) => { - console.log("getWant err: " + JSON.stringify(err)); + console.log("getAllAccessibleAccounts err: " + JSON.stringify(err)); }); ``` -### queryAuthenticatorInfo9+ +### getAllAccounts(deprecated) -queryAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void +getAllAccounts(owner: string, callback: AsyncCallback<Array<AppAccountInfo>>): void + +获取指定应用全部帐号信息。 -获取指定应用帐号的认证器信息,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[getAccountsByOwner]替代。 +> +> 从 API version 7开始支持。 + +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------- | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | --------- | +| owner | string | 是 | 应用包名称。 | +| callback | AsyncCallback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 应用帐号信息列表。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.queryAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); - console.log('queryAuthenticatorInfo data: ' + JSON.stringify(data)); - }); - } catch (err) { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); - } + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle, (err, data)=>{ + console.debug("getAllAccounts err:" + JSON.stringify(err)); + console.debug("getAllAccounts data:" + JSON.stringify(data)); + }); ``` -### queryAuthenticatorInfo9+ +### getAllAccounts(deprecated) -queryAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> +getAllAccounts(owner: string): Promise<Array<AppAccountInfo>> + +获取指定应用全部帐号信息。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAccountsByOwner](#getaccountsbyowner9-1)替代。 +> +> 从 API version 7开始支持。 -获取指定应用帐户的认证器信息,使用Promise方式异步返回结果。 +**需要权限:** ohos.permission.GET_ALL_APP_ACCOUNTS,仅系统应用可用。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ------ | +| owner | string | 是 | 应用包名称。 | **返回值:** -| 类型 | 说明 | -| -------------------------------- | --------------------- | -| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array<[AppAccountInfo](#appaccountinfo)>> | Promise对象。返回指定应用全部帐号信息对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.queryAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { - console.log('queryAuthenticatorInfo: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("queryAuthenticatorInfo err: " + JSON.stringify(err)); - } + const selfBundle = "com.example.actsgetallaaccounts"; + appAccountManager.getAllAccounts(selfBundle).then((data) => { + console.log('getAllAccounts: ' + data); + }).catch((err) => { + console.log("getAllAccounts err: " + JSON.stringify(err)); + }); ``` -### getAuthenticatorInfo(deprecated) +### getAccountCredential(deprecated) -getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void +getAccountCredential(name: string, credentialType: string, callback: AsyncCallback<string>): void -获取指定应用帐号的认证器信息,使用callback回调异步返回结果。 +获取此应用帐号的凭据(如数字密码、人脸和PIN码等)。使用callback异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[queryAuthenticatorInfo](#queryauthenticatorinfo9)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[getCredential](#getcredential9)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | -------------------------------------- | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | -| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 查询结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | --------------------------- | ---- | -------------- | +| name | string | 是 | 应用帐号名称。 | +| credentialType | string | 是 | 获取此应用帐号的凭据的类型。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取此应用帐号的凭据成功时,err为undefined,data返回此应用帐号的凭据对象;否则为错误对象。 | **示例:** ```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)); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001", (err, result) => { + console.log("getAccountCredential err: " + JSON.stringify(err)); + console.log('getAccountCredential result: ' + result); }); ``` -### getAuthenticatorInfo(deprecated) +### getAccountCredential(deprecated) -getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> +getAccountCredential(name: string, credentialType: string): Promise<string> -获取指定应用帐户的认证器信息,使用Promise方式异步返回结果。 +获取此应用程序帐号的凭据。使用Promise异步回调。 -> **说明:** 从API version 9开始废弃, 建议使用[queryAuthenticatorInfo](#queryauthenticatorinfo9-1)替代。 +> **说明:** 从API version 9开始废弃, 建议使用[getCredential](#getcredential9-1)替代。 > -> 从 API version 8开始支持。 +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| ----- | ------ | ---- | ----------- | -| owner | string | 是 | 应用帐号的所有者包名。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------------- | ------ | ---- | ---------- | +| name | string | 是 | 应用帐号名称。 | +| credentialType | string | 是 | 要获取的凭据的类型。 | **返回值:** -| 类型 | 说明 | -| -------------------------------- | --------------------- | -| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :-------------------- | :-------------------- | +| Promise<string> | Promise对象。返回此应用程序帐号的凭据对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { - console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + appAccountManager.getAccountCredential("ZhangSan", "credentialType001").then((data) => { + console.log('getAccountCredential, result: ' + data); }).catch((err) => { - console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log("getAccountCredential err: " + JSON.stringify(err)); }); ``` -### checkAccountLabels9+ +### getAccountExtraInfo(deprecated) -checkAccountLabels(name: string, owner: string, labels: Array<string>, callback: AsyncCallback<boolean>): void; +getAccountExtraInfo(name: string, callback: AsyncCallback<string>): void + +获取此应用帐号的额外信息(能转换成string类型的其它信息)。使用callback异步回调。 -检查指定帐户是否具有特定的标签集合,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------------------------- | ----- | --------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。| -| labels | Array<string> | 是 | 标签数组。 | -| callback | AsyncCallback<boolean> | 是 | 检查结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | --------------- | +| name | string | 是 | 应用帐号名称。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取此应用帐号的额外信息成功时,err为undefined,data返回此应用帐号的额外信息对象;否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; - try { - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels, (err, data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); - console.log("checkAccountLabels err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("checkAccountLabels err: " + JSON.stringify(err)); - } + appAccountManager.getAccountExtraInfo("ZhangSan", (err, result) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + console.log('getAccountExtraInfo result: ' + result); + }); ``` -### checkAccountLabels9+ +### getAccountExtraInfo(deprecated) -checkAccountLabels(name: string, owner: string, labels: Array<string>): Promise<boolean> +getAccountExtraInfo(name: string): Promise<string> -检查指定帐户是否具有特定的标签集合,使用Promise方式异步返回结果。 +获取此应用程序帐号的额外信息。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------------------------- | ----- | --------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。| -| labels | Array<string> | 是 | 标签数组。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | ------- | +| name | string | 是 | 应用帐号名称。 | **返回值:** -| 类型 | 说明 | -| ------------------- | -------------------------------- | -| Promise<boolean> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :-------------------- | :-------------------- | +| Promise<string> | Promise对象。返回此应用程序帐号的额外信息对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - var labels = ["student"]; - try { - appAccountManager.checkAccountLabels("zhangsan", "com.example.ohos.accountjsdemo", labels).then((data) => { - console.log('checkAccountLabels: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("checkAccountLabels err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("checkAccountLabels err: " + JSON.stringify(err)); - } + appAccountManager.getAccountExtraInfo("ZhangSan").then((data) => { + console.log('getAccountExtraInfo, result: ' + data); + }).catch((err) => { + console.log("getAccountExtraInfo err: " + JSON.stringify(err)); + }); ``` -### deleteAccountCredential9+ +### getAssociatedData(deprecated) + +getAssociatedData(name: string, key: string, callback: AsyncCallback<string>): void -deleteAccountCredential(name: string, credentialType: string, callback: AsyncCallback<void>): void +获取与此应用程序帐号关联的数据。使用callback异步回调。 -删除指定应用帐户的指定类型的凭据信息,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[getCustomData](#getcustomdata9)替代。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------------------------- | ----- | -------------- | -| name | string | 是 | 应用帐户的名称。 | -| credentialType | string | 是 | 凭据类型。 | -| callback | AsyncCallback<void> | 是 | 删除结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ----------------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要获取的数据的键。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取与此应用程序帐号关联的数据成功时,err为undefined,data返回与此应用程序帐号关联的数据对象;否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.deleteAccountCredential("zhangsan", "pin", (err, data) => { - console.log('deleteAccountCredential: ' + JSON.stringify(data)); - console.log("deleteAccountCredential err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("deleteAccountCredential err: " + JSON.stringify(err)); - } + appAccountManager.getAssociatedData("ZhangSan", "k001", (err, result) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + console.log('getAssociatedData result: ' + result); + }); ``` -### deleteAccountCredential9+ +### getAssociatedData(deprecated) + +getAssociatedData(name: string, key: string): Promise<string> -deleteAccountCredential(name: string, credentialType: string): Promise<void> +获取与此应用程序帐号关联的数据。使用Promise异步回调。 -删除指定应用帐户的指定类型的凭据信息,使用Promise方式异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[getCustomData](#getcustomdata9-1)替代。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------ | ----- | --------------- | -| name | string | 是 | 应用帐户的名称。 | -| credentialType | string | 是 | 凭据类型。 | +| 参数名 | 类型 | 必填 | 说明 | +| ---- | ------ | ---- | --------- | +| name | string | 是 | 应用帐号名称。 | +| key | string | 是 | 要获取的数据的键。 | **返回值:** -| 类型 | 说明 | -| ------------------- | -------------------------------- | -| Promise<void> | Promise实例,用于获取异步返回结果。 | +| 类型 | 说明 | +| :-------------------- | :-------------------- | +| Promise<string> | Promise对象。返回与此应用程序帐号关联的数据对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - appAccountManager.deleteAccountCredential("zhangsan", "pin").then((data) => { - console.log('deleteAccountCredential: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("deleteAccountCredential err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("deleteAccountCredential err: " + JSON.stringify(err)); - } + appAccountManager.getAssociatedData("ZhangSan", "k001").then((data) => { + console.log('getAssociatedData: ' + data); + }).catch((err) => { + console.log("getAssociatedData err: " + JSON.stringify(err)); + }); ``` -### selectAccountsByOptions9+ +### on('change')(deprecated) -selectAccountsByOptions(options: SelectAccountsOptions, callback: AsyncCallback<Array<AppAccountInfo>>); +on(type: 'change', owners: Array<string>, callback: Callback<Array<AppAccountInfo>>): void + +订阅指定帐号所有者的帐户变更事件。使用callback异步回调。 -根据选项选择请求方可访问的帐号列表,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[on('accountChange')](#onaccountchange9)替代。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ----------------------------------- | ----- | --------------- | -| options | SelectAccountsOptions | 是 | 选择帐户的选项。 | -| callback | AsyncCallback<[AppAccountInfo](#appaccountinfo)> | 是 | 选择结果的回调。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ------------------------------ | +| type | 'change' | 是 | 事件回调类型,支持的事件为'change',当帐号所有者更新帐号时,触发该事件。 | +| owners | Array<string> | 是 | 指示帐号的所有者。 | +| callback | Callback<Array<[AppAccountInfo](#appaccountinfo)>> | 是 | 回调函数。返回指定帐号所有者更新的帐号信息数组。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] - }; - try { - appAccountManager.selectAccountsByOptions(options, (err, data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + 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)); } ``` -### selectAccountsByOptions9+ +### off('change')(deprecated) -selectAccountsByOptions(options: SelectAccountsOptions): Promise<Array<AppAccountInfo>> +off(type: 'change', callback?: Callback>): void + +取消订阅帐号事件。使用callback异步回调。 -根据选项选择请求方可访问的帐户列表,使用Promise方式异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[off('accountChange')](#offaccountchange9)替代。 +> +> 从 API version 7开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------------- | ------------------------- | ----- | --------------- | -| options | [SelectAccountsOptions](#selectaccountsoptions9) | 是 | 选择帐户的选项。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | -------------------------------- | -| Promise<[AppAccountInfo](#appaccountinfo)> | Promise实例,用于获取异步返回结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------- | ---- | ------------ | +| type | 'change' | 是 | 事件回调类型,支持的事件为'change',当帐号所有者更新帐号时,触发该事件。 | +| callback | Callback> | 否 | 回调函数,返回指定帐号所有者更新的帐号信息数组。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - allowedOwners: ["com.example.ohos.accountjsdemo"] - }; - try { - appAccountManager.selectAccountsByOptions(options).then((data) => { - console.log('selectAccountsByOptions: ' + JSON.stringify(data)); - }).catch((err) => { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); - }); - } catch (err) { - console.log("selectAccountsByOptions err: " + JSON.stringify(err)); + 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)); } ``` -### verifyCredential9+ +### authenticate(deprecated) -verifyCredential(name: string, owner: string, callback: AuthenticatorCallback): void; +authenticate(name: string, owner: string, authType: string, options: {[key: string]: any}, callback: AuthenticatorCallback): void + +对应用帐户进行鉴权以获取OAuth令牌。使用callback异步回调。 -验证用户凭据,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[auth](#auth9)替代。 +> +> 从 API version 8开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ----- | ----------------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,返回验证结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------- | ---- | --------------- | +| name | string | 是 | 要鉴权的应用帐号名称。 | +| owner | string | 是 | 要鉴权的应用帐号所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| options | {[key: string]: any} | 是 | 鉴权所需的可选项。 | +| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 回调函数。返回鉴权结果对象。 | **示例:** ```js - const appAccountManager = account_appAccount.createAppAccountManager(); - try { - 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'; + + 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)); }); - } catch (err) { - console.log("verifyCredential err: " + JSON.stringify(err)); } + + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.authenticate("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", {}, { + onResult: onResultCallback, + onRequestRedirected: onRequestRedirectedCallback + }); ``` -### verifyCredential9+ +### getOAuthToken(deprecated) -verifyCredential(name: string, owner: string, options: VerifyCredentialOptions, callback: AuthenticatorCallback): void; +getOAuthToken(name: string, owner: string, authType: string, callback: AsyncCallback<string>): void -验证用户凭据,使用callback回调异步返回结果。 +获取指定应用帐号和鉴权类型的OAuth令牌。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAuthToken](#getauthtoken9)替代。 +> +> 从 API version 8开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ----------------------- | ----- | ----------------------- | -| name | string | 是 | 应用帐户的名称。 | -| owner | string | 是 | 应用帐户的所有者。 | -| options | [VerifyCredentialOptions](#verifycredentialoptions9) | 是 | 验证凭据的选项。 | -| callback | [AuthenticatorCallback](#authenticatorcallbackdeprecated) | 是 | 认证器回调,返回验证结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | --------------------------- | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| callback | AsyncCallback<string> | 是 | 回调函数。当获取指定应用帐号和鉴权类型的Auth令牌成功时,err为undefined,data返回Auth令牌对象;否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - credentialType: "pin", - credential: "123456" - }; - try { - 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)); - } - }); - } catch (err) { - console.log("verifyCredential err: " + JSON.stringify(err)); - } + appAccountManager.getOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", (err, data) => { + console.log('getOAuthToken err: ' + JSON.stringify(err)); + console.log('getOAuthToken token: ' + data); + }); ``` -### setAuthenticatorProperties9+ +### getOAuthToken(deprecated) -setAuthenticatorProperties(owner: string, callback: AuthCallback): void; +getOAuthToken(name: string, owner: string, authType: string): Promise<string> + +获取指定应用帐户和鉴权类型的OAuth令牌。使用Promise异步回调。 -设置认证器属性,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[getAuthToken](#getauthtoken9-1)替代。 +> +> 从 API version 8开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ----- | ----------------------- | -| owner | string | 是 | 认证器的所有者。 | -| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,返回设置结果。 | - -**示例:** +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | + +**返回值:** + +| 类型 | 说明 | +| --------------------- | --------------------- | +| Promise<string> | Promise对象。返回指定应用帐户和鉴权类型的OAuth令牌对象。 | + +**示例:** + + ```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)); + }); + ``` + +### setOAuthToken(deprecated) + +setOAuthToken(name: string, authType: string, token: string, callback: AsyncCallback<void>): void + +设置指定应用帐号和鉴权类型的OAuth令牌。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | -------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | OAuth令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定应用帐号和鉴权类型的OAuth令牌成功时,err为undefined;否则为错误对象。 | + +**示例:** + + ```js + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthToken("LiSi", "getSocialData", "xxxx", (err) => { + console.log('setOAuthToken err: ' + JSON.stringify(err)); + }); + ``` + +### setOAuthToken(deprecated) + +setOAuthToken(name: string, authType: string, token: string): Promise<void> + +设置指定应用帐户和鉴权类型的OAuth令牌。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | -------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | OAuth令牌。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | --------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**示例:** + + ```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)); + }); + ``` + +### deleteOAuthToken(deprecated) + +deleteOAuthToken(name: string, owner: string, authType: string, token: string, callback: AsyncCallback<void>): void + +删除指定应用帐户和鉴权类型的OAuth令牌。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[deleteAuthToken](#deleteauthtoken9)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------- | ---- | ------------ | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | 要删除的OAuth令牌。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当删除指定应用帐户和鉴权类型的OAuth令牌成功时,err为undefined;否则为错误对象。 | + +**示例:** + + ```js + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.deleteOAuthToken("LiSi", "com.example.ohos.accountjsdemo", "getSocialData", "xxxxx", (err) => { + console.log('deleteOAuthToken err: ' + JSON.stringify(err)); + }); + ``` + +### deleteOAuthToken(deprecated) + +deleteOAuthToken(name: string, owner: string, authType: string, token: string): Promise<void> + +删除指定应用帐户和鉴权类型的OAuth令牌。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[setAuthToken](#setauthtoken9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------ | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| authType | string | 是 | 鉴权类型。 | +| token | string | 是 | 要删除的OAuth令牌。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | --------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**示例:** + + ```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)); + }); + ``` + +### setOAuthTokenVisibility(deprecated) + +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean, callback: AsyncCallback<void>): void + +设置指定鉴权类型的Auth令牌对特定应用的可见性。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[setAuthTokenVisibility](#setauthtokenvisibility9)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ------------------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 被设置可见性的应用包名。 | +| isVisible | boolean | 是 | 是否可见。当设置成true可见,false不可见。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当设置指定鉴权类型的Auth令牌对特定应用的可见性成功时,err为undefined;否则为错误对象。 | + +**示例:** + + ```js + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.setOAuthTokenVisibility("LiSi", "getSocialData", "com.example.ohos.accountjsdemo", true, (err) => { + console.log('setOAuthTokenVisibility err: ' + JSON.stringify(err)); + }); + ``` + +### setOAuthTokenVisibility(deprecated) + +setOAuthTokenVisibility(name: string, authType: string, bundleName: string, isVisible: boolean): Promise<void> + +设置指定鉴权类型的OAuth令牌对特定应用的可见性。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[setAuthTokenVisibility](#setauthtokenvisibility9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------- | ---- | ------------ | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 被设置可见性的应用包名。 | +| isVisible | boolean | 是 | 是否可见。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | --------------------- | +| Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**示例:** + + ```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)); + }); + ``` + +### checkOAuthTokenVisibility(deprecated) + +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string, callback: AsyncCallback<boolean>): void + +检查指定鉴权类型的OAuth令牌对特定应用的可见性。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[checkAuthTokenVisibility](#checkauthtokenvisibility9)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ---------------------------- | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 检查可见性的应用包名。 | +| callback | AsyncCallback<boolean> | 是 | 回调函数。检查指定鉴权类型的OAuth令牌对特定应用的可见性时,err为undefined,data为true表示可见,data为false表示不可见;否则为错误对象。 | + +**示例:** + + ```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); + }); + ``` + +### checkOAuthTokenVisibility(deprecated) + +checkOAuthTokenVisibility(name: string, authType: string, bundleName: string): Promise<boolean> + +检查指定鉴权类型的OAuth令牌对特定应用的可见性。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[checkAuthTokenVisibility](#checkauthtokenvisibility9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------ | ---- | ------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 鉴权类型。 | +| bundleName | string | 是 | 用于检查可见性的应用包名。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------- | --------------------- | +| Promise<boolean> | Promise对象。返回true表示指定鉴权类型的OAuth令牌对特定应用的可见,返回false表示不可见。 | + +**示例:** + + ```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)); + }); + ``` + +### getAllOAuthTokens(deprecated) + +getAllOAuthTokens(name: string, owner: string, callback: AsyncCallback<Array<OAuthTokenInfo>>): void + +获取指定应用对调用方全部可见的OAuth令牌。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAllAuthTokens](#getallauthtokens9)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | +| callback | AsyncCallback<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | 是 | 回调函数。当获取指定应用对调用方全部可见的OAuth令牌成功时,err为undefined,data为全部可见的OAuth令牌数组;否则为错误对象。 | + +**示例:** + + ```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)); + }); + ``` + +### getAllOAuthTokens(deprecated) + +getAllOAuthTokens(name: string, owner: string): Promise<Array<OAuthTokenInfo>> + +获取指定应用帐户对调用方可见的全部OAuth令牌。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAllAuthTokens](#getallauthtokens9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------- | +| name | string | 是 | 应用帐号的名称。 | +| owner | string | 是 | 应用帐号的所有者包名。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------- | --------------------- | +| Promise<Array< [OAuthTokenInfo](#oauthtokeninfodeprecated)>> | Promise对象。返回指定应用帐户对调用方可见的全部OAuth令牌对象。 | + +**示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - try { - 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)); - } + 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)); + }); + ``` + +### getOAuthList(deprecated) + +getOAuthList(name: string, authType: string, callback: AsyncCallback<Array<string>>): void + +获取指定应用帐户和鉴权类型的OAuth令牌的授权列表。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAuthList](#getauthlist9)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ---------------------------------------- | ---- | ----------------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 应用帐号的鉴权类型的OAuth令牌的授权列表。 | +| callback | AsyncCallback<Array<string>> | 是 | 回调函数。当获取指定应用帐户和鉴权类型的OAuth令牌的授权列表成功时,err为undefined,data为OAuth令牌的授权列表;否则为错误对象。 | + +**示例:** + + ```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)); + }); + ``` + +### getOAuthList(deprecated) + +getOAuthList(name: string, authType: string): Promise<Array<string>> + +获取指定应用帐户和鉴权类型的OAuth令牌的授权列表。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAuthList](#getauthlist9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ----------------------- | +| name | string | 是 | 应用帐号的名称。 | +| authType | string | 是 | 应用帐号的鉴权类型的OAuth令牌的授权列表。 | + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------- | --------------------- | +| Promise<Array<string>> | Promise对象。返回指定应用帐户和鉴权类型的OAuth令牌的授权列表对象。 | + +**示例:** + + ```js + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getOAuthList("com.example.ohos.accountjsdemo", "getSocialData").then((data) => { + console.log('getOAuthList data: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getOAuthList err: " + JSON.stringify(err)); + }); + ``` + +### getAuthenticatorCallback(deprecated) + +getAuthenticatorCallback(sessionId: string, callback: AsyncCallback<AuthenticatorCallback>): void + +获取鉴权会话的认证器回调。使用callback异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAuthCallback](#getauthcallback9)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ---------------------------------------- | ---- | -------- | +| sessionId | string | 是 | 鉴权会话的标识。 | +| callback | AsyncCallback<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | 是 | 回调函数。当获取鉴权会话的认证器回调函数成功时,err为undefined,data为认证器回调函数;否则为错误对象。 | + +**示例:** + + ```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); + }); + }); + ``` + +### getAuthenticatorCallback(deprecated) + +getAuthenticatorCallback(sessionId: string): Promise<AuthenticatorCallback> + +获取鉴权会话的认证器回调。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[getAuthCallback](#getauthcallback9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | ------ | ---- | -------- | +| sessionId | string | 是 | 鉴权会话的标识。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------ | --------------------- | +| Promise<[AuthenticatorCallback](#authenticatorcallbackdeprecated)> | Promise对象。返回鉴权会话的认证器回调对象。 | + +**示例:** + + ```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)); }); - } catch (err) { - console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); - } + }).catch((err) => { + console.log("getWant err: " + JSON.stringify(err)); + }); ``` -### setAuthenticatorProperties9+ +### getAuthenticatorInfo(deprecated) -setAuthenticatorProperties(owner: string, options: SetPropertiesOptions, callback: AuthCallback): void; +getAuthenticatorInfo(owner: string, callback: AsyncCallback<AuthenticatorInfo>): void + +获取指定应用帐号的认证器信息。使用callback异步回调。 -设置认证器属性,使用callback回调异步返回结果。 +> **说明:** 从API version 9开始废弃, 建议使用[queryAuthenticatorInfo](#queryauthenticatorinfo9)替代。 +> +> 从 API version 8开始支持。 **系统能力:** SystemCapability.Account.AppAccount **参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | --------------------- | ----- | ----------------------- | -| owner | string | 是 | 认证器的所有者。 | -| options | [SetPropertiesOptions](#setpropertiesoptions9) | 是 | 设置属性的选项。 | -| callback | [AuthCallback](#authcallback9) | 是 | 认证器回调,返回设置结果。 | +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------- | ---- | ----------- | +| owner | string | 是 | 应用帐号的所有者包名。 | +| callback | AsyncCallback<[AuthenticatorInfo](#authenticatorinfo8)> | 是 | 回调函数。当获取指定应用帐号的认证器信息成功时,err为undefined,data为认证器信息对象;否则为错误对象。 | **示例:** ```js const appAccountManager = account_appAccount.createAppAccountManager(); - var options = { - properties: {"prop1": "value1"} - }; - try { - 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)); - } - }); - } catch (err) { - console.log("setAuthenticatorProperties err: " + JSON.stringify(err)); - } + appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo", (err, data) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + console.log('getAuthenticatorInfo data: ' + JSON.stringify(data)); + }); + ``` + +### getAuthenticatorInfo(deprecated) + +getAuthenticatorInfo(owner: string): Promise<AuthenticatorInfo> + +获取指定应用帐户的认证器信息。使用Promise异步回调。 + +> **说明:** 从API version 9开始废弃, 建议使用[queryAuthenticatorInfo](#queryauthenticatorinfo9-1)替代。 +> +> 从 API version 8开始支持。 + +**系统能力:** SystemCapability.Account.AppAccount + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------ | ---- | ----------- | +| owner | string | 是 | 应用帐号的所有者包名。 | + +**返回值:** + +| 类型 | 说明 | +| -------------------------------- | --------------------- | +| Promise<[AuthenticatorInfo](#authenticatorinfo8)> | Promise对象。返回指定应用帐户的认证器信息对象。 | + +**示例:** + ```js + const appAccountManager = account_appAccount.createAppAccountManager(); + appAccountManager.getAuthenticatorInfo("com.example.ohos.accountjsdemo").then((data) => { + console.log('getAuthenticatorInfo: ' + JSON.stringify(data)); + }).catch((err) => { + console.log("getAuthenticatorInfo err: " + JSON.stringify(err)); + }); ``` ## AppAccountInfo diff --git a/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md b/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md index f9a869d66f263dc29bb2e10cbf488785f5375f66..ea67b7e858460f02207609e1b16c42d33475b878 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-application-AccessibilityExtensionAbility.md @@ -2,7 +2,7 @@ **AccessibilityExtensionAbility**基于ExtensionAbility框架,提供辅助功能业务的能力。 ->**说明:** +>![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > >本模块首批接口从API version 9开始支持,后续版本的新增接口,采用上角标单独标记接口的起始版本。 > @@ -32,36 +32,10 @@ import AccessibilityExtensionAbility from '@ohos.application.AccessibilityExtens | 名称 | 参数类型 | 可读 | 可写 | 说明 | | --------- | ---------------------------------------- | ---- | ---- | ---------- | -| eventType | [EventType](js-apis-accessibility.md#EventType) \| [WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](touchguidetype) \| [GestureType](gesturetype) \| [PageUpdateType](pageupdatetype) | 是 | 否 | 具体事件类型。 | +| eventType | [EventType](js-apis-accessibility.md#EventType) \| [WindowUpdateType](js-apis-accessibility.md#WindowUpdateType) \| [TouchGuideType](#touchguidetype) \| [GestureType](#gesturetype) \| [PageUpdateType](#pageupdatetype) | 是 | 否 | 具体事件类型。 | | target | AccessibilityElement | 是 | 否 | 发生事件的目标组件。 | | timeStamp | number | 是 | 否 | 事件时间戳。 | -## GesturePath - -表示手势路径信息。 - -**系统能力**:以下各项对应的系统能力均为 SystemCapability.BarrierFree.Accessibility.Core - -### 属性 - -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| ------------ | ---------------------------------------- | ---- | ---- | ------ | -| points | Array<[GesturePoint](gesturepoint)> | 是 | 是 | 手势。 | -| durationTime | number | 是 | 是 | 手势总耗时。 | - -## GesturePoint - -表示手势触摸点。 - -**系统能力**:以下各项对应的系统能力均为 SystemCapability.BarrierFree.Accessibility.Core - -### 属性 - -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| --------- | ------ | ---- | ---- | ------- | -| positionX | number | 是 | 是 | 触摸点X坐标。 | -| positionY | number | 是 | 是 | 触摸点Y坐标。 | - ## GestureType 手势事件类型。 @@ -117,16 +91,12 @@ onConnect(): void; **系统能力:** SystemCapability.BarrierFree.Accessibility.Core -**参数:** - -无 - **示例:** ```ts onConnect(): void { console.log("AxExtensionAbility onConnect"); -} +}; ``` ## AccessibilityExtensionAbility.onDisconnect @@ -137,16 +107,12 @@ onDisconnect(): void; **系统能力:** SystemCapability.BarrierFree.Accessibility.Core -**参数:** - -无 - **示例:** ```ts onDisconnect(): void { console.log("AxExtensionAbility onDisconnect"); -} +}; ``` ## AccessibilityExtensionAbility.onAccessibilityEvent @@ -171,7 +137,7 @@ onAccessibilityEvent(event: AccessibilityEvent): void { if (event.eventType == 'click') { console.log("AxExtensionAbility onAccessibilityEvent: click"); } -} +}; ``` ## AccessibilityExtensionAbility.onKeyEvent @@ -198,5 +164,5 @@ onKeyEvent(keyEvent: inputEventClient.KeyEvent): boolean { return true; } return false; -} +}; ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-audio.md b/zh-cn/application-dev/reference/apis/js-apis-audio.md index 79113c8c43330044a1074a869c63ca1a36c08238..87476515907d9b6432f8bb0fd78864a22a8fb646 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-audio.md +++ b/zh-cn/application-dev/reference/apis/js-apis-audio.md @@ -1,6 +1,6 @@ # 音频管理 -音频管理提供管理音频的一些基础能力,包括对音频音量、音频设备的管理,以及对音频数据的采集和渲染等。 +音频管理提供管理音频的一些基础能力,包括对音频音量、音频设备的管理,以及对音频数据的采集和渲染等。 该模块提供以下音频相关的常用功能: @@ -687,6 +687,16 @@ async function createTonePlayer(){ | volumeGroupId9+ | number | 是 | 音量组id。可用于getGroupManager入参 | | networkId9+ | string | 是 | 网络id。 | +## MicStateChangeEvent9+ + +麦克风状态变化时,应用接收的事件。 + +**系统能力:** 以下各项对应的系统能力均为SystemCapability.Multimedia.Audio.Device + +| 名称 | 类型 | 必填 | 说明 | +| ---------- | ----------------------------------- | ---- | -------------------------------------------------------- | +| mute | boolean | 是 | 回调返回系统麦克风静音状态,true为静音,false为非静音。 | + ## ConnectType9+ 枚举,设备连接类型。 @@ -3263,6 +3273,32 @@ async function getRoutingManager(){ } ``` +### on('micStateChange')9+ + +on(type: 'micStateChange', callback: Callback<MicStateChangeEvent>): void + +监听系统麦克风状态更改事件 + +目前此订阅接口在单进程多AudioManager实例的使用场景下,仅最后一个实例的订阅生效,其他实例的订阅会被覆盖(即使最后一个实例没有进行订阅),因此推荐使用单一AudioManager实例进行开发。 + +**系统能力:** SystemCapability.Multimedia.Audio.Device + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------------------------------------- | ---- | ------------------------------------------------------------ | +| type | string | 是 | 事件回调类型,支持的事件为:'micStateChange'(系统麦克风状态变化事件,检测到系统麦克风状态改变时,触发该事件)。 | +| callback | Callback<[MicStateChangeEvent](#micstatechangeevent9)> | 是 | 回调方法,返回变更后的麦克风状态。 | + +**示例:** + +```js +var audioManager = audio.getAudioManager(); +audioManager.getRoutingManager.on('micStateChange', (micStateChange) => { + console.info(`Current microphone status is: ${micStateChange.mute} `); +}); +``` + ### selectInputDevice9+ selectInputDevice(inputAudioDevices: AudioDeviceDescriptors): Promise<void> @@ -5253,7 +5289,7 @@ load(type: ToneType, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | :--------------| :-------------------------- | :-----| :------------------------------ | | type | ToneType(#tonetype9) | 是 | 配置的音调类型。 | -| callback | AsyncCallback | 是 | 使用callback方式异步返回缓冲区。 | +| callback | AsyncCallback | 是 | 使用callback方式异步返回结果。 | **示例:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md index eacc955069bb833d0aca75099f828ccc1842cd63..59ee4c1d6948e357bc8b75df713466d53e089742 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-backgroundTaskManager.md @@ -8,7 +8,7 @@ 应用中存在用户能够直观感受到的且需要一直在后台运行的业务时(如,后台播放音乐),可以使用长时任务机制。 -对于系统特权应用,提供独立的能效资源申请接口。系统特权应用如果需要使用特定的系统资源,例如在被挂起期间仍然能够收到系统公共事件,可以使用能效资源申请接口。 +对于系统特权应用,提供独立的能效资源申请接口。系统特权应用如果需要使用特定的系统资源,例如需要在被挂起期间仍然能够收到系统公共事件,可以使用能效资源申请接口。 > **说明:** > 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 @@ -27,7 +27,7 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen 后台应用申请延迟挂起。 -延迟挂起时间一般情况下默认值为180000,低电量(依据系统低电量广播)时默认值为60000。 +延迟挂起时间一般情况下默认值为180000毫秒,低电量(依据系统低电量广播)时默认值为60000毫秒。 **系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.TransientTask @@ -49,9 +49,9 @@ requestSuspendDelay(reason: string, callback: Callback<void>): DelaySuspen let delayInfo = backgroundTaskManager.requestSuspendDelay(myReason, () => { console.info("Request suspension delay will time out."); }) - - var id = delayInfo.requestId; - var time = delayInfo.actualDelayTime; + + let id = delayInfo.requestId; + let time = delayInfo.actualDelayTime; console.info("The requestId is: " + id); console.info("The actualDelayTime is: " + time); ``` @@ -68,14 +68,14 @@ getRemainingDelayTime(requestId: number, callback: AsyncCallback<number>): **参数**: | 参数名 | 类型 | 必填 | 说明 | | --------- | --------------------------- | ---- | ---------------------------------------- | -| requestId | number | 是 | 延迟挂起的请求ID。 | +| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | | callback | AsyncCallback<number> | 是 | 指定的callback回调方法。用于返回应用程序进入挂起状态之前的剩余时间,以毫秒为单位。 | **示例**: ```js - let id = 1; - backgroundTaskManager.getRemainingDelayTime(id, (err, res) => { + let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); + backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId, (err, res) => { if(err) { console.log('callback => Operation getRemainingDelayTime failed. Cause: ' + err.code); } else { @@ -96,7 +96,7 @@ getRemainingDelayTime(requestId: number): Promise<number> **参数**: | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------- | -| requestId | number | 是 | 延迟挂起的请求ID。 | +| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | **返回值**: | 类型 | 说明 | @@ -105,8 +105,8 @@ getRemainingDelayTime(requestId: number): Promise<number> **示例**: ```js - let id = 1; - backgroundTaskManager.getRemainingDelayTime(id).then( res => { + let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); + backgroundTaskManager.getRemainingDelayTime(delayInfo.requestId).then( res => { console.log('promise => Operation getRemainingDelayTime succeeded. Data: ' + JSON.stringify(res)); }).catch( err => { console.log('promise => Operation getRemainingDelayTime failed. Cause: ' + err.code); @@ -125,12 +125,12 @@ cancelSuspendDelay(requestId: number): void **参数**: | 参数名 | 类型 | 必填 | 说明 | | --------- | ------ | ---- | ---------- | -| requestId | number | 是 | 延迟挂起的请求ID。 | +| requestId | number | 是 | 延迟挂起的请求ID。这个值通过调用[requestSuspendDelay](#backgroundtaskmanagerrequestsuspenddelay)方法获取。 | **示例**: ```js - let id = 1; - backgroundTaskManager.cancelSuspendDelay(id); + let delayInfo = backgroundTaskManager.requestSuspendDelay("test", () => {}); + backgroundTaskManager.cancelSuspendDelay(delayInfo.requestId); ``` @@ -153,6 +153,9 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | **示例**: + +FA模型示例: + ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; @@ -180,11 +183,48 @@ let wantAgentInfo = { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj, callback) + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) }); ``` +Stage模型示例: + +```ts +import Ability from '@ohos.application.Ability' +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import wantAgent from '@ohos.wantAgent'; + +function callback(err, data) { + if (err) { + console.error("Operation startBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation startBackgroundRunning succeeded"); + } +} + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj, callback) + }); + } +}; +``` + ## backgroundTaskManager.startBackgroundRunning8+ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: WantAgent): Promise<void> @@ -209,6 +249,9 @@ startBackgroundRunning(context: Context, bgMode: BackgroundMode, wantAgent: Want | Promise\ | 使用Promise形式返回结果。 | **示例**: + +FA模型示例: + ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; @@ -228,13 +271,45 @@ let wantAgentInfo = { wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { backgroundTaskManager.startBackgroundRunning(featureAbility.getContext(), - backgroundTaskManager.BackgroundMode.DATA_TRANSFER, wantAgentObj).then(() => { + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { console.info("Operation startBackgroundRunning succeeded"); }).catch((err) => { console.error("Operation startBackgroundRunning failed Cause: " + err); }); }); +``` + +Stage模型示例: + +```ts +import Ability from '@ohos.application.Ability' +import backgroundTaskManager from '@ohos.backgroundTaskManager'; +import wantAgent from '@ohos.wantAgent'; +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + let wantAgentInfo = { + wants: [ + { + bundleName: "com.example.myapplication", + abilityName: "com.example.myapplication.MainAbility" + } + ], + operationType: wantAgent.OperationType.START_ABILITY, + requestCode: 0, + wantAgentFlags: [wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG] + }; + + wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { + backgroundTaskManager.startBackgroundRunning(this.context, + backgroundTaskManager.BackgroundMode.LOCATION, wantAgentObj).then(() => { + console.info("Operation startBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation startBackgroundRunning failed Cause: " + err); + }); + }); + } +}; ``` ## backgroundTaskManager.stopBackgroundRunning8+ @@ -252,6 +327,9 @@ stopBackgroundRunning(context: Context, callback: AsyncCallback<void>): vo | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果。 | **示例**: + +FA模型示例: + ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; @@ -268,6 +346,27 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext(), callbac ``` +Stage模型示例: + +```ts +import Ability from '@ohos.application.Ability' +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +function callback(err, data) { + if (err) { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + } else { + console.info("Operation stopBackgroundRunning succeeded"); + } +} + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + backgroundTaskManager.stopBackgroundRunning(this.context, callback); + } +}; +``` + ## backgroundTaskManager.stopBackgroundRunning8+ stopBackgroundRunning(context: Context): Promise<void> @@ -287,6 +386,9 @@ stopBackgroundRunning(context: Context): Promise<void> | Promise\ | 使用Promise形式返回结果。 | **示例**: + +FA模型示例: + ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; import featureAbility from '@ohos.ability.featureAbility'; @@ -299,11 +401,30 @@ backgroundTaskManager.stopBackgroundRunning(featureAbility.getContext()).then(() ``` +Stage模型示例: + +```ts +import Ability from '@ohos.application.Ability' +import backgroundTaskManager from '@ohos.backgroundTaskManager'; + +export default class MainAbility extends Ability { + onCreate(want, launchParam) { + backgroundTaskManager.stopBackgroundRunning(this.context).then(() => { + console.info("Operation stopBackgroundRunning succeeded"); + }).catch((err) => { + console.error("Operation stopBackgroundRunning failed Cause: " + err); + }); + } +}; +``` + ## backgroundTaskManager.applyEfficiencyResources9+ applyEfficiencyResources(request: [EfficiencyResourcesRequest](#efficiencyresourcesrequest9)): boolean -向系统申请能效资源,使用boolean形式返回结果。 +向系统申请或释放能效资源,使用boolean形式返回结果。 +通过EfficiencyResourcesRequest参数中的isApply变量,设置是申请还是释放。 +应用使用此接口,需要向应用中心申请获得相应特权。 进程和它所属的应用可以同时申请某一类资源,例如CPU资源,但是应用释放资源的时候会将进程的资源一起释放。 **系统能力**: SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply @@ -328,6 +449,7 @@ import backgroundTaskManager from '@ohos.backgroundTaskManager'; let request = { resourceTypes: backgroundTaskManager.ResourceType.CPU, + // 如果将isApply置为false,则表示释放资源 isApply: true, timeOut: 0, reason: "apply", @@ -343,6 +465,7 @@ console.info("result of applyEfficiencyResources is: " + res) resetAllEfficiencyResources(): void 释放所有已经申请的资源。 +应用使用此接口,需要向应用中心申请获得相应特权。 **系统能力:** SystemCapability.ResourceSchedule.BackgroundTaskManager.EfficiencyResourcesApply @@ -353,7 +476,7 @@ resetAllEfficiencyResources(): void ```js import backgroundTaskManager from '@ohos.backgroundTaskManager'; -backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); +backgroundTaskManager.resetAllEfficiencyResources(); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md index 2d778e03977a44ad74f4ce890218492a6296d4f5..a8422df7d701782aa7e9e492601f66bbc13b4639 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ElementName.md @@ -7,7 +7,9 @@ ElementName信息,通过接口[Context.getElementName](js-apis-Context.md)获取。 -## ElementName +## ElementName(deprecated) + +> 从API version 9开始不再维护,建议使用[ElementName](js-apis-bundleManager-elementName.md)替代。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md index 3072cd0b3855380720e646a73c9cfb0aeb9e38fc..e5460e4565189b78098c79ff7eaaf4820ecdd65d 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-ShortcutInfo.md @@ -1,6 +1,6 @@ -# ShortcutInfo - +# ShortcutInfo(deprecated) +> 从API version 9开始不再维护,建议使用[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md)替代 > **说明:** > @@ -12,9 +12,9 @@ -## ShortcutWant +## ShortcutWant(deprecated) -快捷方式所指向的目标信息。 +> 从API version 9开始不再维护,建议使用[ShortcutWant](js-apis-bundleManager-shortcutInfo.md)替代 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework @@ -26,9 +26,10 @@ | targetModule9+ | string | 是 | 否 | 快捷方式的目标模块 | | targetClass | string | 是 | 否 | 快捷方式所需的目标类 | -## ShortcutInfo +## ShortcutInfo(deprecated) + +> 从API version 9开始不再维护,建议使用[ShortcutInfo](js-apis-bundleManager-shortcutInfo.md)替代。 -快捷方式属性信息。 **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.BundleFramework diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md index 5780790fed9c45955d326b23850800ff9227a0f8..690b6415c2ddd04ef1932bfc60aa4381d6574447 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md +++ b/zh-cn/application-dev/reference/apis/js-apis-bundle-remoteAbilityInfo.md @@ -9,7 +9,10 @@ 包含基本远程能力信息 -## RemoteAbilityInfo +## RemoteAbilityInfo(deprecated) + +> 从API version 9开始不再维护,建议使用[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)替代。 + **系统能力:** 以下各项对应的系统能力均为SystemCapability.BundleManager.DistributedBundleFramework diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-elementName.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-elementName.md new file mode 100644 index 0000000000000000000000000000000000000000..7c8e9520a08430cc709a9731c16f72dc7b8412c2 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-elementName.md @@ -0,0 +1,19 @@ +# ElementName + +ElementName信息,通过接口[Context.getElementName](js-apis-Context.md)获取。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +## ElementName + + **系统能力:** SystemCapability.BundleManager.BundleFramework + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------------------- | ---------| ---- | ---- | ------------------------- | +| deviceId | string | 是 | 是 | 设备id。 | +| bundleName | string | 是 | 是 | 应用包名。 | +| abilityName | string | 是 | 是 | Ability名称。 | +| uri | string | 是 | 是 | 资源标识符。 | +| shortName | string | 是 | 是 | Ability短名称。 | +| moduleName | string | 是 | 是 | Ability所属的HAP包的模块名称。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..2ddcaff30332d16ef4cdba1e950a2ed3132a5f1d --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-remoteAbilityInfo.md @@ -0,0 +1,20 @@ +# RemoteAbilityInfo + +包含远程的ability信息,通过接口[distributedBundle.getRemoteAbilityInfo](js-apis-distributedBundle.md)获取。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +本模块接口为系统接口。 + +## RemoteAbilityInfo + + **系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + + **系统接口:** 此接口为系统接口。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------- | -------------------------------------------- | ---- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | 是 | 否 | 指明远程ability的ElementName信息 | +| label | string | 是 | 否 | 指明远程ability的标签信息 | +| icon | string | 是 | 否 | 指明的远程ability的图标信息 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md new file mode 100644 index 0000000000000000000000000000000000000000..64632e0107e5766cac4eab9ca44e0b8344c0365f --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-bundleManager-shortcutInfo.md @@ -0,0 +1,38 @@ +# ShortcutInfo + +应用配置文件中定义的快捷方式信息,FA模型配置在[config.json](../../quick-start/package-structure.md)文件中进行配置,Stage模型配置参考[shortcuts对象内部结构](../../quick-start/stage-structure.md#shortcuts对象内部结构) + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +本模块接口为系统接口。 + +## ShortcutWant + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + +**系统接口:** 此接口为系统接口。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ------------------------- | ------ | ---- | ---- | -------------------- | +| targetBundle | string | 是 | 否 | 快捷方式的目标bundleName | +| targetModule | string | 是 | 否 | 快捷方式的目标moduleName | +| targetAbility | string | 是 | 否 | 快捷方式所需的目标abilityName | + +## ShortcutInfo + +**系统能力:** SystemCapability.BundleManager.BundleFramework.Launcher + + **系统接口:** 此接口为系统接口。 + +| 名称 | 类型 | 可读 | 可写 | 说明 | +| ----------------------- | ------------------------------------------ | ---- | ---- | ---------------------------- | +| id | string | 是 | 否 | 快捷方式所属应用程序的Id | +| bundleName | string | 是 | 否 | 包含快捷方式的包名称 | +| moduleName | string | 是 | 否 | 快捷方式的模块名 | +| hostAbility | string | 是 | 否 | 快捷方式的本地Ability名称 | +| icon | string | 是 | 否 | 快捷方式的图标 | +| iconId | number | 是 | 否 | 快捷方式的图标Id | +| label | string | 是 | 否 | 快捷方式的标签 | +| labelId | number | 是 | 否 | 快捷方式的标签Id | +| wants | Array\<[ShortcutWant](#shortcutwant)> | 是 | 否 | 快捷方式所需要的信息 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-camera.md b/zh-cn/application-dev/reference/apis/js-apis-camera.md index 1f7ab803f4c4d48b2cefcfa7874461b553f02cd5..1d7ecedb9bf69cf520049f33f1a3bfd780c1243b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-camera.md +++ b/zh-cn/application-dev/reference/apis/js-apis-camera.md @@ -89,6 +89,17 @@ camera.getCameraManager(context).then((cameraManager) => { | format | [CameraFormat](#cameraformat) | 是 | 输出格式。 | | size | [Size](#size) | 是 | 分辨率。 | +## FrameRateRange + +帧率范围。 + +**系统能力:** SystemCapability.Multimedia.Camera.Core + +| 名称 | 类型 | 只读 | 说明 | +| -------- | ----------------------------- |---- | ------------- | +| min | number | 是 | 最小帧率。 | +| max | number | 是 | 最大帧率。 | + ## VideoProfile 视频配置信息项。 @@ -97,9 +108,7 @@ camera.getCameraManager(context).then((cameraManager) => { | 名称 | 类型 | 只读 | 说明 | | ------------------------- | ----------------------------------------- | --- |----------- | -| format | [CameraFormat](#cameraformat) | 是 | 输出格式。 | -| size | [Size](#size) | 是 | 分辨率。 | -| frameRate | Array | 是 | 帧率。 | +| frameRateRange | [FrameRateRange](#frameraterange) | 是 | 帧率范围。 | ## CameraOutputCapability @@ -169,7 +178,7 @@ cameraManager.getSupportedCameras().then((cameraArray) => { ### getSupportedOutputCapability -getSupportedOutputCapability(callback: AsyncCallback): void +getSupportedOutputCapability(camera:CameraDevice, callback: AsyncCallback): void 查询相机设备在模式下支持的输出能力,通过注册回调函数获取结果。 @@ -177,14 +186,15 @@ getSupportedOutputCapability(callback: AsyncCallback): **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------------------------------- | -- | -------------------------- | -| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | 是 | 使用callback方式获取相机输出能力。 | +| 名称 | 类型 | 必填 | 说明 | +| ------------ |--------------------------------------------------------------- | -- | -------------------------- | +| CameraDevice | [CameraDevice](#cameradevice) | 是 | 相机设备。 | +| callback | AsyncCallback<[CameraOutputCapability](#cameraoutputcapability)\> | 是 | 使用callback方式获取相机输出能力。 | **示例:** ```js -cameraManager.getSupportedOutputCapability((err, cameras) => { +cameraManager.getSupportedOutputCapability(cameradevice, (err, cameras) => { if (err) { console.error(`Failed to get the cameras. ${err.message}`); return; @@ -195,7 +205,7 @@ cameraManager.getSupportedOutputCapability((err, cameras) => { ### getSupportedOutputCapability -getSupportedOutputCapability(): Promise +getSupportedOutputCapability(camera:CameraDevice): Promise 查询相机设备在模式下支持的输出能力,通过Promise获取结果。 @@ -205,7 +215,7 @@ getSupportedOutputCapability(): Promise | 名称 | 类型 | 必填 | 说明 | | -------- | --------------------------------- | ---- | ---------- | -| camera | [CameraDevice](#cameradevice) | 是 | CameraDevice对象。| +| camera | [CameraDevice](#cameradevice) | 是 | 相机设备。 | **返回值:** @@ -217,60 +227,11 @@ getSupportedOutputCapability(): Promise **示例:** ```js -cameraManager.getSupportedOutputCapability().then((cameraoutputcapability) => { +cameraManager.getSupportedOutputCapability(cameradevice).then((cameraoutputcapability) => { console.log('Promise returned with an array of supported outputCapability'); }) ``` -### getSupportedMetadataObjectType - -getSupportedMetadataObjectType(callback: AsyncCallback\>): void - -查询相机设备支持的元能力信息,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------------------------------------- | -- | -------------------------- | -| callback | AsyncCallback\> | 是 | 使用callback方式获取相机支持的元能力力信息。 | - -**示例:** - -```js -cameraManager.getSupportedMetadataObjectType((err, metadataobject) => { - if (err) { - console.error(`Failed to get the supported metadataObjectType. ${err.message}`); - return; - } - console.log('Callback returned with an array of supported metadataObjectType.' ); -}) -``` - -### getSupportedMetadataObjectType - -getSupportedMetadataObjectType(): Promise - -查询相机设备支持的元能力信息,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -| -------------------------------------------------------------- | ----------------------------- | -| Promise\> | 使用Promise的方式获取结果,返回相机支持的元能力信息。 | - - -**示例:** - -```js -cameraManager.getSupportedMetadataObjectType().then((metadataobject) => { - console.log('Promise returned with an array of supported metadataObjectType.' ); -}) -``` - ### createCameraInput createCameraInput(camera: CameraDevice, callback: AsyncCallback): void @@ -456,63 +417,6 @@ cameraManager.createPreviewOutput(profile, surfaceId).then((previewoutput) => { }) ``` -### createDeferredPreviewOutput - -createDeferredPreviewOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void - -尚未获取surfaceID时创建预览输出对象,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------- | ---- | --------------------------------- | -| profile | [Profile](#profile) | 是 | 支持的预览配置信息。 | -| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)或者[ImageReceiver](js-apis-image.md#imagereceiver9)组件获取的SurfaceID。 | -| callback | AsyncCallback<[PreviewOutput](#previewoutput)\> | 是 | 回调函数,用于获取PreviewOutput实例。 | - -**示例:** - -```js -cameraManager.createDeferredPreviewOutput(profile, surfaceId, (err, previewoutput) => { - if (err) { - console.error(`Failed to create deferredPreviewOutput. ${err.message}`); - return; - } - console.log('Callback returned with deferredPreviewOutput created.'); -}) -``` - -### createDeferredPreviewOutput - -createDeferredPreviewOutput(profile: Profile, surfaceId: string): Promise - -尚未获取surfaceID时创建预览输出对象,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ---------------------------------| ---- | ---------- | -| profile | [Profile](#profile) | 是 | 支持的预览配置信息。 | -| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)或者[ImageReceiver](js-apis-image.md#imagereceiver9)组件获取的SurfaceID。 | - -**返回值:** - -| 类型 | 说明 | -| ----------------------------------------- | --------------------------------------- | -| Promise<[PreviewOutput](#previewoutput)\> | 使用Promise的方式获取PreviewOutput的实例。 | - -**示例:** - -```js -cameraManager.createDeferredPreviewOutput(profile, surfaceId).then((previewoutput) => { - console.log('Promise returned with DefeerredPreviewOutput created.'); -}) -``` - ### createPhotoOutput createPhotoOutput(profile: Profile, surfaceId: string, callback: AsyncCallback): void @@ -543,7 +447,7 @@ cameraManager.createPhotoOutput(profile, surfaceId, (err, photooutput) => { ### createPhotoOutput -createPhotoOutput(profile: Profile, surfaceId: string): Promise +createPhotoOutput(profile: Profile, surfaceId: string): Promise 创建拍照输出对象,通过Promise获取结果。 @@ -629,7 +533,7 @@ cameraManager.createVideoOutput(profile, surfaceId).then((videooutput) => { ### createMetadataOutput -createMetadataOutput(callback: AsyncCallback): void +createMetadataOutput(metadataObjectTypes:Array, callback: AsyncCallback): void 创建metadata流输出对象,通过注册回调函数获取结果。 @@ -639,12 +543,13 @@ createMetadataOutput(callback: AsyncCallback): void | 名称 | 类型 | 必填 | 说明 | | -------------------- | -------------------------------------------------- | --- | ---------------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型信息。 | | callback | AsyncCallback<[MetadataOutput](#metadataoutput)\> | 是 | 回调函数,用于获取MetadataOutput实例。 | **示例:** ```js -cameraManager.createMetadataOutput((err, metadataoutput) => { +cameraManager.createMetadataOutput(metadataObjectTypes, (err, metadataoutput) => { if (err) { console.error(`Failed to create metadataOutput. ${err.message}`); return; @@ -655,12 +560,18 @@ cameraManager.createMetadataOutput((err, metadataoutput) => { ### createMetadataOutput -createMetadataOutput(): Promise +createMetadataOutput(metadataObjectTypes:Array): Promise 创建metadata流输出对象,通过Promise获取结果。 **系统能力:** SystemCapability.Multimedia.Camera.Core +**参数:** + +| 名称 | 类型 | 必填 | 说明 | +| -------------------- | -------------------------------------------------- | --- | -------------------- | +| metadataObjectTypes | Array<[MetadataObjectType](#metadataobjecttype)\> | 是 | metadata流类型信息。 | + **返回值:** | 类型 | 说明 | @@ -751,37 +662,6 @@ cameraManager.on('cameraStatus', (err, cameraStatusInfo) => { }) ``` -### on('cameraMute') - -on(type: 'cameraMute', callback: AsyncCallback): void - -监听相机禁用的状态变化,通过注册回调函数获取相机的状态变化。 - -此接口为系统接口。 - -**需要权限:** ohos.permission.CAMERA - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | --------------------------------------- | ---- | ------------------------------- | -| type | string | 是 | 监听事件,固定为'cameraMute',即相机状禁用态变化事件。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取相机是否禁用。 | - -**示例:** - -```js -cameraManager.on('cameraMute', (err, status) => { - if (err) { - console.error(`Failed to get cameraMute callback. ${err.message}`); - return; - } - console.log(`status: ${status}`); -}) -``` - ## CameraStatusInfo 相机管理器回调返回的接口实例,表示相机状态信息。 @@ -888,6 +768,7 @@ async function getCameraInfo("cameraId") { | 名称 | 默认值 | 说明 | | ----------------------- | --------- | ------------ | +| CAMERA_FORMAT_RGBA_8888 | 3 | RGB格式的图片。 | | CAMERA_FORMAT_YUV_420_SP| 1003 | YUV 420 SP格式的图片。 | | CAMERA_FORMAT_JPEG | 2000 | JPEG格式的图片。 | @@ -1041,7 +922,7 @@ cameraInput.release().then(() => { ### on('error') -on(type: 'error', callback: ErrorCallback): void +on(type: 'error', camera:CameraDevice, callback: ErrorCallback): void 监听CameraInput的错误事件,通过注册回调函数获取结果。 @@ -1049,9 +930,10 @@ on(type: 'error', callback: ErrorCallback): void **参数:** -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------------------- | ---- | ------------------------------------------- | +| 名称 | 类型 | 必填 | 说明 | +| -------- | -------------------------------- | --- | ------------------------------------------- | | type | string | 是 | 监听事件,固定为'error',即CameraInput错误事件。 | +| camera | [CameraDevice](#cameradevice) | 是 | CameraDevice对象。 | | callback | ErrorCallback<[CameraInputError](#camerainputerror)\> | 是 | 回调函数,用于获取结果。 | **示例:** @@ -1138,17 +1020,6 @@ cameraInput.on('error', (cameraInputError) => { | FOCUS_STATE_FOCUSED | 1 | 对焦成功。 | | FOCUS_STATE_UNFOCUSED | 2 | 未完成对焦。 | -## ExposureState - -枚举,曝光状态。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core。 - -| 名称 | 值 | 说明 | -| ------------------------- | ---- | -------- | -| EXPOSURE_STATE_SCAN | 0 | 曝光中。 | -| EXPOSURE_STATE_CONVERGED | 1 | 曝光收敛。 | - ## VideoStabilizationMode 枚举,视频防抖模式。 @@ -1264,61 +1135,6 @@ captureSession.commitConfig().then(() => { }) ``` -### canAddInput - -canAddInput(cameraInput: CameraInput, callback: AsyncCallback): void - -判断是否可以添加[CameraInput](#camerainput)到会话中,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | ------------------------ | -| cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -captureSession.canAddInput(cameraInput, (err, status) => { - if (err) { - console.error(`Can not add cameraInput. ${err.message}`); - return; - } - console.log('Callback returned with cameraInput can added.'); -}) -``` - -### canAddInput - -canAddInput(cameraInput: CameraInput): Promise - -判断是否可以添加[CameraInput](#camerainput)到会话中,通过注Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ----------- | --------------------------- | ---- | ------------------------ | -| cameraInput | [CameraInput](#camerainput) | 是 | 需要添加的CameraInput实例。 | - -**返回值:** - -| 类型 | 说明 | -| -------------- | -------------------------- | -| Promise | 使用Promise的方式获取结果。 | - -**示例:** - -```js -captureSession.canAddInput(cameraInput).then(() => { - console.log('Promise returned with cameraInput can added.'); -}) -``` - ### addInput addInput\(cameraInput: CameraInput, callback: AsyncCallback\): void @@ -1429,63 +1245,6 @@ captureSession.removeInput(cameraInput).then(() => { }) ``` -### canAddOutput - -canAddOutput(cameraOutput: CameraOutput, callback: AsyncCallback\): void - -查询是否可以添加[CameraOutput](#cameraoutput)到会话中,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | 是 | 需要添加的CameraOutput实例。 | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -captureSession.canAddOutput(cameraOutput, (err, status) => { - if (err) { - console.error(`Can not add cameraOutput. ${err.message}`); - return; - } - console.log('Callback returned with cameraOutput can added.'); -}) -``` - -### canAddOutput - -canAddOutput(cameraOutput: CameraOutput): Promise - -查询是否可以添加[CameraOutput](#cameraoutput)到会话中,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------------- | ------------------------------- | ---- | ------------------------- | -| cameraOutput | [CameraOutput](#cameraoutput) | 是 | 需要添加的CameraOutput实例。 | - - -**返回值:** - -| 类型 | 说明 | -| -------------- | --------------------------- | -| Promise | 使用Promise的方式获取结果。 | - - -**示例:** - -```js -captureSession.canAddOutput(cameraOutput).then(() => { - console.log('Promise returned with cameraOutput can added.'); -}) -``` - ### addOutput addOutput\(cameraOutput: CameraOutput, callback: AsyncCallback\): void @@ -1694,102 +1453,6 @@ captureSession.stop().then(() => { }) ``` -### lockForControl - -lockForControl(callback: AsyncCallback): void - -请求以独占方式控制设备的硬件属性[CameraInput](#camerainput),需要调用[unlockForControl](#unlockforcontrol),通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------- | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -captureSession.lockForControl((err) => { - if (err) { - console.error(`Failed to lock. ${err.message}`); - return; - } - console.log('Locked.'); -}) -``` - -### lockForControl - -lockForControl(): Promise - -请求以独占方式控制设备的硬件属性[CameraInput](#camerainput),需要调用[unlockForControl](#unlockforcontrol),通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -| -------------- | ------------------------ | -| Promise | 使用Promise的方式获取结果。 | - -**示例:** - -```js -captureSession.lockForControl().then(() => { - console.log('Locked.'); -}) -``` - -### unlockForControl - -unlockForControl(callback: AsyncCallback): void - -控制生效,并放弃对设备配置的排他控制,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------- | -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -captureSession.unlockForControl((err) => { - if (err) { - console.error(`Failed to unlock. ${err.message}`); - return; - } - console.log('Unlocked.'); -}) -``` - -### unlockForControl - -unlockForControl(): Promise - -控制生效,并放弃对设备配置的排他控制,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -| -------------- | ------------------------ | -| Promise | 使用Promise的方式获取结果。 | - -**示例:** - -```js -captureSession.unlockForControl().then(() => { - console.log('Unlocked.'); -}) -``` - ### release release\(callback: AsyncCallback\): void @@ -1855,7 +1518,7 @@ hasFlash(callback: AsyncCallback): void **示例:** ```js -cameraInput.hasFlash((err, status) => { +captureSession.hasFlash((err, status) => { if (err) { console.error(`Failed to check whether the device has flash light. ${err.message}`); return; @@ -1881,7 +1544,7 @@ hasFlash(): Promise **示例:** ```js -cameraInput.hasFlash().then((status) => { +captureSession.hasFlash().then((status) => { console.log(`Promise returned with the flash light support status: ${status}`); }) ``` @@ -1904,7 +1567,7 @@ isFlashModeSupported(flashMode: FlashMode, callback: AsyncCallback): v **示例:** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { +captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO, (err, status) => { if (err) { console.error(`Failed to check whether the flash mode is supported. ${err.message}`); return; @@ -1936,7 +1599,7 @@ isFlashModeSupported(flashMode: FlashMode): Promise **示例:** ```js -cameraInput.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { +captureSession.isFlashModeSupported(camera.FlashMode.FLASH_MODE_AUTO).then((status) => { console.log(`Promise returned with flash mode support status.${status}`); }) ``` @@ -1964,7 +1627,7 @@ setFlashMode(flashMode: FlashMode, callback: AsyncCallback): void **示例:** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { +captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO, (err) => { if (err) { console.error(`Failed to set the flash mode ${err.message}`); return; @@ -2001,7 +1664,7 @@ setFlashMode(flashMode: FlashMode): Promise **示例:** ```js -cameraInput.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { +captureSession.setFlashMode(camera.FlashMode.FLASH_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFlashMode.'); }) ``` @@ -2023,7 +1686,7 @@ getFlashMode(callback: AsyncCallback): void **示例:** ```js -cameraInput.getFlashMode((err, flashMode) => { +captureSession.getFlashMode((err, flashMode) => { if (err) { console.error(`Failed to get the flash mode ${err.message}`); return; @@ -2049,7 +1712,7 @@ getFlashMode(): Promise **示例:** ```js -cameraInput.getFlashMode().then((flashMode) => { +captureSession.getFlashMode().then((flashMode) => { console.log(`Promise returned with current flash mode : ${flashMode}`); }) ``` @@ -2072,7 +1735,7 @@ isExposureModeSupported(aeMode: ExposureMode, callback: AsyncCallback) **示例:** ```js -cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { if (err) { console.log(`Failed to check exposure mode supported ${err.message}`); return ; @@ -2104,7 +1767,7 @@ isExposureModeSupported(aeMode: ExposureMode): Promise **示例:** ```js -cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { console.log(`Promise returned with exposure mode supported : ${isSupported}`); }) ``` @@ -2126,7 +1789,7 @@ getExposureMode(callback: AsyncCallback): void **示例:** ```js -cameraInput.getExposureMode((err, exposureMode) => { +captureSession.getExposureMode((err, exposureMode) => { if (err) { console.log(`Failed to get the exposure mode ${err.message}`); return ; @@ -2152,7 +1815,7 @@ getExposureMode(): Promise **示例:** ```js -cameraInput.getExposureMode().then((exposureMode) => { +captureSession.getExposureMode().then((exposureMode) => { console.log(`Promise returned with current exposure mode : ${exposureMode}`); }) ``` @@ -2175,7 +1838,7 @@ setExposureMode(aeMode: ExposureMode, callback: AsyncCallback): void **示例:** ```js -cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { +captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKEN,(err) => { if (err) { console.log(`Failed to set the exposure mode ${err.message}`); return ; @@ -2201,7 +1864,7 @@ setExposureMode(aeMode: ExposureMode): Promise **示例:** ```js -cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => { +captureSession.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => { console.log('Promise returned with the successful execution of setExposureMode.'); }) ``` @@ -2210,7 +1873,7 @@ cameraInput.setExposureMode(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then(() => getMeteringPoint(callback: AsyncCallback): void -查询曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留) +查询曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留,将在3.2版本开放) **系统能力:** SystemCapability.Multimedia.Camera.Core @@ -2223,7 +1886,7 @@ getMeteringPoint(callback: AsyncCallback): void **示例:** ```js -cameraInput.getMeteringPoint((err, exposurePoint) => { +captureSession.getMeteringPoint((err, exposurePoint) => { if (err) { console.log(`Failed to get the current exposure point ${err.message}`); return ; @@ -2236,7 +1899,7 @@ cameraInput.getMeteringPoint((err, exposurePoint) => { getMeteringPoint(): Promise -查询曝光区域中心点,通过Promise获取结果。(该接口目前为预留) +查询曝光区域中心点,通过Promise获取结果。(该接口目前为预留,将在3.2版本开放) **系统能力:** SystemCapability.Multimedia.Camera.Core @@ -2249,16 +1912,16 @@ getMeteringPoint(): Promise **示例:** ```js -cameraInput.getMeteringPoint().then((exposurePoint) => { +captureSession.getMeteringPoint().then((exposurePoint) => { console.log(`Promise returned with current exposure point : ${exposurePoint}`); }) ``` ### setMeteringPoint -setMeteringPoint(point: Point, callback: AsyncCallback): void +setMeteringPoint(point: Point, callback: AsyncCallback): void -设置曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留) +设置曝光区域中心点,通过注册回调函数获取结果。(该接口目前为预留,将在3.2版本开放) **系统能力:** SystemCapability.Multimedia.Camera.Core @@ -2274,7 +1937,7 @@ setMeteringPoint(point: Point, callback: AsyncCallback): void ```js const Point1 = {x: 1, y: 1}; -cameraInput.setMeteringPoint(Point1,(err) => { +captureSession.setMeteringPoint(Point1,(err) => { if (err) { console.log(`Failed to set the exposure point ${err.message}`); return ; @@ -2287,7 +1950,7 @@ cameraInput.setMeteringPoint(Point1,(err) => { setMeteringPoint(point: Point): Promise -设置曝光区域中心点,通过Promise获取结果。(该接口目前为预留) +设置曝光区域中心点,通过Promise获取结果。(该接口目前为预留,将在3.2版本开放) **系统能力:** SystemCapability.Multimedia.Camera.Core @@ -2308,7 +1971,7 @@ setMeteringPoint(point: Point): Promise ```js const Point2 = {x: 2, y: 2}; -cameraInput.setMeteringPoint(Point2).then(() => { +captureSession.setMeteringPoint(Point2).then(() => { console.log('Promise returned with the successful execution of setMeteringPoint'); }) ``` @@ -2330,7 +1993,7 @@ getExposureBiasRange(callback: AsyncCallback\>): void **示例:** ```js -cameraInput.getExposureBiasRange((err, biasRangeArray) => { +captureSession.getExposureBiasRange((err, biasRangeArray) => { if (err) { console.log(`Failed to get the array of compenstation range ${err.message}`); return ; @@ -2356,7 +2019,7 @@ getExposureBiasRange(): Promise\> **示例:** ```js -cameraInput.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { +captureSession.isExposureModeSupported(camera.ExposureMode.EXPOSURE_MODE_LOCKED).then((isSupported) => { console.log(`Promise returned with exposure mode supported : ${isSupported}`); }) ``` @@ -2381,7 +2044,7 @@ setExposureBias(exposureBias: number, callback: AsyncCallback): void **示例:** ```js -cameraInput.setExposureBias(-4,(err) => { +captureSession.setExposureBias(-4,(err) => { if (err) { console.log(`Failed to set the exposure bias ${err.message}`); return ; @@ -2415,7 +2078,7 @@ setExposureBias(exposureBias: number): Promise **示例:** ```js -cameraInput.setExposureBias(-4).then(() => { +captureSession.setExposureBias(-4).then(() => { console.log('Promise returned with the successful execution of setExposureBias.'); }) ``` @@ -2437,7 +2100,7 @@ getExposureValue(callback: AsyncCallback): void **示例:** ```js -cameraInput.getExposureValue((err, exposureValue) => { +captureSession.getExposureValue((err, exposureValue) => { if (err) { console.log(`Failed to get the exposure value ${err.message}`); return ; @@ -2463,7 +2126,7 @@ getExposureValue(): Promise **示例:** ```js -cameraInput.getExposureValue().then((exposureValue) => { +captureSession.getExposureValue().then((exposureValue) => { console.log(`Promise returned with exposure value: ${exposureValude}`); }) ``` @@ -2486,7 +2149,7 @@ isFocusModeSupported(afMode: FocusMode, callback: AsyncCallback): void **示例:** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { +captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO, (err, status) => { if (err) { console.error(`Failed to check whether the focus mode is supported. ${err.message}`); return; @@ -2518,7 +2181,7 @@ isFocusModeSupported(afMode: FocusMode): Promise **示例:** ```js -cameraInput.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { +captureSession.isFocusModeSupported(camera.FocusMode.FOCUS_MODE_AUTO).then((status) => { console.log(`Promise returned with focus mode support status ${status}.`); }) ``` @@ -2543,7 +2206,7 @@ setFocusMode(afMode: FocusMode, callback: AsyncCallback): void **示例:** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { +captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO, (err) => { if (err) { console.error(`Failed to set the focus mode ${err.message}`); return; @@ -2577,7 +2240,7 @@ setFocusMode(afMode: FocusMode): Promise **示例:** ```js -cameraInput.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { +captureSession.setFocusMode(camera.FocusMode.FOCUS_MODE_AUTO).then(() => { console.log('Promise returned with the successful execution of setFocusMode.'); }) ``` @@ -2599,7 +2262,7 @@ getFocusMode(callback: AsyncCallback): void **示例:** ```js -cameraInput.getFocusMode((err, afMode) => { +captureSession.getFocusMode((err, afMode) => { if (err) { console.error(`Failed to get the focus mode ${err.message}`); return; @@ -2625,7 +2288,7 @@ getFocusMode(): Promise **示例:** ```js -cameraInput.getFocusMode().then((afMode) => { +captureSession.getFocusMode().then((afMode) => { console.log(`Promise returned with current focus mode : ${afMode}`); }) ``` @@ -2650,7 +2313,7 @@ setFocusPoint(point: Point, callback: AsyncCallback): void ```js const Point1 = {x: 1, y: 1}; -cameraInput.setFocusPoint(Point1, (err) => { +captureSession.setFocusPoint(Point1, (err) => { if (err) { console.error(`Failed to set the focus point ${err.message}`); return; @@ -2684,7 +2347,7 @@ setFocusPoint(point: Point): Promise ```js const Point2 = {x: 2, y: 2}; -cameraInput.setFocusPoint(Point2).then(() => { +captureSession.setFocusPoint(Point2).then(() => { console.log('Promise returned with the successful execution of setFocusPoint.'); }) ``` @@ -2706,7 +2369,7 @@ getFocusPoint(callback: AsyncCallback): void **示例:** ```js -cameraInput.getFocusPoint((err, point) => { +captureSession.getFocusPoint((err, point) => { if (err) { console.error(`Failed to get the current focus point ${err.message}`); return; @@ -2732,7 +2395,7 @@ getFocusPoint(): Promise **示例:** ```js -cameraInput.getFocusPoint().then((point) => { +captureSession.getFocusPoint().then((point) => { console.log('Promise returned with the current focus point: ' + JSON.stringify(point)); }) ``` @@ -2754,7 +2417,7 @@ getFocalLength(callback: AsyncCallback): void **示例:** ```js -cameraInput.getFocalLength((err, focalLength) => { +captureSession.getFocalLength((err, focalLength) => { if (err) { console.error(`Failed to get the current focal length ${err.message}`); return; @@ -2780,7 +2443,7 @@ getFocalLength(): Promise **示例:** ```js -cameraInput.getFocalLength().then((focalLength) => { +captureSession.getFocalLength().then((focalLength) => { console.log(`Promise returned with the current focal length: ${focalLength}`); }) ``` @@ -2802,7 +2465,7 @@ getZoomRatioRange\(callback: AsyncCallback\>\): void **示例:** ```js -cameraInput.getZoomRatioRange((err, zoomRatioRange) => { +captureSession.getZoomRatioRange((err, zoomRatioRange) => { if (err) { console.error(`Failed to get the zoom ratio range. ${err.message}`); return; @@ -2828,7 +2491,7 @@ getZoomRatioRange\(\): Promise\> **示例:** ```js -cameraInput.getZoomRatioRange().then((zoomRatioRange) => { +captureSession.getZoomRatioRange().then((zoomRatioRange) => { console.log(`Promise returned with zoom ratio range: ${zoomRatioRange.length}`); }) ``` @@ -2851,7 +2514,7 @@ setZoomRatio(zoomRatio: number, callback: AsyncCallback): void **示例:** ```js -cameraInput.setZoomRatio(1, (err) => { +captureSession.setZoomRatio(1, (err) => { if (err) { console.error(`Failed to set the zoom ratio value ${err.message}`); return; @@ -2883,7 +2546,7 @@ setZoomRatio(zoomRatio: number): Promise **示例:** ```js -cameraInput.setZoomRatio(1).then(() => { +captureSession.setZoomRatio(1).then(() => { console.log('Promise returned with the successful execution of setZoomRatio.'); }) ``` @@ -2905,7 +2568,7 @@ getZoomRatio(callback: AsyncCallback): void **示例:** ```js -cameraInput.getZoomRatio((err, zoomRatio) => { +captureSession.getZoomRatio((err, zoomRatio) => { if (err) { console.error(`Failed to get the zoom ratio ${err.message}`); return; @@ -2931,7 +2594,7 @@ getZoomRatio(): Promise **示例:** ```js -cameraInput.getZoomRatio().then((zoomRatio) => { +captureSession.getZoomRatio().then((zoomRatio) => { console.log(`Promise returned with current zoom ratio : ${zoomRatio}`); }) ``` @@ -3106,34 +2769,11 @@ on(type: 'focusStateChange', callback: AsyncCallback): void **示例:** ```js -cameraInput.on('focusStateChange', (focusState) => { +captureSession.on('focusStateChange', (focusState) => { console.log(`Focus state : ${focusState}`); }) ``` -### on('exposureStateChange') - -on(type: 'exposureStateChange', callback: AsyncCallback): void - -监听曝光的状态变化,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------- | ---- | ---------------------------------------------- | -| type | string | 是 | 监听事件,固定为'exposureStateChange',即曝光状态变化事件。| -| callback | AsyncCallback<[ExposureState](#exposurestate)\> | 是 | 回调函数,用于获取曝光状态。 | - -**示例:** - -```js -cameraInput.on('exposureStateChange', (exposureState) => { - console.log(`Exposuer state : ${exposureState}`); -}) -``` - ### on('error') on(type: 'error', callback: ErrorCallback): void @@ -3200,7 +2840,7 @@ release(callback: AsyncCallback): void **示例:** ```js -previewOutput.release((err) => { +cameraOutput.release((err) => { if (err) { console.error(`Failed to release the PreviewOutput instance ${err.message}`); return; @@ -3226,7 +2866,7 @@ release(): Promise **示例:** ```js -previewOutput.release().then(() => { +cameraOutput.release().then(() => { console.log('Promise returned to indicate that the PreviewOutput instance is released successfully.'); }) ``` @@ -3235,61 +2875,6 @@ previewOutput.release().then(() => { 预览输出类。继承[CameraOutput](#cameraoutput) -### addDeferredSurface - -addDeferredSurface(surfaceId: string, callback: AsyncCallback): void - -在previewOutput生成之后添加surface,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | -------------------------------------------------------------------- | -| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)组件获取的SurfaceID。| -| callback | AsyncCallback | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -previewOutput.addDeferredSurface('surfaceId', (err) => { - if (err) { - console.error(`Failed to add deferredSurface. ${err.message}`); - return; - } - console.log('Callback returned with deferredSurface added.'); -}) -``` - -### addDeferredSurface - -addDeferredSurface(surfaceId: string): Promise - -在previewOutput生成之后添加surface,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -----------| ---- | ------------------------------------------------------------------------------ | -| surfaceId| string | 是 | 从[XComponent](../arkui-ts/ts-basic-components-xcomponent.md)组件获取的SurfaceID。| - -**返回值:** - -| 类型 | 说明 | -| -------------- | ----------------------- | -| Promise | 使用Promise的方式获取结果。 | - -**示例:** - -```js -previewOutput.addDeferredSurface('surfaceId').then(() => { - console.log('Promise returned with deferredSurface added.'); -}) -``` - ### start start(callback: AsyncCallback): void @@ -3524,59 +3109,12 @@ previewOutput.on('error', (previewOutputError) => { | quality | [QualityLevel](#qualitylevel) | 否 | QUALITY_LEVEL_HIGH| 图片质量。 | | rotation | [ImageRotation](#imagerotation) | 否 | ROTATION_0 | 图片旋转角度。 | | location | [Location](#location) | 否 | (0,0,0) | 图片地理位置信息。 | +| mirror | boolean | 否 | false |镜像使能开关(默认关)。 | ## PhotoOutput 拍照会话中使用的输出信息。 -### getDefaultCaptureSetting - -getDefaultCaptureSetting(callback: AsyncCallback): void - -获取默认拍照参数,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | ----------------------------------------------------------- | ---- | -------------------- | -| callback | AsyncCallback<[PhotoCaptureSetting](#photocapturesetting)\> | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -photoOutput.getDefaultCaptureSetting((err, photocapturesetting) => { - if (err) { - console.error(`Failed to get the defaultCaptureSetting. ${err.message}`); - return; - } - console.log('Callback returned with an array of defaultCaptureSetting.'); -}) -``` - -### getDefaultCaptureSetting - -getDefaultCaptureSetting(): Promise - -获取默认拍照参数,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -| ----------------------------------------------------- | ----------------------- | -| Promise<[PhotoCaptureSetting](#photocapturesetting)\> | 使用Promise的方式获取结果。 | - -**示例:** - -```js -photoOutput.getDefaultCaptureSetting().then((photocapturesetting) => { - console.log('Callback returned with an array of defaultCaptureSetting.'); -}) -``` - ### capture capture(callback: AsyncCallback): void @@ -3951,111 +3489,6 @@ videoOutput.stop().then(() => { }) ``` -### getFrameRateRange - -getFrameRateRange(callback: AsyncCallback\>): void - -获取帧率范围,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| -------- | -------------------- | ---- | ------------------------ | -| callback | AsyncCallback\> | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -videoOutput.getFrameRateRange((err) => { - if (err) { - console.error(`Failed to get the frameRateRange ${err.message}`); - return; - } - console.log('getFrameRateRange success.'); -}); -``` - -### getFrameRateRange - -getFrameRateRange(): Promise\> - -获取帧率范围,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**返回值:** - -| 类型 | 说明 | -| -------------- | ----------------------- | -| Promise\> | 使用Promise的方式获取结果。 | - -**示例:** - -```js -videoOutput.getFrameRateRange().then(() => { - console.log('getFrameRateRange success.'); -}) -``` - -### setFrameRateRange - -setFrameRateRange(minFrameRate: number, maxFrameRate: number, callback: AsyncCallback\>): void - -获取帧率范围,通过注册回调函数获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------------ | ----------------------------- | ---- | ------------------- | -| minFrameRate | number | 是 | 最小帧率。 | -| maxFrameRate | number | 是 | 最大帧率。 | -| callback | AsyncCallback\> | 是 | 回调函数,用于获取结果。 | - -**示例:** - -```js -videoOutput.setFrameRateRange(minFrameRate, maxFrameRate,(err) => { - if (err) { - console.error(`Failed to set the frameRateRange ${err.message}`); - return; - } - console.log('setFrameRateRange success.'); -}); -``` - -### setFrameRateRange - -setFrameRateRange(minFrameRate: number, maxFrameRate: number): Promise\> - -获取帧率范围,通过Promise获取结果。 - -**系统能力:** SystemCapability.Multimedia.Camera.Core - -**参数:** - -| 名称 | 类型 | 必填 | 说明 | -| ------------ | ----------------------------- | ---- | ------------------- | -| minFrameRate | number | 是 | 最小帧率。 | -| maxFrameRate | number | 是 | 最大帧率。 | - -**返回值:** - -| 类型 | 说明 | -| -------------- | ----------------------- | -| Promise\> | 使用Promise的方式获取结果。 | - -**示例:** - -```js -videoOutput.setFrameRateRange(minFrameRate, maxFrameRate).then(() => { - console.log('setFrameRateRange success.'); -}) -``` - ### on('frameStart') on(type: 'frameStart', callback: AsyncCallback): void @@ -4446,7 +3879,7 @@ metadataOutput.on('metadataObjectsAvailable', (metadataObject) => { ### on('error') -on(tuype: 'error', callback: ErrorCallback): void +on(type: 'error', callback: ErrorCallback): void 监听metadata流的错误,通过注册回调函数获取结果。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md index b759733187f276b6396380571bee3f48c1d930b0..28646100317913a0d82f2fbe740c7fa647e4f491 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-continuation-continuationManager.md @@ -30,6 +30,16 @@ register(callback: AsyncCallback\): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回流转管理服务连接后生成的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360207 | The maximum number of registrations exceeded. | + **示例:** ```ts @@ -61,6 +71,17 @@ register(options: ContinuationExtraParams, callback: AsyncCallback\): vo | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 是 | 过滤可选择设备列表的额外参数。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回流转管理服务连接后生成的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360207 | The maximum number of registrations exceeded. | +| 29360216 | Invalid continuation mode. | + **示例:** ```ts @@ -100,6 +121,17 @@ register(options?: ContinuationExtraParams): Promise\; | ------------------------- | ------------------ | | Promise\ | Promise形式返回流转管理服务连接后生成的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object | +| 7 | The object is null. | +| 29360207 | The maximum number of registrations exceeded. | +| 29360216 | Invalid continuation mode. | + **示例:** ```ts @@ -131,6 +163,16 @@ registerContinuation(callback: AsyncCallback\): void; | -------- | -------- | -------- | -------- | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回流转管理服务连接后生成的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600003 | The number of token registration times has reached the upper limit. | + **示例:** ```ts @@ -164,6 +206,16 @@ registerContinuation(options: ContinuationExtraParams, callback: AsyncCallback\< | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 是 | 过滤可选择设备列表的额外参数。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回流转管理服务连接后生成的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600003 | The number of token registration times has reached the upper limit. | + **示例:** ```ts @@ -205,6 +257,16 @@ registerContinuation(options?: ContinuationExtraParams): Promise\; | ------------------------- | ------------------ | | Promise\ | Promise形式返回流转管理服务连接后生成的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600003 | The number of token registration times has reached the upper limit. | + **示例:** ```ts @@ -244,6 +306,18 @@ on(type: "deviceConnect", callback: Callback\): void; | type | string | 是 | 监听的事件类型,固定值"deviceConnect"。 | | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | 是 | 当用户从设备选择模块中选择设备时调用,返回设备ID、设备类型和设备名称供开发者使用。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object | +| 7 | The object is null | 7 | +| 29360208 | The token has not registered. | +| 29360209 | Callback has been registered. | +| 29360214 | The type of callback is not supported. | + **示例:** ```ts @@ -271,6 +345,18 @@ on(type: "deviceDisconnect", callback: Callback\): void; | type | string | 是 | 监听的事件类型,固定值"deviceDisconnect"。 | | callback | Callback\ | 是 | 当用户从设备选择模块中断开设备时调用,返回设备ID供开发者使用。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360209 | Callback has been registered. | +| 29360214 | The type of callback is not supported. | + **示例:** ```ts @@ -296,6 +382,18 @@ off(type: "deviceConnect", callback?: Callback\): void; | type | string | 是 | 取消监听的事件类型,固定值"deviceConnect"。 | | callback | Callback\<[ContinuationResult](js-apis-continuation-continuationResult.md)> | 否 | 当用户从设备选择模块中选择设备时调用,返回设备ID、设备类型和设备名称供开发者使用。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360214 | The type of callback is not supported. | + **示例:** ```ts @@ -323,6 +421,18 @@ off(type: "deviceDisconnect", callback?: Callback\): void; | type | string | 是 | 取消监听的事件类型,固定值"deviceDisconnect"。 | | callback | Callback\ | 否 | 当用户从设备选择模块中断开设备时调用,返回设备ID供开发者使用。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | +| 29360210 | Callback has not registered. | +| 29360214 | The type of callback is not supported. | + **示例:** ```ts @@ -347,6 +457,17 @@ on(type: "deviceConnect", token: number, callback: Callback\> | 是 | 当用户从设备选择模块中选择设备时调用,返回设备ID、设备类型和设备名称供开发者使用。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | + **示例:** ```ts @@ -381,6 +502,17 @@ on(type: "deviceDisconnect", token: number, callback: Callback\>) | token | number | 是 | 注册后的token。 | | callback | Callback\> | 是 | 当用户从设备选择模块中断开设备时调用,返回设备ID供开发者使用。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | + **示例:** ```ts @@ -413,6 +545,17 @@ off(type: "deviceConnect", token: number): void; | type | string | 是 | 取消监听的事件类型,固定值"deviceConnect"。 | | token | number | 是 | 注册后的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | + **示例:** ```ts @@ -439,6 +582,17 @@ off(type: "deviceDisconnect", token: number): void; | type | string | 是 | 取消监听的事件类型,固定值"deviceDisconnect"。 | | token | number | 是 | 注册后的token。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | +| 16600004 | The specified callback has been registered. | + **示例:** ```ts @@ -467,6 +621,19 @@ startDeviceManager(token: number, callback: AsyncCallback\): void; | token | number | 是 | 注册后的token。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 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. | +| 29360216 | Invalid continuation mode. | + **示例:** ```ts @@ -498,6 +665,19 @@ startDeviceManager(token: number, options: ContinuationExtraParams, callback: As | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 是 | 过滤可选择设备列表的额外参数。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 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. | +| 29360216 | Invalid continuation mode. | + **示例:** ```ts @@ -537,6 +717,19 @@ startDeviceManager(token: number, options?: ContinuationExtraParams): Promise\ | Promise形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 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. | +| 29360216 | Invalid continuation mode. | + **示例:** ```ts @@ -568,6 +761,16 @@ startContinuationDeviceManager(token: number, callback: AsyncCallback\): v | token | number | 是 | 注册后的token。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + **示例:** ```ts @@ -601,6 +804,16 @@ startContinuationDeviceManager(token: number, options: ContinuationExtraParams, | options | [ContinuationExtraParams](js-apis-continuation-continuationExtraParams.md) | 是 | 过滤可选择设备列表的额外参数。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + **示例:** ```ts @@ -642,6 +855,16 @@ startContinuationDeviceManager(token: number, options?: ContinuationExtraParams) | ------------------------- | ------------------ | | Promise\ | Promise形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + **示例:** ```ts @@ -681,6 +904,19 @@ updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState, | status | [DeviceConnectState](#deviceconnectstate) | 是 | 设备连接状态。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 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. | + **示例:** ```ts @@ -719,6 +955,19 @@ updateConnectStatus(token: number, deviceId: string, status: DeviceConnectState) | ------------------------- | ------------------ | | Promise\ | Promise形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 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. | + **示例:** ```ts @@ -750,6 +999,16 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt | status | [DeviceConnectState](#deviceconnectstate) | 是 | 设备连接状态。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + **示例:** ```ts @@ -790,6 +1049,16 @@ updateContinuationState(token: number, deviceId: string, status: DeviceConnectSt | ------------------------- | ------------------ | | Promise\ | Promise形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + **示例:** ```ts @@ -826,6 +1095,16 @@ unregister(token: number, callback: AsyncCallback\): void; | token | number | 是 | 注册后的token。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | + **示例:** ```ts @@ -861,6 +1140,16 @@ unregister(token: number): Promise\; | ------------------------- | ------------------ | | Promise\ | Promise形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 3 | Failed to flatten the object. | +| 7 | The object is null. | +| 29360208 | The token has not registered. | + **示例:** ```ts @@ -889,6 +1178,16 @@ unregisterContinuation(token: number, callback: AsyncCallback\): void; | token | number | 是 | 注册后的token。 | | callback | AsyncCallback\ | 是 | AsyncCallback形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + **示例:** ```ts @@ -926,6 +1225,16 @@ unregisterContinuation(token: number): Promise\; | ------------------------- | ------------------ | | Promise\ | Promise形式返回接口调用结果。 | +**错误码:** + +以下错误码的详细介绍请参见[分布式调度错误码](../errorcodes/errcode-DistributedSchedule.md)。 + +| 错误码ID | 错误信息 | +| ------- | -------------------------------------------- | +| 401 | The parameter check failed. | +| 16600001 | The system ability work abnormally. | +| 16600002 | The specified token or callback has not registered. | + **示例:** ```ts diff --git a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md index a6f6fa765108af8a4db7b5b195fbe0bd9f678654..3b7ed92b83cddfb82a351e6482904a35e61d5f74 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-device-manager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-device-manager.md @@ -35,13 +35,24 @@ createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------------- | ---- | ------------------------------------ | | bundleName | string | 是 | 指示应用程序的包名。 | | callback | AsyncCallback<[DeviceManager](#devicemanager)> | 是 | DeviceManager实例创建时调用的回调,返回设备管理器对象实例。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600102 | Failed to obtain the service. | + +**示例:** + ```js try { deviceManager.createDeviceManager("ohos.samples.jshelloworld", (err, data) => { @@ -209,7 +220,6 @@ createDeviceManager(bundleName: string, callback: AsyncCallback<DeviceManager 设备管理实例,用于获取可信设备和本地设备的相关信息。在调用DeviceManager的方法前,需要先通过createDeviceManager构建一个DeviceManager实例dmInstance。 - ### release release(): void @@ -218,7 +228,16 @@ release(): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js try { dmInstance.release(); @@ -227,7 +246,6 @@ release(): void } ``` - ### getTrustedDeviceListSync getTrustedDeviceListSync(): Array<DeviceInfo> @@ -236,12 +254,22 @@ getTrustedDeviceListSync(): Array<DeviceInfo> **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 返回值: +**返回值:** + | 名称 | 说明 | | -------------------------------------- | --------- | | Array<[DeviceInfo](#deviceinfo)> | 返回可信设备列表。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js try { var deviceInfoList = dmInstance.getTrustedDeviceListSync(); @@ -250,7 +278,6 @@ getTrustedDeviceListSync(): Array<DeviceInfo> } ``` - ### getTrustedDeviceList8+ getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): void @@ -259,12 +286,22 @@ getTrustedDeviceList(callback:AsyncCallback<Array<DeviceInfo>>): voi **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------------------- | | callback | AsyncCallback<Array<[DeviceInfo](#deviceinfo)>> | 是 | 获取所有可信设备列表的回调,返回设备信息。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js try { dmInstance.getTrustedDeviceList((err, data) => { @@ -287,22 +324,28 @@ getTrustedDeviceList(): Promise<Array<DeviceInfo>> **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 返回值: +**返回值:** + | 类型 | 说明 | | ---------------------------------------- | --------------------- | | Promise<Array<[DeviceInfo](#deviceinfo)>> | Promise实例,用于获取异步返回结果。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js - try { - dmInstance.getTrustedDeviceList().then((data) => { - console.log('get trusted device info: ' + JSON.stringify(data)); - }).catch((err) => { - console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); - }); - } catch (err) { + dmInstance.getTrustedDeviceList().then((data) => { + console.log('get trusted device info: ' + JSON.stringify(data)); + }).catch((err) => { console.error("getTrustedDeviceList errCode:" + err.code + ",errMessage:" + err.message); - } + }); ``` ### getLocalDeviceInfoSync8+ @@ -313,12 +356,22 @@ getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 返回值: - | 名称 | 说明 | - | -------------------------------------- | --------- | - | Array<[DeviceInfo](#deviceinfo)> | 返回本地设备列表。 | +**返回值:** + + | 名称 | 说明 | + | ------------------------- | ---------------- | + | [DeviceInfo](#deviceinfo) | 返回本地设备列表。 | + +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** -- 示例: ```js try { var deviceInfo = dmInstance.getLocalDeviceInfoSync(); @@ -327,7 +380,6 @@ getLocalDeviceInfoSync(): [DeviceInfo](#deviceinfo) } ``` - ### getLocalDeviceInfo8+ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void @@ -336,12 +388,22 @@ getLocalDeviceInfo(callback:AsyncCallback<DeviceInfo>): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------- | | callback | AsyncCallback<[DeviceInfo](#deviceinfo)> | 是 | 获取本地设备信息。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js try { dmInstance.getLocalDeviceInfo((err, data) => { @@ -364,22 +426,28 @@ getLocalDeviceInfo(): Promise<DeviceInfo> **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 返回值: +**返回值:** + | 类型 | 说明 | | ---------------------------------------- | --------------------- | | Promise<[DeviceInfo](#deviceinfo)> | Promise实例,用于获取异步返回结果。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| ------- | --------------------------------------------------------------- | +| 11600101| Failed to execute the function. | + +**示例:** + ```js - try { - dmInstance.getLocalDeviceInfo().then((data) => { - console.log('get local device info: ' + JSON.stringify(data)); - }).catch((err) => { - console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); - }); - } catch (err) { + dmInstance.getLocalDeviceInfo().then((data) => { + console.log('get local device info: ' + JSON.stringify(data)); + }).catch((err) => { console.error("getLocalDeviceInfo errCode:" + err.code + ",errMessage:" + err.message); - } + }); ``` ### startDeviceDiscovery8+ @@ -390,12 +458,23 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: - | 名称 | 参数类型 | 必填 | 说明 | +**参数:** + + | 名称 | 参数类型 | 必填 | 说明 | | ------------- | ------------------------------- | ---- | ----- | - | subscribeInfo | [SubscribeInfo](#subscribeinfo) | 是 | 发现信息。 | + | subscribeInfo | [SubscribeInfo](#subscribeinfo) | 是 | 发现信息。| + +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600104 | Discovery invalid. | + +**示例:** -- 示例: ```js // 生成发现标识,随机数确保每次调用发现接口的标识不一致 var subscribeId = Math.floor(Math.random() * 10000 + 1000); @@ -423,13 +502,24 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo, filterOptions?: string): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: - | 名称 | 参数类型 | 必填 | 说明 | - | ------------- | ------------------------------- | ---- | ----- | +**参数:** + + | 名称 | 参数类型 | 必填 | 说明 | + | ------------- | ------------------------------- | ---- | ----- | | subscribeInfo | [SubscribeInfo](#subscribeinfo) | 是 | 发现信息。 | - | filterOptions | string | 否 | 发现设备过滤信息。| + | filterOptions | string | 否 | 发现设备过滤信息。| + +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600104 | Discovery invalid. | + +**示例:** -- 示例: ```js // 生成发现标识,随机数确保每次调用发现接口的标识不一致 var subscribeId = Math.floor(Math.random() * 10000 + 1000); @@ -457,7 +547,7 @@ startDeviceDiscovery(subscribeInfo: SubscribeInfo, filterOptions?: string): void console.error("startDeviceDiscovery errCode:" + err.code + ",errMessage:" + err.message); } ``` - + ### stopDeviceDiscovery stopDeviceDiscovery(subscribeId: number): void @@ -466,12 +556,22 @@ stopDeviceDiscovery(subscribeId: number): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | ----------- | ------ | ---- | ----- | | subscribeId | number | 是 | 发现标识。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js // 入参需要和startDeviceDiscovery接口传入的subscribeId配对使用 try { @@ -489,12 +589,23 @@ publishDeviceDiscovery(publishInfo: PublishInfo): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | ------------- | ------------------------------- | ---- | ----- | | publishInfo | [PublishInfo](#publishinfo) | 是 | 发布设备发现信息。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600105 | Publish invalid. | + +**示例:** + ```js // 生成发布标识,随机数确保每次调用发布接口的标识不一致 var publishId = Math.floor(Math.random() * 10000 + 1000); @@ -519,12 +630,22 @@ unPublishDeviceDiscovery(publishId: number): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | ----------- | -------- | ---- | ----- | | publishId | number | 是 | 发布标识。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js // 入参需要和publishDeviceDiscovery接口传入的publishId配对使用 try { @@ -542,14 +663,25 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | ---------- | ---------------------------------------- | ---- | ------- | | deviceInfo | [DeviceInfo](#deviceinfo) | 是 | 设备信息。 | | authParam | [AuthParam](#authparam) | 是 | 认证参数。 | | callback | AsyncCallback<{ deviceId: string, pinToken ?: number }> | 是 | 认证结果回调。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | +| 11600103 | Authentication invalid. | + +**示例:** + ```js // 认证的设备信息,可以从发现的结果中获取 var deviceInfo ={ @@ -567,8 +699,8 @@ authenticateDevice(deviceInfo: DeviceInfo, authParam: AuthParam, callback: Async console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message); return; } - console.info(TAG + "authenticateDevice result:" + JSON.stringify(data)); - token = data.pinToken; + console.info("authenticateDevice result:" + JSON.stringify(data)); + let token = data.pinToken; }); } catch (err) { console.error("authenticateDevice errCode:" + err.code + ",errMessage:" + err.message); @@ -583,12 +715,22 @@ unAuthenticateDevice(deviceInfo: DeviceInfo): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | ---------- | ------------------------- | ---- | ----- | | deviceInfo | [DeviceInfo](#deviceinfo) | 是 | 设备信息。 | -- 示例: +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** + ```js try { dmInstance.unAuthenticateDevice(deviceInfo); @@ -597,7 +739,6 @@ unAuthenticateDevice(deviceInfo: DeviceInfo): void } ``` - ### verifyAuthInfo verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, level: number}>): void @@ -606,13 +747,23 @@ verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, le **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------- | | authInfo | [AuthInfo](#authinfo) | 是 | 认证信息。 | - | authInfo | AsyncCallback<{ deviceId: string, level: number }> | 是 | 验证结果回调。 | + | callback | AsyncCallback<{ deviceId: string, level: number }> | 是 | 验证结果回调。 | + +**错误码:** + +以下的错误码的详细介绍请参见[设备管理错误码](../errorcodes/errorcode-device-manager.md) + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------------------------- | +| 11600101 | Failed to execute the function. | + +**示例:** -- 示例: ```js let authInfo = { "authType": 1, @@ -625,13 +776,104 @@ verifyAuthInfo(authInfo: AuthInfo, callback: AsyncCallback<{deviceId: string, le console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message); return; } - console.info(TAG + "verifyAuthInfo result:" + JSON.stringify(data)); + console.info("verifyAuthInfo result:" + JSON.stringify(data)); }); } catch (err) { console.error("verifyAuthInfo errCode:" + err.code + ",errMessage:" + err.message); } ``` +### setUserOperation9+ + +setUserOperation(operateAction: number, params: string): void; + +设置用户ui操作行为。 + +**系统能力**:SystemCapability.DistributedHardware.DeviceManager + +**参数:** + + | 名称 | 参数类型 | 必填 | 说明 | + | ------------- | --------------- | ---- | ------------------- | + | operateAction | number | 是 | 用户操作动作。 | + | params | string | 是 | 表示用户的输入参数。 | + +**示例:** + + ```js + try { + /* + operateAction = 0 - 允许授权 + operateAction = 1 - 取消授权 + operateAction = 2 - 授权框用户操作超时 + operateAction = 3 - 取消pin码框展示 + operateAction = 4 - 取消pin码输入框展示 + operateAction = 5 - pin码输入框确定操作 + */ + let operation = 0; + this.dmInstance.setUserOperation(operation, "extra") + } catch (err) { + console.error("setUserOperation errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +### on('uiStateChange')9+ + +on(type: 'uiStateChange', callback: Callback<{ param: string}>): void; + +ui状态变更回调。 + +**系统能力**:SystemCapability.DistributedHardware.DeviceManager + +**参数:** + + | 名称 | 参数类型 | 必填 | 说明 | + | -------- | ------------------------------------ | ---- | ------------------------------ | + | type | string | 是 | 注册的设备管理器 ui 状态回调,以便在状态改变时通知应用。 | + | callback | Callback<{ param: string}> | 是 | 指示要注册的设备管理器 ui 状态回调,返回ui状态。 | + +**示例:** + + ```js + try { + dmInstance.on('uiStateChange', (data) => { + console.log("uiStateChange executed, dialog closed" + JSON.stringify(data)) + var tmpStr = JSON.parse(data.param) + this.isShow = tmpStr.verifyFailed + console.log("uiStateChange executed, dialog closed" + this.isShow) + if (!this.isShow) { + this.destruction() + } + }); + } catch (err) { + console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); + } + ``` + +### off('uiStateChange')9+ + +off(type: 'uiStateChange', callback?: Callback<{ param: string}>): void; + +取消ui状态变更回调 + +**系统能力**:SystemCapability.DistributedHardware.DeviceManager + +**参数:** + + | 名称 | 参数类型 | 必填 | 说明 | + | -------- | ------------------------------------- | ---- | ------------------------------ | + | type | string | 是 | 取消注册的设备管理器 ui 状态回调。 | + | callback | Callback<{ param: string}> | 是 | 指示要取消注册的设备管理器 ui 状态,返回UI状态。 | + +**示例:** + + ```js + try { + dmInstance.off('uiStateChange'); + } catch (err) { + console.error("uiStateChange errCode:" + err.code + ",errMessage:" + err.message); + } + ``` ### on('deviceStateChange') @@ -641,13 +883,15 @@ on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChange **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------ | | type | string | 是 | 注册设备状态回调,固定为deviceStateChange。 | | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo) }> | 是 | 指示要注册的设备状态回调,返回设备状态和设备信息。 | -- 示例: +**示例:** + ```js try { dmInstance.on('deviceStateChange', (data) => { @@ -658,7 +902,6 @@ on(type: 'deviceStateChange', callback: Callback<{ action: DeviceStateChange } ``` - ### off('deviceStateChange') off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChangeAction, device: DeviceInfo }>): void @@ -667,13 +910,15 @@ off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChang **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------------------------- | | type | string | 是 | 根据应用程序的包名取消注册设备状态回调。 | | callback | Callback<{ action: [DeviceStateChangeAction](#devicestatechangeaction), device: [DeviceInfo](#deviceinfo)  }> | 是 | 指示要取消注册的设备状态回调,返回设备状态和设备信息。 | -- 示例: +**示例:** + ```js try { dmInstance.off('deviceStateChange', (data) => { @@ -684,7 +929,6 @@ off(type: 'deviceStateChange', callback?: Callback<{ action: DeviceStateChang } ``` - ### on('deviceFound') on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: DeviceInfo }>): void @@ -693,13 +937,15 @@ on(type: 'deviceFound', callback: Callback<{ subscribeId: number, device: Dev **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | -------------------------- | | type | string | 是 | 注册设备发现回调,以便在发现周边设备时通知应用程序。 | | callback | Callback<{ subscribeId: number, device: DeviceInfo }> | 是 | 注册设备发现的回调方法。 | -- 示例: +**示例:** + ```js try { dmInstance.on('deviceFound', (data) => { @@ -718,13 +964,15 @@ off(type: 'deviceFound', callback?: Callback<{ subscribeId: number, device: D **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------------------------- | | type | string | 是 | 取消注册设备发现回调。 | | callback | Callback<{ subscribeId: number, device: [DeviceInfo](#deviceinfo) }> | 是 | 指示要取消注册的设备发现回调,返回设备状态和设备信息。 | -- 示例: +**示例:** + ```js try { dmInstance.off('deviceFound', (data) => { @@ -743,13 +991,15 @@ on(type: 'discoverFail', callback: Callback<{ subscribeId: number, reason: nu **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ------------------------------ | | type | string | 是 | 注册设备发现失败回调,以便在发现周边设备失败时通知应用程序。 | | callback | Callback<{ subscribeId: number, reason: number }> | 是 | 注册设备发现失败的回调方法。 | -- 示例: +**示例:** + ```js try { dmInstance.on('discoverFail', (data) => { @@ -768,13 +1018,15 @@ off(type: 'discoverFail', callback?: Callback<{ subscribeId: number, reason: **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ----------------- | | type | string | 是 | 取消注册设备发现失败回调。 | | callback | Callback<{ subscribeId: number, reason: number }> | 是 | 指示要取消注册的设备发现失败回调。 | -- 示例: +**示例:** + ```js try { dmInstance.off('discoverFail', (data) => { @@ -793,13 +1045,16 @@ on(type: 'publishSuccess', callback: Callback<{ publishId: number }>): voi **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | -------------------------- | | type | string | 是 | 注册发布设备成功回调,以便将发布成功时通知应用程序。 | | callback | Callback<{ publishId: number }> | 是 | 注册设备发布成功的回调方法。 | -- 示例: + +**示例:** + ```js try { dmInstance.on('publishSuccess', (data) => { @@ -818,13 +1073,15 @@ off(type: 'publishSuccess', callback?: Callback<{ publishId: number }>): v **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------------------------- | | type | string | 是 | 取消注册设备发布成功回调。 | | callback | Callback<{ publishId: number }> | 是 | 指示要取消注册的设备发布成功回调。 | -- 示例: +**示例:** + ```js try { dmInstance.off('publishSuccess', (data) => { @@ -843,13 +1100,15 @@ on(type: 'publishFail', callback: Callback<{ publishId: number, reason: numbe **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ----------------------------------------------------- | ---- | ------------------------------ | | type | string | 是 | 注册设备发布失败回调,以便在发布设备失败时通知应用程序。 | | callback | Callback<{ publishId: number, reason: number }> | 是 | 注册设备发布失败的回调方法。 | -- 示例: +**示例:** + ```js try { dmInstance.on('publishFail', (data) => { @@ -868,13 +1127,15 @@ off(type: 'publishFail', callback?: Callback<{ publishId: number, reason: num **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ----------------------------------------------------- | ---- | ----------------- | | type | string | 是 | 取消注册设备发布失败回调。 | | callback | Callback<{ publishId: number, reason: number }> | 是 | 指示要取消注册设备发布失败回调。 | -- 示例: +**示例:** + ```js try { dmInstance.off('publishFail', (data) => { @@ -893,13 +1154,15 @@ on(type: 'serviceDie', callback: () => void): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | ---------------------------------------- | | type | string | 是 | 注册serviceDie回调,以便在devicemanager服务异常终止时通知应用程序。 | | callback | () => void | 是 | 注册serviceDie的回调方法。 | -- 示例: +**示例:** + ```js try { dmInstance.on("serviceDie", () => { @@ -910,7 +1173,6 @@ on(type: 'serviceDie', callback: () => void): void } ``` - ### off('serviceDie') off(type: 'serviceDie', callback?: () => void): void @@ -919,13 +1181,15 @@ off(type: 'serviceDie', callback?: () => void): void **系统能力**:SystemCapability.DistributedHardware.DeviceManager -- 参数: +**参数:** + | 名称 | 参数类型 | 必填 | 说明 | | -------- | ----------------------- | ---- | ---------------------------------------- | | type | string | 是 | 取消注册serviceDie回调,以便在devicemanager服务异常终止时通知应用程序。 | | callback | () => void | 否 | 取消注册serviceDie的回调方法。 | -- 示例: +**示例:** + ```js try { dmInstance.off("serviceDie", () => { diff --git a/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md b/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md index 6b99171e10220d85932ad78e8f3b33bc48c4aa1a..42794c93059d0ecefe69c2ad8438cb44350afaef 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md +++ b/zh-cn/application-dev/reference/apis/js-apis-deviceUsageStatistics.md @@ -23,7 +23,7 @@ ## 导入模块 -``` +```js import bundleState from '@ohos.bundleState' ``` @@ -31,7 +31,7 @@ import bundleState from '@ohos.bundleState' isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void -判断指定bundleName的应用当前是否是空闲状态,三方应用只能查询自身的空闲状态,使用Callback形式返回。 +判断指定bundleName的应用当前是否是空闲状态,三方应用只能查询自身的空闲状态,查询其他应用空闲状态,需要申请权限ohos.permission.BUNDLE_ACTIVE_INFO,使用Callback形式返回。 **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup @@ -44,7 +44,7 @@ isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void **示例**: - ``` + ```js bundleState.isIdleState("com.ohos.camera", (err, res) => { if (err) { console.log('BUNDLE_ACTIVE isIdleState callback failed, because: ' + err.code); @@ -58,7 +58,7 @@ isIdleState(bundleName: string, callback: AsyncCallback<boolean>): void isIdleState(bundleName: string): Promise<boolean> -判断指定bundleName的应用当前是否是空闲状态,三方应用只能查询自身的空闲状态,使用Promise形式返回。 +判断指定bundleName的应用当前是否是空闲状态,三方应用只能查询自身的空闲状态,查询其他应用空闲状态,需要申请权限ohos.permission.BUNDLE_ACTIVE_INFO,使用Promise形式返回。 **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup @@ -88,7 +88,7 @@ isIdleState(bundleName: string): Promise<boolean> queryAppUsagePriorityGroup(): Promise<number> -查询当前应用的优先级分组。使用Promise形式返回其应用分组。 +查询当前应用的优先级分组。使用Promise形式返回其应用分组,分组信息参考[GroupType](#grouptype)。 **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup @@ -112,7 +112,7 @@ bundleState.queryAppUsagePriorityGroup().then( res => { queryAppUsagePriorityGroup(callback: AsyncCallback<number>): void -查询当前应用的优先级分组。使用callback形式返回其应用分组。 +查询当前应用的优先级分组。使用callback形式返回其应用分组,分组信息参考[GroupType](#grouptype)。 **系统能力**:SystemCapability.ResourceSchedule.UsageStatistics.AppGroup @@ -150,8 +150,8 @@ queryBundleStateInfos(begin: number, end: number, callback: AsyncCallback<Bun | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | | callback | AsyncCallback<[BundleActiveInfoResponse](#bundleactiveinforesponse)> | 是 | 指定的callback回调方法。返回指定起始和结束时间内应用使用时长统计信息。 | **示例**: @@ -188,8 +188,8 @@ queryBundleStateInfos(begin: number, end: number): Promise<BundleActiveInfoRe | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | **返回值**: @@ -230,14 +230,14 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num | 参数名 | 类型 | 必填 | 说明 | | ---------- | ---------------------------------------- | ---- | ---------------------------------------- | | byInterval | [IntervalType](#intervaltype) | 是 | 查询类型。 | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | | callback | AsyncCallback<Array<[BundleStateInfo](#bundlestateinfo)>> | 是 | 指定的callback回调方法。返回指定时间段间隔(天、周、月、年)查询应用使用时长统计信息。 | **示例**: ```js - bundleState.queryBundleStateInfoByInterval(0, 0, 20000000000000, (err, res) => { + bundleState.queryBundleStateInfoByInterval(bundleState.IntervalType.BY_OPTIMIZED, 0, 20000000000000, (err, res) => { if (err) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval callback failed, because: ' + err.code); } else { @@ -267,8 +267,8 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num | 参数名 | 类型 | 必填 | 说明 | | ---------- | ----------------------------- | ---- | ----- | | byInterval | [IntervalType](#intervaltype) | 是 | 查询类型。 | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | **返回值**: @@ -279,7 +279,7 @@ queryBundleStateInfoByInterval(byInterval: IntervalType, begin: number, end: num **示例**: ```js - bundleState.queryBundleStateInfoByInterval(0, 0, 20000000000000).then( res => { + bundleState.queryBundleStateInfoByInterval(bundleState.IntervalType.BY_OPTIMIZED, 0, 20000000000000).then( res => { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise success.'); for (let i = 0; i < res.length; i++) { console.log('BUNDLE_ACTIVE queryBundleStateInfoByInterval promise number : ' + (i + 1)); @@ -306,8 +306,8 @@ queryBundleActiveStates(begin: number, end: number, callback: AsyncCallback<A | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | | callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | 是 | 指定的callback回调方法。返回指定起始和结束时间查询所有应用的事件集合。 | **示例**: @@ -342,8 +342,8 @@ queryBundleActiveStates(begin: number, end: number): Promise<Array<BundleA | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | **返回值**: @@ -377,8 +377,8 @@ queryCurrentBundleActiveStates(begin: number, end: number, callback: AsyncCallba | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | --------------------------------------- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | | callback | AsyncCallback<Array<[BundleActiveState](#bundleactivestate)>> | 是 | 指定的callback回调方法。返回指定起始和结束时间查询当前应用的事件集合。 | **示例**: @@ -409,8 +409,8 @@ queryCurrentBundleActiveStates(begin: number, end: number): Promise<Array< | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | **返回值**: @@ -884,8 +884,8 @@ queryBundleActiveEventStates(begin: number, end: number): Promise<Array<Bu | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | **返回值**: @@ -920,8 +920,8 @@ queryBundleActiveEventStates(begin: number, end: number, callback: AsyncCallback | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | | callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | 是 | 指定的callback回调方法。返回指定起始和结束时间查询系统事件(休眠、唤醒、解锁、锁屏)统计信息。 | **示例**: @@ -953,8 +953,8 @@ queryAppNotificationNumber(begin: number, end: number): Promise<Array<Bund | 参数名 | 类型 | 必填 | 说明 | | ----- | ------ | ---- | ----- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | **返回值**: @@ -989,8 +989,8 @@ queryAppNotificationNumber(begin: number, end: number, callback: AsyncCallback&l | 参数名 | 类型 | 必填 | 说明 | | -------- | ---------------------------------------- | ---- | ---------------------------------------- | -| begin | number | 是 | 起始时间。 | -| end | number | 是 | 结束时间。 | +| begin | number | 是 | 起始时间,单位毫秒。 | +| end | number | 是 | 结束时间,单位毫秒。 | | callback | AsyncCallback<Array<[BundleActiveEventState](#bundleactiveeventstate9)>> | 是 | 指定的callback回调方法。返回通过指定起始和结束时间查询所有应用的通知次数信息。 | **示例**: diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md index d9e03d2412cc526c7401b0994979428f073ca95d..5d62db3f113c60af609aa15ce4aa6990fb079ab3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributed-account.md @@ -7,7 +7,7 @@ ## 导入模块 - + ```js import account_distributedAccount from '@ohos.account.distributedAccount'; ``` @@ -40,7 +40,7 @@ getDistributedAccountAbility(): DistributedAccountAbility getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void -获取分布式帐号信息,使用callback回调异步返回结果。 +获取分布式帐号信息,使用callback异步回调。 **系统能力:** SystemCapability.Account.OsAccount @@ -50,7 +50,15 @@ getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): voi | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | 是 | 获取分布式帐号信息的回调。 | + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | 是 | 回调参数。当获取分布式帐号信息成功,err为undefined,data为获取到的分布式帐号信息对象;否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 201 | permission denied. | + | 401 | the parameter check failed. | + | 12300001 | system service exception. | **示例:** ```js @@ -70,7 +78,7 @@ getOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): voi getOsAccountDistributedInfo(): Promise<DistributedInfo> -获取分布式帐号信息,使用Promise方式异步返回结果。 +获取分布式帐号信息。使用Promise异步回调。 **系统能力:** SystemCapability.Account.OsAccount @@ -80,7 +88,15 @@ getOsAccountDistributedInfo(): Promise<DistributedInfo> | 类型 | 说明 | | -------- | -------- | - | Promise<[DistributedInfo](#distributedinfo)> | Promise实例,用于获取异步返回结果。 | + | Promise<[DistributedInfo](#distributedinfo)> | Promise对象。返回分布式帐号信息对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 201 | permission denied. | + | 401 | the parameter check failed. | + | 12300001 | system service exception. | **示例:** ```js @@ -100,7 +116,7 @@ getOsAccountDistributedInfo(): Promise<DistributedInfo> queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): void -获取分布式帐号信息,使用callback回调异步返回结果。 +获取分布式帐号信息。使用callback异步回调。 > **说明:** 从API version 9开始废弃,建议使用[getOsAccountDistributedInfo](#getosaccountdistributedinfo9) > > 从 API version 7开始支持。 @@ -113,7 +129,7 @@ queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): v | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | 是 | 获取分布式帐号信息的回调。 | + | callback | AsyncCallback<[DistributedInfo](#distributedinfo)> | 是 | 回调函数。当获取分布式帐号信息成功,err为undefined,data为获取到的分布式帐号信息对象;否则为错误对象。 | **示例:** ```js @@ -129,7 +145,7 @@ queryOsAccountDistributedInfo(callback: AsyncCallback<DistributedInfo>): v queryOsAccountDistributedInfo(): Promise<DistributedInfo> -获取分布式帐号信息,使用Promise方式异步返回结果。 +获取分布式帐号信息。使用Promise异步回调。 > **说明:** 从API version 9开始废弃,建议使用[getOsAccountDistributedInfo](#getosaccountdistributedinfo9-1) > > 从 API version 7开始支持。 @@ -142,7 +158,7 @@ queryOsAccountDistributedInfo(): Promise<DistributedInfo> | 类型 | 说明 | | -------- | -------- | - | Promise<[DistributedInfo](#distributedinfo)> | Promise实例,用于获取异步返回结果。 | + | Promise<[DistributedInfo](#distributedinfo)> | Promise对象。返回分布式帐号信息对象。 | **示例:** ```js @@ -159,7 +175,7 @@ queryOsAccountDistributedInfo(): Promise<DistributedInfo> setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void -更新分布式帐号信息,使用callback回调异步返回结果。 +更新分布式帐号信息。使用callback异步回调。 **系统能力:** SystemCapability.Account.OsAccount @@ -170,7 +186,16 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallbac | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | accountInfo | [DistributedInfo](#distributedinfo) | 是 | 分布式帐号信息。 | - | callback | AsyncCallback<void> | 是 | 更新分布式帐号信息的回调。 | + | callback | AsyncCallback<void> | 是 | 回调函数。当更新分布式帐号信息成功时,err为undefined,否则为错误对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 201 | permission denied. | + | 401 | the parameter check failed. | + | 12300001 | system service exception. | + | 12300002 | invalid accountInfo. | **示例:** ```js @@ -189,7 +214,7 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallbac setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> -更新分布式帐号信息,使用Promise方式异步返回结果。 +更新分布式帐号信息。使用Promise异步回调。 **系统能力:** SystemCapability.Account.OsAccount @@ -205,7 +230,16 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> | 类型 | 说明 | | -------- | -------- | - | Promise<void> | Promise实例,用于获取异步返回结果。 | + | Promise<void> | Promise对象。无返回结果的Promise对象。 | + +**错误码:** + + | 错误码ID | 错误信息| + | ------- | -------| + | 201 | permission denied. | + | 401 | the parameter check failed. | + | 12300001 | system service exception. | + | 12300002 | invalid accountInfo. | **示例:** ```js @@ -225,7 +259,7 @@ setOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCallback<void>): void -更新分布式帐号信息,使用callback回调异步返回结果。 +更新分布式帐号信息。使用callback异步回调。 > **说明:** 从API version 9开始废弃,建议使用[setOsAccountDistributedInfo](#setosaccountdistributedinfo9) > > 从 API version 7开始支持。 @@ -239,7 +273,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | accountInfo | [DistributedInfo](#distributedinfo) | 是 | 分布式帐号信息。 | - | callback | AsyncCallback<void> | 是 | 更新分布式帐号信息的回调。 | + | callback | AsyncCallback<void> | 是 | 回调函数。当更新分布式帐号信息成功时,err为undefined,否则为错误对象。 | **示例:** ```js @@ -254,7 +288,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo, callback: AsyncCall updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> -更新分布式帐号信息,使用Promise方式异步返回结果。 +更新分布式帐号信息。使用Promise异步回调。 > **说明:** 从API version 9开始废弃,建议使用[setOsAccountDistributedInfo](#setosaccountdistributedinfo9-1) > > 从 API version 7开始支持。 @@ -272,7 +306,7 @@ updateOsAccountDistributedInfo(accountInfo: DistributedInfo): Promise<void> | 类型 | 说明 | | -------- | -------- | - | Promise<void> | Promise实例,用于获取异步返回结果。 | + | Promise<void> | Promise对象。无返回结果的Promise对象。 | **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md b/zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md new file mode 100644 index 0000000000000000000000000000000000000000..02cee1ce3332cd40ed61f674bce5162147c5f4f1 --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedBundle.md @@ -0,0 +1,503 @@ +# distributedBundle模块(JS端SDK接口) + +本模块提供分布式包的管理能力 + +> **说明:** +> +> 本模块首批接口从API version 9 开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + +本模块接口为系统接口。 + +## 导入模块 + +``` +import distributedBundle from '@ohos.bundle.distributedBundle'; +``` + +## 系统能力 + +SystemCapability.BundleManager.DistributedBundleFramework + +## 权限列表 + +| 权限 | 权限等级 | 描述 | +| ------------------------------------------ | ------------ | ------------------ | +| ohos.permission.GET_BUNDLE_INFO_PRIVILEGED | system_basic | 可查询所有应用信息 | + +权限等级参考[权限等级说明](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/security/accesstoken-overview.md#%E6%9D%83%E9%99%90%E7%AD%89%E7%BA%A7%E8%AF%B4%E6%98%8E) + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, callback: AsyncCallback\): void; + +以异步方法根据给定的ElementName获取有关远程设备AbilityInfo信息。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | 是 | ElementName信息。 | +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | 是 | 回调函数,操作成功返回err为null,data为RemoteAbilityInfo对象;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName): Promise\; + +以异步方法根据给定的ElementName获取有关远程设备AbilityInfo信息。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | -------------------------------------------- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | 是 | ElementName信息。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise对象,返回RemoteAbilityInfo对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }).then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\, callback: AsyncCallback\>): void; + +以异步方法根据给定的ElementName获取有关远程设备AbilityInfo数组信息。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | 是 | ElementName信息,最大数组长度为10 | +| callback | AsyncCallback\> | 是 | 回调函数,调用成功返回err为null,data为RemoteAbilityInfo数组对象;否则返回错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application1', + abilityName: 'MainAbility1' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ], (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\): Promise\>; + +以异步方法根据给定的ElementName和locale获取有关远程设备AbilityInfo数组信息。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | --------------------------------------------------- | ---- | ----------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | 是 | ElementName信息,最大数组长度为10。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\> | Promise对象,返回RemoteAbilityInfo数组对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ]).then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, locale: string, callback: AsyncCallback\): void; + +以异步方法根据给定的ElementName和locale获取有关远程设备AbilityInfo信息。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | 是 | ElementName信息。 | +| locale | string |是 | 语言地区 | +| callback | AsyncCallback<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | 是 | 回调函数,操作成功返回err为null,data为RemoteAbilityInfo对象;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, 'zh-Hans-CN', (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementName: ElementName, locale: string): Promise\; + +以异步方法根据给定的ElementName和locale获取有关远程设备AbilityInfo信息。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ----------- | -------------------------------------------- | ---- | ----------------------- | +| elementName | [ElementName](js-apis-bundleManager-elementName.md) | 是 | ElementName信息。 | +| locale | string |是 | 语言地区 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\<[RemoteAbilityInfo](js-apis-bundleManager-remoteAbilityInfo.md)> | Promise对象,返回RemoteAbilityInfo对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, 'zh-Hans-CN').then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\, locale: string, callback: AsyncCallback\>): void; + +以异步方法根据给定的ElementName和locale获取有关远程设备AbilityInfo数组信息。使用callback异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | ------------------------------------------------------------ | ---- | -------------------------------------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | 是 | ElementName信息,最大数组长度为10 | +| locale | string |是 | 语言地区 | +| callback | AsyncCallback\> | 是 | 回调函数,调用成功返回err为null,data为RemoteAbilityInfo数组对象;否则返回错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application1', + abilityName: 'MainAbility1' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ], 'zh-Hans-CN', (err, data) => { + if (err) { + console.error('Operation failed:' + JSON.stringify(err)); + } else { + console.info('Operation succeed:' + JSON.stringify(data)); + } + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` + +## distributedBundle.getRemoteAbilityInfo + +getRemoteAbilityInfo(elementNames: Array\, locale: string): Promise\>; + +以异步方法根据给定的ElementName和locale获取有关远程设备AbilityInfo数组信息。使用Promise异步回调。 + +**系统接口:** 此接口为系统接口。 + +**需要权限:** ohos.permission.GET_BUNDLE_INFO_PRIVILEGED + +**系统能力:** SystemCapability.BundleManager.DistributedBundleFramework + +**参数:** + +| 名称 | 类型 | 必填 | 描述 | +| ------------ | --------------------------------------------------- | ---- | ----------------------- | +| elementNames | Array<[ElementName](js-apis-bundleManager-elementName.md)> | 是 | ElementName信息,最大数组长度为10。 | +| locale | string |是 | 语言地区 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------------------ | --------------------------------- | +| Promise\> | Promise对象,返回RemoteAbilityInfo数组对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[ohos.bundle错误码](../errorcodes/errcode-bundle.md)。 + +| 错误码ID | 错误新息(此处仅提供错误抛出的关键信息) | +|---------------|-------------------------| +| 201 | Permission denied.| +| 401 | The parameter check failed. | +| 801 | Capability not supported. | +| 17700001 | The specified bundle name is not found | +| 17700003 | The specified ability name is not found. | +| 17700007 | The specified device id is not found. | +| 17700027 | The distributed service is not running. | + +**示例:** + +```js +try { + distributedBundle.getRemoteAbilityInfo( + [ + { + deviceId: '1', + bundleName: 'com.example.application', + abilityName: 'MainAbility' + }, + { + deviceId: '1', + bundleName: 'com.example.application2', + abilityName: 'MainAbility' + } + ], 'zh-Hans-CN').then(data => { + console.info('Operation succeed:' + JSON.stringify(data)); + }).catch(err => { + console.error('Operation failed:' + JSON.stringify(err)); + }); +} catch (err) { + console.error('Operation failed:' + JSON.stringify(err)); +} +``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md b/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md index 4cba4c6d6ea8c76ad4e8167305ffa1dd30fd79e9..589acab75c3572a816b91095edeac82ed06fb051 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-distributedMissionManager.md @@ -48,7 +48,7 @@ registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback, console.log('NotifyNetDisconnect state ' + JSON.stringify(state)); } var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; var options = { notifyMissionsChanged: NotifyMissionsChanged, @@ -104,7 +104,7 @@ registerMissionListener(parameter: MissionDeviceInfo, options: MissionCallback): console.log('NotifyNetDisconnect state ' + JSON.stringify(state)); } var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; var options = { notifyMissionsChanged: NotifyMissionsChanged, @@ -145,7 +145,7 @@ unRegisterMissionListener(parameter: MissionDeviceInfo, callback: AsyncCallback& ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; try { distributedMissionManager.unRegisterMissionListener(parameter, (error) => { @@ -186,7 +186,7 @@ unRegisterMissionListener(parameter: MissionDeviceInfo): Promise<void> ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; try { distributedMissionManager.unRegisterMissionListener(parameter) @@ -221,7 +221,7 @@ startSyncRemoteMissions(parameter: MissionParameter, callback: AsyncCallback< ```ts var parameter = { - deviceId: remoteDeviceId, + deviceId: "", fixConflict: false, tag: 0 }; @@ -263,7 +263,7 @@ startSyncRemoteMissions(parameter: MissionParameter): Promise<void> ```ts var parameter = { - deviceId: remoteDeviceId, + deviceId: "", fixConflict: false, tag: 0 }; @@ -300,7 +300,7 @@ stopSyncRemoteMissions(parameter: MissionDeviceInfo, callback: AsyncCallback< ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; try { distributedMissionManager.stopSyncRemoteMissions(parameter, (error) => { @@ -340,7 +340,7 @@ stopSyncRemoteMissions(parameter: MissionDeviceInfo): Promise<void> ```ts var parameter = { - deviceId: remoteDeviceId + deviceId: "" }; try { distributedMissionManager.stopSyncRemoteMissions(parameter) @@ -376,10 +376,10 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback, callba ```ts var parameter = { - srcDeviceId: localDeviceId - dstDeviceId: remoteDeviceId - missionId: remoteMissionId - wantParams: {"key": "value"} + srcDeviceId: "", + dstDeviceId: "", + missionId: 1, + wantParam: {"key": "value"} }; function OnContinueDone(resultCode) { console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); @@ -426,10 +426,10 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promi ```ts var parameter = { - srcDeviceId: localDeviceId - dstDeviceId: remoteDeviceId - missionId: remoteMissionId - wantParams: {"key": "value"} + srcDeviceId: "", + dstDeviceId: "", + missionId: 1, + wantParam: {"key": "value"} }; function OnContinueDone(resultCode) { console.log('OnContinueDone resultCode: ' + JSON.stringify(resultCode)); @@ -501,8 +501,8 @@ continueMission(parameter: ContinueDeviceInfo, options: ContinueCallback): Promi | -------- | ------ | ---- | ---- | ------- | | srcDeviceId | string | 是 | 是 | 表示任务迁移源设备ID。 | | dstDeviceId | string | 是 | 是 | 表示任务迁移目标设备ID。 | -| missionId | string | 是 | 是 | 表示任务ID。 | -| wantParams | {[key: string]: any} | 是 | 是 | 表示扩展参数。 | +| missionId | number | 是 | 是 | 表示任务ID。 | +| wantParam | {[key: string]: any} | 是 | 是 | 表示扩展参数。 | ## ContinueCallback diff --git a/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md b/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md index c08edb1e7bb45081b84d82818a31f528bd97491d..0f302eb0e6eccd14e73db49b92686113e443e290 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md +++ b/zh-cn/application-dev/reference/apis/js-apis-faultLogger.md @@ -39,10 +39,12 @@ import faultLogger from '@ohos.faultLogger' | summary | string | 故障的概要 | | fullLog | string | 故障日志全文 | -## faultLogger.querySelfFaultLog +## faultLogger.querySelfFaultLog(deprecated) querySelfFaultLog(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void +> **说明:** 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9)替代。 + 获取当前进程故障信息,该方法通过回调方式获取故障信息数组,故障信息数组内最多上报10份故障信息。 **系统能力:** SystemCapability.HiviewDFX.Hiview.FaultLogger @@ -79,10 +81,12 @@ function queryFaultLogCallback(error, value) { faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); ``` -## faultLogger.querySelfFaultLog +## faultLogger.querySelfFaultLog(deprecated) querySelfFaultLog(faultType: FaultType) : Promise<Array<FaultLogInfo>> +> **说明:** 从 API Version 9 开始废弃,建议使用[faultLogger.query](#faultloggerquery9-1)替代。 + 获取当前进程故障信息,该方法通过Promise方式返回故障信息数组,故障信息数组内最多上报10份故障信息。 **系统能力:** SystemCapability.HiviewDFX.Hiview.FaultLogger @@ -106,18 +110,125 @@ async function getLog() { let value = await faultLogger.querySelfFaultLog(faultLogger.FaultType.JS_CRASH); if (value) { console.info("value length is " + value.length); - let len = value.length; - for (let i = 0; i < len; i++) { - console.info("log: " + i); - console.info("Log pid: " + value[i].pid); - console.info("Log uid: " + value[i].uid); - console.info("Log type: " + value[i].type); - console.info("Log timestamp: " + value[i].timestamp); - console.info("Log reason: " + value[i].reason); - console.info("Log module: " + value[i].module); - console.info("Log summary: " + value[i].summary); - console.info("Log text: " + value[i].fullLog); - } + let len = value.length; + for (let i = 0; i < len; i++) { + console.info("log: " + i); + console.info("Log pid: " + value[i].pid); + console.info("Log uid: " + value[i].uid); + console.info("Log type: " + value[i].type); + console.info("Log timestamp: " + value[i].timestamp); + console.info("Log reason: " + value[i].reason); + console.info("Log module: " + value[i].module); + console.info("Log summary: " + value[i].summary); + console.info("Log text: " + value[i].fullLog); + } + } +} +``` + +## faultLogger.query9+ + +query(faultType: FaultType, callback: AsyncCallback<Array<FaultLogInfo>>) : void + +获取当前进程故障信息,该方法通过回调方式获取故障信息数组,故障信息数组内最多上报10份故障信息。 + +**系统能力:** SystemCapability.HiviewDFX.Hiview.FaultLogger + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| faultType | [FaultType](#faulttype) | 是 | 输入要查询的故障类型。 | +| callback | AsyncCallbackArray<Array<[FaultLogInfo](#faultloginfo)>> | 是 | 回调函数,在回调函数中获取故障信息数组。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常,error返回错误提示字符串 + +**错误码:** + +以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 + +| 错误码ID | 错误信息(此处仅提供错误抛出的关键信息) | +| --- | --- | +| 10600001 | The service is not running or broken | + +**示例:** + +```js +function queryFaultLogCallback(error, value) { + if (error) { + console.info('error is ' + error); + } else { + console.info("value length is " + value.length); + let len = value.length; + for (let i = 0; i < len; i++) { + console.info("log: " + i); + console.info("Log pid: " + value[i].pid); + console.info("Log uid: " + value[i].uid); + console.info("Log type: " + value[i].type); + console.info("Log timestamp: " + value[i].timestamp); + console.info("Log reason: " + value[i].reason); + console.info("Log module: " + value[i].module); + console.info("Log summary: " + value[i].summary); + console.info("Log text: " + value[i].fullLog); + } + } +} +try { + faultLogger.query(faultLogger.FaultType.JS_CRASH, queryFaultLogCallback); +} catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); +} +``` + +## faultLogger.query9+ + +query(faultType: FaultType) : Promise<Array<FaultLogInfo>> + +获取当前进程故障信息,该方法通过Promise方式返回故障信息数组,故障信息数组内最多上报10份故障信息。 + +**系统能力:** SystemCapability.HiviewDFX.Hiview.FaultLogger + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| faultType | [FaultType](#faulttype) | 是 | 输入要查询的故障类型。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<Array<[FaultLogInfo](#faultloginfo)>> | Promise实例,可以在其then()方法中获取故障信息实例,也可以使用await。
- value拿到故障信息数组;value为undefined表示获取过程中出现异常 | + +**错误码:** + +以下错误码的详细介绍参见[ohos.faultLogger错误码](../errorcodes/errorcode-faultlogger.md)。 + +| 错误码ID | 错误信息(此处仅提供错误抛出的关键信息) | +| --- | --- | +| 10600001 | The service is not running or broken | + +**示例:** + +```js +async function getLog() { + try { + let value = await faultLogger.query(faultLogger.FaultType.JS_CRASH); + if (value) { + console.info("value length is " + value.length); + let len = value.length; + for (let i = 0; i < len; i++) { + console.info("log: " + i); + console.info("Log pid: " + value[i].pid); + console.info("Log uid: " + value[i].uid); + console.info("Log type: " + value[i].type); + console.info("Log timestamp: " + value[i].timestamp); + console.info("Log reason: " + value[i].reason); + console.info("Log module: " + value[i].module); + console.info("Log summary: " + value[i].summary); + console.info("Log text: " + value[i].fullLog); + } + } + } catch (err) { + console.error(`code: ${err.code}, message: ${err.message}`); } } ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-filemanager.md b/zh-cn/application-dev/reference/apis/js-apis-filemanager.md deleted file mode 100644 index 66552c4a933cbf9503ed39bf0eea6e3ee82fcf2b..0000000000000000000000000000000000000000 --- a/zh-cn/application-dev/reference/apis/js-apis-filemanager.md +++ /dev/null @@ -1,282 +0,0 @@ -# 公共文件访问与管理 - -该模块提供公共文件访问和管理的服务接口,向下对接底层文件管理服务,如媒体库、外卡管理;向上对应用程序提供公共文件查询、创建的能力。 - ->![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> ->- 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ->- 本模块接口为系统接口,三方应用不支持调用,当前只支持filepicker调用。 - -## 导入模块 - -```js -import filemanager from '@ohos.fileManager'; -``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}) : Promise<FileInfo[]> - -以异步方法获取第一层相册,目录信息。使用promise形式返回结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | --- | --- | --- | -- | - | options | Object | 否 | 支持如下选项:
- dev,[DevInfo](#devinfo)类型,不填默认dev = {name: "local"}, 当前仅支持设备'local' | - -**返回值:** - - | 类型 | 说明 | - | --- | -- | - | Promise<[FileInfo](#fileinfo)[]> | 第一层目录相册信息 | - -**示例:** - - ```js - filemanager.getRoot().then((fileInfos) => { - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }).catch((err) => { - console.log(err) - }); - ``` - -## filemanager.getRoot - -getRoot(options? : {dev? : DevInfo}, callback : AsyncCallback<FileInfo[]>) : void - -以异步方法获取第一层相册,目录信息。使用callback形式返回结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | ------------------------- | ---- | ----------------------------- | - | options | Object | 否 | 支持如下选项:
- dev,[DevInfo](#devinfo)类型,不填默认dev = {name: "local"}, 当前仅支持设备'local' | - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - -**示例:** - - ```js - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.getRoot(options, (err, fileInfos)=>{ - for (var i = 0; i < fileInfos.length; i++) { - console.log("files:"+JSON.stringify(fileInfos)); - } - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}) : Promise<FileInfo[]> - -以异步方法获取第二层相册,文件信息。使用promise形式返回结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | --- | --- | --- | -- | - | path | string | 是 | 待查询目录uri | - | type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | - | options | Object | 否 | 支持如下选项:
- dev,[DevInfo](#devinfo)类型,不填默认dev = {name: "local"}, 当前仅支持设备'local'。
- offset,number类型,待查询文件偏移个数。
- count,number类型,待查询文件个数。 | - -**返回值:** - - | 类型 | 说明 | - | --- | -- | - | Promise<FileInfo[]> | 文件信息 | - -**异常:** - - | 错误名称 | 错误类型 | 错误码 |说明 | - | --- | -- | --- | -- | - | 对应的目录、相册不存在 | No such file or directory | 2 | uri对应的目录、相册不存在 | - | 获取FMS服务失败 | No such process | 3 | 获取FMS服务失败 | - | path对应uri不是相册、目录 | Not a directory | 20 | path对应uri不是相册、目录 | - -**示例:** - - ```js - // 获取目录下所有文件,通过getRoot获取的目录uri - filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "file_folder"); - let path = file.path; - filemanager.listFile(path, "file").then((files) => { - console.log("files:" + JSON.stringify(files)); - }).catch((err) => { - console.log("failed to get files" + err); - }); - }).catch((err) => { - console.log("failed to get root" + err); - }); - ``` - -## filemanager.listFile - -listFile(path : string, type : string, options? : {dev? : DevInfo, offset? : number, count? : number}, callback : AsyncCallback<FileInfo[]>) : void - -以异步方法获取第二层相册,文件信息。使用callback形式返回结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------- | ---- | ------------------------------------------------------------ | -| path | string | 是 | 待查询目录uri | -| type | string | 是 | 待查询文件类型, 支持以下类型 "file", "image", "audio", "video" | -| options | Object | 否 | 支持如下选项:
- dev,[DevInfo](#devinfo)类型,不填默认dev = {name: "local"}, 当前仅支持设备'local'。
- offset,number类型,待查询文件偏移个数。
- count,number类型,待查询文件个数。 | -| callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - -**异常:** - -| 错误名称 | 错误类型 | 错误码 | 说明 | -| ------------------------- | ------------------------- | ------ | ------------------------- | -| 对应的目录、相册不存在 | No such file or directory | 2 | uri对应的目录、相册不存在 | -| 获取FMS服务失败 | No such process | 3 | 获取FMS服务失败 | -| path对应uri不是相册、目录 | Not a directory | 20 | path对应uri不是相册、目录 | - -**示例:** - -```js -// 获取目录下所有文件,通过getRoot获取的目录uri -filemanager.getRoot().then((fileInfos) => { - let file = fileInfos.find(item => item.name == "image_album"); - let path = file.path; - filemanager.listFile(path, "image",function(err, files){ - console.log("files:" + JSON.stringify(files)); - }) -}).catch((err) => { - console.log("failed to get root" + err); -}); -``` - -## filemanager.createFile - -createFile(path : string, filename : string, options? : {dev? : DevInfo}) : Promise<string> - -以异步方法创建文件到指定路径,返回文件uri。使用promise形式返回结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | --- | --- | --- | -- | - | filename | string | 是 | 待创建的文件名 | - | path | string | 是 | 待保存目的相册uri | - | options | Object | 否 | 支持如下选项:
- dev,[DevInfo](#devinfo)类型,不填默认dev = {name: "local"}, 当前仅支持设备'local' | - -**返回值:** - -| 类型 | 说明 | -| --- | -- | -| Promise<string> | 文件uri | - -**异常:** - - | 错误名称 | 错误类型 | 错误码 |说明 | - | --- | -- | --- | -- | - | 创建文件不允许 | Operation not permitted | 1 | 已有重名文件 | - | 对应的目录、相册不存在 | No such file or directory | 2 | uri对应的目录、相册不存在 | - | 获取FMS服务失败 | No such process | 3 | 获取FMS服务失败 | - | path对应uri不是相册、目录 | Not a directory | 20 | path对应uri不是相册、目录 | - -**示例:** - - ```js - // 创建文件,返回文件uri - let media_path = "" // 通过listFile、getRoot获取的文件uri - let name = "xxx.jpg" // 待保存文件的后缀 - filemanager.createFile(media_path, name).then((uri) => { - // 返回uri给应用 - console.log("file uri:"+uri); - }).catch((err) => { - console.log(err); - }); - ``` - -## filemanager.createFile - -createFile(path : string, filename: string, options? : {dev? : DevInfo}, callback : AsyncCallback<string>) : void - -以异步方法创建文件到指定路径,返回文件uri。使用callback形式返回结果。 - -**系统能力**:SystemCapability.FileManagement.UserFileService - -**参数:** - - | 参数名 | 类型 | 必填 | 说明 | - | -------- | ------------------------- | ---- | ----------------------------- | - | filename | string | 是 | 待创建的文件名 | - | path | string | 是 | 待保存目的相册uri | - | options | Object | 否 | 支持如下选项:
- dev,[DevInfo](#devinfo)类型,不填默认dev = {name: "local"}, 当前仅支持设备'local' | - | callback | AsyncCallback<[FileInfo](#fileinfo)[]> | 是 | 异步获取文件的信息之后的回调 | - -**异常:** - - | 错误名称 | 错误类型 | 错误码 | 说明 | - | ------------------------- | ------------------------- | ------ | ------------------------- | - | 创建文件不允许 | Operation not permitted | 1 | 已有重名文件 | - | 对应的目录、相册不存在 | No such file or directory | 2 | uri对应的目录、相册不存在 | - | 获取FMS服务失败 | No such process | 3 | 获取FMS服务失败 | - | path对应uri不是相册、目录 | Not a directory | 20 | path对应uri不是相册、目录 | - -**示例:** - - ```js - // 创建文件,返回文件uri - // 通过listFile、getRoot获取的文件uri - let media_path = "" - // 待保存文件的后缀 - let name = "xxx.jpg" - let options = { - "dev":{ - "name":"local" - } - }; - filemanager.createFile(media_path, name, options, function(err, uri) { - // 返回uri给应用 - console.log("file uri:"+uri); - }); - - ``` - -## FileInfo -文件信息类型,通过getRoot, listFile等接口返回的类型。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileService。 - -### 属性 - -| 参数名 | 类型 | 可读 | 可写 | 说明 | -| --- | -- | -- | -- | -- | -| name | string | 是 | 否 | 文件名称 | -| path | string | 是 | 否 | 文件Uri | -| type | string | 是 | 否 | 文件类型 | -| size | number | 是 | 否 | 文件大小 | -| addedTime | number | 是 | 否 | 媒体插入时间 | -| modifiedTime | number | 是 | 否 | 媒体修改时间 | - -## DevInfo - -设备类型,配置接口访问的设备类型。 - -**系统能力**:以下各项对应的系统能力均为SystemCapability.FileManagement.UserFileService。 - -### 属性 - -| 参数名 | 类型 | 可读 | 可写 | 说明 | -| ------ | ------ | ---- | ---- | -------- | -| name | string | 是 | 是 | 设备名称 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md b/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md index 64bcef93dbd8f297263d84e1f00c7278c0b68430..b2aa4eead87307c8f41758558d1f6c851dfabe67 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hiappevent.md @@ -3,7 +3,8 @@ 本模块提供了应用事件打点能力,包括对打点数据的落盘,以及对打点功能的管理配置。 > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** -> 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> - 本模块接口从API version 9开始废弃,建议使用新接口[@ohos.hiviewdfx.hiAppEvent](js-apis-hiviewdfx-hiappevent)替代。 +> - 本模块首批接口从API version 7开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 @@ -16,13 +17,9 @@ import hiAppEvent from '@ohos.hiAppEvent'; 开发者在使用应用事件打点功能前,需要首先了解应用事件相关的参数规格定义。 -**事件领域** - -事件领域为string类型,字符串非空且长度在32个字符以内,有效的字符是0-9、a-z、下划线,不能以下划线开头。 - **事件名称** -事件名称为string类型,字符串非空且长度在48个字符以内,有效的字符是0-9、a-z、下划线,不能以下划线开头。 +事件名称为string类型,字符串非空且长度在48个字符以内,有效的字符是0-9、a-z、下划线,只能以小写字母开头,不能以下划线结尾。 **事件类型** @@ -32,7 +29,7 @@ import hiAppEvent from '@ohos.hiAppEvent'; 事件参数为object类型,key为事件的参数名称,value为事件的参数值,其规格定义如下: -- 参数名为string类型,字符串非空且长度在16个字符以内,有效的字符是0-9、a-z、下划线,不能以下划线开头或结尾; +- 参数名为string类型,字符串非空且长度在16个字符以内,有效的字符是0-9、a-z、下划线,只能以小写字母开头,不能以下划线结尾; - 参数值支持string、number、boolean、Array类型; - 参数值为string类型时,其长度需在8*1024个字符以内,超出会做截断处理; - 参数值为Array类型时,Array中的元素类型只能全为string、number、boolean中的一种,且元素个数需在100以内,超出会做丢弃处理; @@ -46,20 +43,10 @@ import hiAppEvent from '@ohos.hiAppEvent'; - 返回值大于0,表示事件校验存在异常参数,在忽略异常参数后将事件落盘到事件文件; - 返回值小于0,表示事件校验失败,不将事件落盘到事件文件。 -**订阅回调** - -开发者在调用事件订阅方法后,可以在订阅回调函数中对订阅数据进行处理,其入参定义如下: - -- curRow:返回的订阅事件数量; -- curSize:返回的订阅事件数据大小,单位为byte; -- holder:返回的订阅事件数据持有者,可以通过其对订阅事件进行处理。 - -## hiAppEvent.write(deprecated) +## hiAppEvent.write write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback<void>): void -> **说明:** 从 API Version 9 开始废弃,建议使用[hiAppEvent.write](#hiappeventwrite9)替代。 - 应用事件打点方法,将事件写入到当天的事件文件中,使用callback方式作为异步回调。 **系统能力:** SystemCapability.HiviewDFX.HiAppEvent @@ -89,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> -> **说明:** 从 API Version 9 开始废弃,建议使用[hiAppEvent.write](#hiappeventwrite9-1)替代。 - 应用事件打点方法,将事件写入到当天的事件文件中,使用Promise方式作为异步回调。 **系统能力:** SystemCapability.HiviewDFX.HiAppEvent @@ -126,97 +111,6 @@ hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str }); ``` -## hiAppEvent.write9+ - -write(info: [AppEventInfo](#appeventinfo9), callback: AsyncCallback<void>): void - -应用事件打点方法,将事件写入到当天的事件文件中,可接收[AppEventInfo](#appeventinfo9)类型的事件对象,使用callback方式作为异步回调。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------ | ---- | -------------- | -| info | [AppEventInfo](#appeventinfo9) | 是 | 应用事件对象。 | -| callback | AsyncCallback<void> | 否 | 事件回调函数。 | - -**示例:** - -```js -hiAppEvent.write({ - domain: "test_domain", - name: "test_event", - eventType: hiAppEvent.EventType.FAULT, - params: { - int_data: 100, - str_data: "strValue" - } -}, (err, value) => { - if (err) { - // 事件写入异常:事件存在异常参数时忽略异常参数后继续写入,或者事件校验失败时不执行写入 - console.error(`failed to write event because ${err.code}`); - return; - } - - // 事件写入正常 - console.log(`success to write event: ${value}`); -}); -``` - -## hiAppEvent.write9+ - -write(info: [AppEventInfo](#appeventinfo9)): Promise<void> - -应用事件打点方法,将事件写入到当天的事件文件中,可接收[AppEventInfo](#appeventinfo9)类型的事件对象,使用Promise方式作为异步回调。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------------------------ | ---- | -------------- | -| info | [AppEventInfo](#appeventinfo9) | 是 | 应用事件对象。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise对象,可以在其then()、catch()方法中分别对事件写入成功、写入异常的情况进行异步处理。 | - -**示例:** - -```js -hiAppEvent.write({ - domain: "test_domain", - name: "test_event", - eventType: hiAppEvent.EventType.FAULT, - params: { - int_data: 100, - str_data: "strValue" - } -}).then((value) => { - // 事件写入正常 - console.log(`success to write event: ${value}`); -}).catch((err) => { - // 事件写入异常:事件存在异常参数时忽略异常参数后继续写入,或者事件校验失败时不执行写入 - console.error(`failed to write event because ${err.code}`); -}); -``` - -## AppEventInfo9+ - -此接口提供了应用事件信息的参数选项。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -| 名称 | 参数类型 | 必填 | 说明 | -| --------- | ----------------------- | ---- | ---------- | -| domain | string | 是 | 事件领域。 | -| name | string | 是 | 事件名称。 | -| eventType | [EventType](#eventtype) | 是 | 事件类型。 | -| params | object | 是 | 事件参数。 | - ## hiAppEvent.configure configure(config: ConfigOption): boolean @@ -262,225 +156,6 @@ hiAppEvent.configure({ | disable | boolean | 否 | 应用打点功能开关。配置值为true表示关闭打点功能,false表示不关闭打点功能。 | | maxStorage | string | 否 | 打点数据本地存储文件所在目录的配额大小,默认限额为“10M”。所在目录大小超出限额后会对目录进行清理操作,会按从旧到新的顺序逐个删除打点数据文件,直到目录大小不超出限额时停止。 | -## hiAppEvent.addWatcher9+ - -addWatcher(watcher: [Watcher](#watcher9)): [AppEventPackageHolder](#appeventpackageholder9) - -添加应用事件订阅者。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------------------- | ---- | ---------------- | -| watcher | [Watcher](#watcher9) | 是 | 应用事件订阅者。 | - -**返回值:** - -| 类型 | 说明 | -| ------------------------------------------------ | ------------------------------------ | -| [AppEventPackageHolder](#appeventpackageholder9) | 订阅数据持有者,订阅失败时返回null。 | - -**示例:** - -```js -// 1. 如果订阅者传入了回调的相关参数,则可以选择在自动触发的回调函数中对订阅事件进行处理 -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. 如果订阅者未传入回调的相关参数,则可以选择使用返回的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 - -移除应用事件订阅者。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| ------- | -------------------- | ---- | ---------------- | -| watcher | [Watcher](#watcher9) | 是 | 应用事件订阅者。 | - -**示例:** - -```js -// 1. 定义一个应用事件订阅者 -let watcher = { - name: "watcher1", -} - -// 2. 开始订阅事件 -hiAppEvent.addWatcher(watcher); - -// 3. 取消订阅事件 -hiAppEvent.removeWatcher(watcher); -``` - -## Watcher9+ - -此接口提供了应用事件订阅者的参数选项。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -| 名称 | 参数类型 | 必填 | 说明 | -| ---------------- | ------------------------------------------------------------ | ---- | -------------------------------- | -| name | string | 是 | 订阅者名称,用于唯一标识订阅者。 | -| triggerCondition | [TriggerCondition](#triggercondition9) | 否 | 订阅回调触发条件。 | -| appEventFilters | [AppEventFilter](#appeventfilter9)[] | 否 | 订阅过滤条件。 | -| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder9)) => void | 否 | 订阅回调函数 。 | - -## TriggerCondition9+ - -此接口提供了订阅者回调触发条件的参数选项。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -| 名称 | 参数类型 | 必填 | 说明 | -| ------- | -------- | ---- | -------------------------------------- | -| row | number | 否 | 满足触发回调的事件总数。 | -| size | number | 否 | 满足触发回调的事件总大小,单位为byte。 | -| timeOut | number | 否 | 满足触发回调的定时时长,单位为30s。 | - -## AppEventFilter9+ - -此接口提供了订阅者过滤应用事件的参数选项。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -| 名称 | 参数类型 | 必填 | 说明 | -| ---------- | ------------------------- | ---- | ------------------------ | -| domain | string | 是 | 需要订阅的事件领域。 | -| eventTypes | [EventType](#eventtype)[] | 否 | 需要订阅的事件类型集合。 | - -## AppEventPackageHolder9+ - -订阅数据持有者类,用于对订阅事件进行处理。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -### constructor9+ - -constructor(watcherName: string); - -类构造函数,在添加订阅时会被系统自动调用来创建一个订阅数据持有者对象并返回给开发者。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**示例:** - -```js -let holder = hiAppEvent.addWatcher({ - name: "watcher", -}); -``` - -### setSize9+ - -setSize(size: number): void - -设置每次取出的应用事件包的数据大小阈值,单位为byte,默认值为512*1024。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**示例:** - -```js -let holder = hiAppEvent.addWatcher({ - name: "watcher", -}); -holder.setSize(1000); -``` - -### takeNext9+ - -takeNext(): [AppEventPackage](#appeventpackage9) - -根据设置的数据大小阈值来取出订阅事件数据,当订阅事件数据全部被取出时返回null作为标识。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**示例:** - -```js -let holder = hiAppEvent.addWatcher({ - name: "watcher", -}); -let eventPkg = holder.takeNext(); -``` - -## AppEventPackage9+ - -此接口提供了订阅返回的应用事件包的参数定义。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -| 名称 | 参数类型 | 说明 | -| --------- | -------- | ------------------------------ | -| packageId | number | 事件包ID,从0开始自动递增。 | -| row | number | 事件包的事件数量。 | -| size | number | 事件包的数据大小,单位为byte。 | -| data | string[] | 事件包的事件信息。 | - -## hiAppEvent.clearData9+ - -clearData(): void - -应用打点数据清理方法,将应用存储在本地的打点数据进行清除。 - -**系统能力:** SystemCapability.HiviewDFX.HiAppEvent - -**示例:** - -```js -hiAppEvent.clearData(); -``` - ## EventType diff --git a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md index d6bdbe5f37e074f8f5cb1611ae8ea5454de65eb9..2d81b2b7faef6ee269588dcadf9889bf59ce6da2 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hidebug.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hidebug.md @@ -162,10 +162,12 @@ getCpuUsage(): number let cpuUsage = hidebug.getCpuUsage(); ``` -## hidebug.startProfiling +## hidebug.startProfiling(deprecated) startProfiling(filename : string) : void +> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9)替代。 + 启动虚拟机Profiling方法跟踪,`startProfiling()`方法的调用需要与`stopProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -188,10 +190,12 @@ hidebug.stopProfiling(); -## hidebug.stopProfiling +## hidebug.stopProfiling(deprecated) stopProfiling() : void +> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9)替代。 + 停止虚拟机Profiling方法跟踪,`stopProfiling()`方法的调用需要与`startProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -206,10 +210,12 @@ hidebug.startProfiling("cpuprofiler-20220216"); hidebug.stopProfiling(); ``` -## hidebug.dumpHeapData +## hidebug.dumpHeapData(deprecated) dumpHeapData(filename : string) : void +> **说明:** 从 API Version 9 开始废弃,建议使用[hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9)替代。 + 虚拟机堆导出。 **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -228,11 +234,11 @@ hidebug.dumpHeapData("heap-20220216"); ## hidebug.getServiceDump9+ -getServiceDump(serviceid : number) : string +getServiceDump(serviceid : number, fd : number, args : Array) : void 获取系统服务信息。 -此接口为系统接口,三方应用不可用。 +**需要权限**: ohos.permission.DUMP **系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug @@ -241,16 +247,115 @@ getServiceDump(serviceid : number) : string | 参数名 | 类型 | 必填 | 说明 | | -------- | ------ | ---- | ------------------------------------------------------------ | | serviceid | number | 是 | 基于该用户输入的service id获取系统服务信息。| +| fd | number | 是 | 文件描述符,该接口会往该fd中写入数据。| +| args | Array | 是 | 系统服务的Dump接口所对应的参数列表。| -**返回值:** -| 类型 | 说明 | -| ------ | -------------------------- | -| string | 返回dump的service信息文件的绝对路径。 | +**示例:** + +```js +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 + +启动虚拟机Profiling方法跟踪,`startJsCpuProfiling()`方法的调用需要与`stopJsCpuProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | 是 | 用户自定义的profiling文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.json`文件。 | + +**示例:** + +```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 + +停止虚拟机Profiling方法跟踪,`startJsCpuProfiling()`方法的调用需要与`stopJsCpuProfiling()`方法的调用一一对应,先开启后关闭,严禁使用`start->start->stop`,`start->stop->stop`,`start->start->stop->stop`等类似的顺序调用。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | 是 | 用户自定义的profiling文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.json`文件。 | + +**示例:** + +```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 + +虚拟机堆导出。 + +**系统能力:** SystemCapability.HiviewDFX.HiProfiler.HiDebug + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------ | ---- | ------------------------------------------------------------ | +| filename | string | 是 | 用户自定义的虚拟机堆文件名,根据传入的`filename`,将在应用的`files`目录生成`filename.heapsnapshot`文件。 | **示例:** ```js -let serviceId = 10; -let pathName = hidebug.getServiceDump(serviceId); +import hidebug from '@ohos.hidebug' + +try { + hidebug.dumpJsHeapData("heapData"); +} catch (error) { + console.info(error.code) + console.info(error.message) +} ``` \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md b/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md index 1895a0eb1687b281cd3f8fe211f26f850f284f9d..94dd6d732addadbf1f5757c5bc5e6c56bd304de8 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-hisysevent.md @@ -55,6 +55,21 @@ write(info: SysEventInfo, callback: AsyncCallback<void>): void | info | [SysEventInfo](#syseventinfo) | 是 | 系统事件。 | | callback | AsyncCallback<void> | 是 | 回调函数,可以在回调函数中处理接口返回值。
- 0表示事件校验成功,事件正常异步写入事件文件;
- 正值表示事件打点存在异常,但可以正常写入;
- 负值表示事件打点失败。 | +**错误码:** + +以下错误码的详细介绍请参见[系统事件错误码](../errorcodes/errorcode-hisysevent.md)。 + +| 错误码ID | 错误信息 | +| ------- | ----------------------------------------------------------------- | +| 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. | + **示例:** ```js @@ -101,6 +116,21 @@ write(info: SysEventInfo): Promise<void> | ------------------- | ------------------------------------------------------------ | | Promise<void> | Promise实例,可以在其then()、catch()方法中分别对系统事件写入成功、写入异常的回调进行处理。 | +**错误码:** + +以下错误码的详细介绍请参见[系统事件错误码](../errorcodes/errorcode-hisysevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | ---------------------------------------------------------------- | +| 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. | + **示例:** ```js @@ -171,7 +201,7 @@ try { ## hiSysEvent.addWatcher -addWatcher(watcher: Watcher): number +addWatcher(watcher: Watcher): void 订阅系统事件,接收[Watcher](#watcher)类型的对象作为事件参数。 @@ -185,6 +215,15 @@ addWatcher(watcher: Watcher): number | ------ | ----------------------------- | ---- | ------------------------ | | watcher | [Watcher](#watcher) | 是 | 系统事件订阅者对象。 | +**错误码:** + +以下错误码的详细介绍请参见[系统事件错误码](../errorcodes/errorcode-hisysevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | ----------------------------------- | +| 11200101 | Count of watchers is over limit. | +| 11200102 | Count of watch rules is over limit. | + **示例:** ```js @@ -213,7 +252,7 @@ try { ## hiSysEvent.removeWatcher -removeWatcher(watcher: Watcher): number +removeWatcher(watcher: Watcher): void 取消订阅系统事件,接收[Watcher](#watcher)类型的对象作为事件参数。 @@ -224,9 +263,17 @@ removeWatcher(watcher: Watcher): number **参数:** | 参数名 | 类型 | 必填 | 说明 | -| ------ | ------------- | ---- | ------------------------ | +| ------ | ------------- | ---- | ------------------------- | | watcher | [Watcher](#watcher) | 是 | 系统事件订阅者对象。 | +**错误码:** + +以下错误码的详细介绍请参见[系统事件错误码](../errorcodes/errorcode-hisysevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------- | +| 11200201 | The watcher does not exist. | + **示例:** ```js @@ -247,7 +294,7 @@ let watcher = { } } try { - let ret = hiSysEvent.addWatcher(watcher) + hiSysEvent.addWatcher(watcher) hiSysEvent.removeWatcher(watcher) } catch (error) { console.error(`error code: ${error.code}, error msg: ${error.message}`); @@ -290,7 +337,7 @@ try { ## hiSysEvent.query -query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): number +query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): void 查询系统事件。 @@ -306,6 +353,17 @@ query(queryArg: QueryArg, rules: QueryRule[], querier: Querier): number | rules | [QueryRule](#queryrule)[] | 是 | 查询规则数组,每次查询可配置多个查询规则。 | | querier | [Querier](#querier) | 是 | 查询者对象,包含查询结果及结束的相关回调。 | +**错误码:** + +以下错误码的详细介绍请参见[系统事件错误码](../errorcodes/errorcode-hisysevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------------------- | +| 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. | + **示例:** ```js diff --git a/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md new file mode 100644 index 0000000000000000000000000000000000000000..f3dd2e21bc90b44260d70f6d7954bf08136b142a --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md @@ -0,0 +1,477 @@ +# 应用事件打点 + +本模块提供了应用事件打点能力,包括应用事件落盘、应用事件订阅、应用事件清理、打点功能配置等功能。 + +> ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 + + +## 导入模块 + +```js +import hiAppEvent from '@ohos.hiviewdfx.hiAppEvent'; +``` + +## 使用说明 + +开发者在使用应用事件打点功能前,需要首先了解应用事件相关的使用规格。 + +**事件打点回调** + +开发者在调用事件打点方法时,可以在回调函数中对打点结果进行处理,当前支持callback形式和Promise形式的回调。 + +**事件订阅回调** + +开发者在调用事件订阅方法时,可以在订阅回调函数中对订阅数据进行处理,其入参定义如下: + +- curRow:返回的订阅事件数量; +- curSize:返回的订阅事件数据大小,单位为byte; +- holder:返回的订阅事件数据持有者,可以通过其对订阅事件进行处理。 + +## hiAppEvent.write + +write(info: [AppEventInfo](#appeventinfo), callback: AsyncCallback<void>): void + +应用事件打点方法,将事件写入到当天的事件文件中,可接收[AppEventInfo](#appeventinfo)类型的事件对象,使用callback方式作为异步回调。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo) | 是 | 应用事件对象。 | +| callback | AsyncCallback<void> | 否 | 事件回调函数。 | + +**错误码:** + +以下错误码的详细介绍请参见[应用事件打点错误码](../errorcodes/errcode-hiviewdfx-hiappevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------- | +| 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. | + +**示例:** + +```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> + +应用事件打点方法,将事件写入到当天的事件文件中,可接收[AppEventInfo](#appeventinfo)类型的事件对象,使用Promise方式作为异步回调。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo) | 是 | 应用事件对象。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise对象,可以在其then()、catch()方法中分别对事件写入成功、写入异常的情况进行异步处理。 | + +**错误码:** + +以下错误码的详细介绍请参见[应用事件打点错误码](../errorcodes/errcode-hiviewdfx-hiappevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------------------------------- | +| 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. | + +**示例:** + +```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 + +此接口提供了应用事件信息的参数选项。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 参数类型 | 必填 | 说明 | +| --------- | ----------------------- | ---- | ---------- | +| domain | string | 是 | 事件领域。 | +| name | string | 是 | 事件名称。 | +| eventType | [EventType](#eventtype) | 是 | 事件类型。 | +| params | object | 是 | 事件参数。 | + +## hiAppEvent.configure + +configure(config: ConfigOption): void + +应用事件打点配置方法,可用于配置打点开关、文件目录存储限额大小等功能。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ----------------------------- | ---- | ------------------------ | +| config | [ConfigOption](#configoption) | 是 | 应用事件打点配置项对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[应用事件打点错误码](../errorcodes/errcode-hiviewdfx-hiappevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------------------------------- | +| 11103001 | Invalid max storage quota value. | + +**示例:** + +```js +// 配置应用事件打点功能开关 +hiAppEvent.configure({ + disable: true +}); + +// 配置事件文件目录存储限额大小 +hiAppEvent.configure({ + maxStorage: '100M' +}); +``` + +## ConfigOption + +此接口提供了应用事件打点的配置选项。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 参数名 | 类型 | 必填 | 说明 | +| ---------- | ------- | ---- | ------------------------------------------------------------ | +| disable | boolean | 否 | 应用事件打点功能开关。配置值为true表示关闭打点功能,false表示不关闭打点功能。 | +| maxStorage | string | 否 | 打点数据本地存储文件所在目录的配额大小,默认限额为“10M”。所在目录大小超出限额后会对目录进行清理操作,会按从旧到新的顺序逐个删除打点数据文件,直到目录大小不超出限额时停止。 | + +## hiAppEvent.addWatcher + +addWatcher(watcher: [Watcher](#watcher)): [AppEventPackageHolder](#appeventpackageholder) + +添加应用事件订阅者。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher) | 是 | 应用事件订阅者。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------------------------ | ------------------------------------ | +| [AppEventPackageHolder](#appeventpackageholder) | 订阅数据持有者,订阅失败时返回null。 | + +**错误码:** + +以下错误码的详细介绍请参见[应用事件打点错误码](../errorcodes/errcode-hiviewdfx-hiappevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------------------- | +| 11102001 | Invalid watcher name. | +| 11102002 | Invalid filtering event domain. | +| 11102003 | Invalid row value. | +| 11102004 | Invalid size value. | +| 11102005 | Invalid timeout value. | + +**示例:** + +```js +// 1. 如果订阅者传入了回调的相关参数,则可以选择在自动触发的回调函数中对订阅事件进行处理 +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. 如果订阅者未传入回调的相关参数,则可以选择使用返回的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 + +移除应用事件订阅者。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher) | 是 | 应用事件订阅者。 | + +**错误码:** + +以下错误码的详细介绍请参见[应用事件打点错误码](../errorcodes/errcode-hiviewdfx-hiappevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | --------------------- | +| 11102001 | Invalid watcher name. | + +**示例:** + +```js +// 1. 定义一个应用事件订阅者 +let watcher = { + name: "watcher1", +} + +// 2. 开始订阅事件 +hiAppEvent.addWatcher(watcher); + +// 3. 取消订阅事件 +hiAppEvent.removeWatcher(watcher); +``` + +## Watcher + +此接口提供了应用事件订阅者的参数选项。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 参数类型 | 必填 | 说明 | +| ---------------- | ------------------------------------------------------------ | ---- | -------------------------------- | +| name | string | 是 | 订阅者名称,用于唯一标识订阅者。 | +| triggerCondition | [TriggerCondition](#triggercondition) | 否 | 订阅回调触发条件。 | +| appEventFilters | [AppEventFilter](#appeventfilter)[] | 否 | 订阅过滤条件。 | +| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder)) => void | 否 | 订阅回调函数 。 | + +## TriggerCondition + +此接口提供了订阅者回调触发条件的参数选项。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 参数类型 | 必填 | 说明 | +| ------- | -------- | ---- | -------------------------------------- | +| row | number | 否 | 满足触发回调的事件总数。 | +| size | number | 否 | 满足触发回调的事件总大小,单位为byte。 | +| timeOut | number | 否 | 满足触发回调的定时时长,单位为30s。 | + +## AppEventFilter + +此接口提供了订阅者过滤应用事件的参数选项。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 参数类型 | 必填 | 说明 | +| ---------- | ------------------------- | ---- | ------------------------ | +| domain | string | 是 | 需要订阅的事件领域。 | +| eventTypes | [EventType](#eventtype)[] | 否 | 需要订阅的事件类型集合。 | + +## AppEventPackageHolder + +订阅数据持有者类,用于对订阅事件进行处理。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +### constructor + +constructor(watcherName: string); + +类构造函数,在添加订阅时会被系统自动调用来创建一个订阅数据持有者对象并返回给开发者。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**示例:** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +``` + +### setSize + +setSize(size: number): void + +设置每次取出的应用事件包的数据大小阈值,单位为byte,默认值为512*1024。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**错误码:** + +以下错误码的详细介绍请参见[应用事件打点错误码](../errorcodes/errcode-hiviewdfx-hiappevent.md)。 + +| 错误码ID | 错误信息 | +| -------- | ------------------- | +| 11104001 | Invalid size value. | + +**示例:** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +holder.setSize(1000); +``` + +### takeNext + +takeNext(): [AppEventPackage](#appeventpackage) + +根据设置的数据大小阈值来取出订阅事件数据,当订阅事件数据全部被取出时返回null作为标识。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**示例:** + +```js +let holder = hiAppEvent.addWatcher({ + name: "watcher", +}); +let eventPkg = holder.takeNext(); +``` + +## AppEventPackage + +此接口提供了订阅返回的应用事件包的参数定义。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 参数类型 | 说明 | +| --------- | -------- | ------------------------------ | +| packageId | number | 事件包ID,从0开始自动递增。 | +| row | number | 事件包的事件数量。 | +| size | number | 事件包的数据大小,单位为byte。 | +| data | string[] | 事件包的事件信息。 | + +## hiAppEvent.clearData + +clearData(): void + +应用事件打点数据清理方法,将应用存储在本地的打点数据进行清除。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +**示例:** + +```js +hiAppEvent.clearData(); +``` + + +## EventType + +事件类型枚举。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 默认值 | 说明 | +| --------- | ------ | -------------- | +| FAULT | 1 | 故障类型事件。 | +| STATISTIC | 2 | 统计类型事件。 | +| SECURITY | 3 | 安全类型事件。 | +| BEHAVIOR | 4 | 行为类型事件。 | + + +## Event + +此接口提供了所有预定义事件的事件名称常量。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ------------------------- | -------- | ---- | ---- | -------------------- | +| USER_LOGIN | string | 是 | 否 | 用户登录事件。 | +| USER_LOGOUT | string | 是 | 否 | 用户登出事件。 | +| DISTRIBUTED_SERVICE_START | string | 是 | 否 | 分布式服务启动事件。 | + + +## Param + +此接口提供了所有预定义参数的参数名称常量。 + +**系统能力:** SystemCapability.HiviewDFX.HiAppEvent + +| 名称 | 参数类型 | 可读 | 可写 | 说明 | +| ------------------------------- | -------- | ---- | ---- | ------------------ | +| USER_ID | string | 是 | 否 | 用户自定义ID。 | +| DISTRIBUTED_SERVICE_NAME | string | 是 | 否 | 分布式服务名称。 | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | 是 | 否 | 分布式服务实例ID。 | \ No newline at end of file diff --git a/zh-cn/application-dev/reference/apis/js-apis-huks.md b/zh-cn/application-dev/reference/apis/js-apis-huks.md index 6e5a68a050a6095fbe08600ad2065957bf715343..219434083c5c0d52ff918258d8529b5f35297d40 100755 --- a/zh-cn/application-dev/reference/apis/js-apis-huks.md +++ b/zh-cn/application-dev/reference/apis/js-apis-huks.md @@ -99,6 +99,8 @@ import huks from '@ohos.security.huks' 表示错误码的枚举以及对应的错误信息, 错误码表示错误类型,错误信息展示错误详情。 +关于错误码的具体信息,可在[错误码参考文档](../errorcodes/errorcode-huks.md)中查看。 + **系统能力**:SystemCapability.Security.Huks | 类型 | 名称 | 说明 | 错误码 | @@ -122,87 +124,6 @@ import huks from '@ohos.security.huks' | 内存不足 | HUKS_ERR_CODE_INSUFFICIENT_MEMORY | 内存不足。 | 12000014 | | 调用其他系统服务失败 | HUKS_ERR_CODE_CALL_SERVICE_FAILED | 调用其他系统服务失败。 | 12000015 | -错误信息: - -| 类型 | 错误码 | ERROR MESSAGE | 错误信息 | -| ------------------------- | -------- | ------------------------------------------------------------ | ----------------------------------------- | -| 权限 | 201 | Check permission failed. User should request permission first. | 表示没有许可。 | -| 参数 | 401 | Argument is invalid. User should make sure using the correct value. | 表示无效的参数。 | -| 参数 | 401 | Input data is not sufficient. | 表示数据不足。 | -| 参数 | 401 | The buffer is too small. | 表示缓冲区太小。 | -| 参数 | 401 | Parameter is null. User should make sure using the correct value. | 表示空指针。 | -| 参数 | 401 | Public key is invalid. | 表示无效的公钥。 | -| 参数 | 401 | Key info is invalid. | 表示无效的密钥信息。 | -| 参数 | 401 | Queried param does not exist. | 表示参数不存在。 | -| 参数 | 401 | Root key material already exists. | 表示存在新的根密钥材料。 | -| 参数 | 401 | The format of wrapped key data is invalid. | 表示导入加密密钥时,密钥格式错误。 | -| 参数 | 401 | Check get auth type failed. User should add auth type in paramset. | 表示获取身份验证类型失败。 | -| 参数 | 401 | Check get challenge type failed. User should add challenge type in paramset. | 表示获取挑战值类型失败。 | -| 参数 | 401 | Check get access type failed. User should add access type in paramset. | 表示获取访问类型失败。 | -| 参数 | 401 | Check get auth token failed. User should add auth token in paramset. | 表示获取身份验证令牌失败。 | -| 参数 | 401 | Time out param is invalid. User should make sure using the correct value. | 表示超时参数无效 | -| 参数 | 401 | Auth type param is invalid. User should make sure using the correct value. | 表示身份验证类型参数无效。 | -| 参数 | 401 | Challenge type param is invalid. User should make sure using the correct value. | 表示挑战值类型参数无效。 | -| 参数 | 401 | Access type param is invalid. User should make sure using the correct value. | 表示访问类型参数无效。 | -| 参数 | 401 | Auth token param is invalid. User should make sure using the correct value. | 表示身份验证令牌参数无效。 | -| 参数 | 401 | Secure sign type param is invalid. User should make sure using the correct value. | 表示安全符号类型参数无效。 | -| 不支持的API | 801 | This api is not supported in current device. | 不支持的API。 | -| 不支持的功能/特性 | 12000001 | Feature is not support. Please make sure using the correct combination of params. | 功能特性不支持,请输入正确的参数组合。 | -| 不支持的功能/特性 | 12000001 | This user auth type is not supported in current device. | 表示不支持当前用户认证类型的访问控制。 | -| 缺少密钥算法参数 | 12000002 | Check get algorithm failed. User should add algorithm in paramset. | 表示检查获取 ALG 失败。 | -| 缺少密钥算法参数 | 12000002 | Check get key size failed. User should add key size in paramset. | 表示检查获取密钥大小失败。 | -| 缺少密钥算法参数 | 12000002 | Check get padding failed. User should add padding in paramset. | 表示检查获取填充失败。 | -| 缺少密钥算法参数 | 12000002 | Check get purpose failed. User should add purpose in paramset. | 表示检查获取目的失败。 | -| 缺少密钥算法参数 | 12000002 | Check get digest failed. User should add digest in paramset. | 表示检查获取摘要失败。 | -| 缺少密钥算法参数 | 12000002 | Check get mode failed. User should add mode in paramset. | 表示检查获取模式失败。 | -| 缺少密钥算法参数 | 12000002 | Check get nonce failed. User should add nonce in paramset. | 表示检查获取随机数失败。 | -| 缺少密钥算法参数 | 12000002 | Check get aad failed. User should add AAD in paramset. | 表示检查获取 AAD 失败。 | -| 缺少密钥算法参数 | 12000002 | Check get iv failed. User should add iv in paramset. | 表示检查 GET IV 失败。 | -| 缺少密钥算法参数 | 12000002 | Check get aead failed. User should add aead in paramset. | 表示检查获取 AE 标记失败。 | -| 缺少密钥算法参数 | 12000002 | Check get salt failed. User should add salt in paramset. | 表示检查获取SALT失败。 | -| 缺少密钥算法参数 | 12000002 | Check get iteration failed. User should add iteration in paramset. | 表示检查获取迭代失败。 | -| 无效密钥算法参数 | 12000003 | Algorithm param is invalid. User should make sure using the correct value. | 表示无效的算法。 | -| 无效密钥算法参数 | 12000003 | Key size param is invalid. User should make sure using the correct value. | 表示无效的密钥大小。 | -| 无效密钥算法参数 | 12000003 | Padding param is invalid. User should make sure using the correct value. | 表示无效的填充。 | -| 无效密钥算法参数 | 12000003 | Purpose param is invalid. User should make sure using the correct value. | 表示无效的目的。 | -| 无效密钥算法参数 | 12000003 | Mode param is invalid. User should make sure using the correct value. | 表示无效模式。 | -| 无效密钥算法参数 | 12000003 | Digest param is invalid. User should make sure using the correct value. | 表示无效的摘要。 | -| 无效密钥算法参数 | 12000003 | Signture size param is invalid. User should make sure using the correct value. | 表示签名大小无效。 | -| 无效密钥算法参数 | 12000003 | IV param is invalid. User should make sure using the correct value. | 表示无效的 IV。 | -| 无效密钥算法参数 | 12000003 | AAD param is invalid. User should make sure using the correct value. | 表示无效的 AAD。 | -| 无效密钥算法参数 | 12000003 | Nonce param is invalid. User should make sure using the correct value. | 表示无效的随机数。 | -| 无效密钥算法参数 | 12000003 | AE param is invalid. User should make sure using the correct value. | 表示无效的 AE 标签。 | -| 无效密钥算法参数 | 12000003 | Salt param is invalid. User should make sure using the correct value. | 表示无效SALT。 | -| 无效密钥算法参数 | 12000003 | Iteration param is invalid. User should make sure using the correct value. | 表示无效的迭代。 | -| 无效密钥算法参数 | 12000003 | Purpose param is invalid. User should make sure using the correct value. | 表示导入加密密钥时,密钥用途错误。 | -| 文件 | 12000004 | Storage space is insufficient. | 表示存储故障。 | -| 文件 | 12000004 | The value of file size is unexpected. | 表示文件大小失败。 | -| 文件 | 12000004 | Read file failed. | 表示读取文件失败。 | -| 文件 | 12000004 | Write file failed. | 表示写文件失败。 | -| 文件 | 12000004 | Remove file failed. | 表示删除文件失败。 | -| 文件 | 12000004 | Open file failed. | 表示打开文件失败。 | -| 文件 | 12000004 | Close file failed. | 表示关闭文件失败。 | -| 文件 | 12000004 | Make directory failed. | 表示创建目录失败。 | -| 文件 | 12000004 | Read key from file failed, for key fi哦呜le is invalid. | 表示无效的密钥文件。 | -| 通信 | 12000005 | Get message from IPC failed. | 表示IPC 信息失败。 | -| 通信 | 12000005 | IPC communication time out. | 表示通讯超时。 | -| 通信 | 12000005 | IPC init failed. | 表示IPC 初始化失败。 | -| 通信 | 12000005 | IPC async call failed. | IPC异步调用失败。 | -| 算法库操作失败 | 12000006 | Errors occured in crypto engine. | 表示CRYPTO ENGINE错误。 | -| 密钥访问失败-密钥访问失效 | 12000007 | This credential is already invalidated permanently. | 密钥访问失败-密钥访问失效 | -| 密钥访问失败-密钥认证失败 | 12000008 | Verify authtoken failed. | 密钥访问失败-密钥认证失败 | -| 密钥访问失败-密钥访问超时 | 12000009 | This authtoken is already timeout. | 密钥访问失败-密钥访问超时 | -| 密钥操作会话数已达上限 | 12000010 | The number of sessions has reached limit. | 密钥操作会话数已达上限。 | -| 目标对象不存在 | 12000011 | Queried entity does not exist. | 表示不存在。 | -| 外部错误 | 12000012 | General error. | 一般错误。 | -| 外部错误 | 12000012 | System error. | 系统错误。 | -| 外部错误 | 12000012 | System external error. | 表示系统外部错误。 | -| 缺失所需凭据 | 12000013 | Queried credential does not exist. | 查询的凭据不存在。 | -| 内存不足 | 12000014 | Memory is insufficient. | 表示内存不足。 | -| 内存不足 | 12000014 | Malloc failed. | 表示MALLOC 失败。 | -| 调用其他系统服务失败 | 12000015 | Calling useriam to get sec info failed. | 访问useriam获取当前用户安全属性信息失败。 | -| 调用其他系统服务失败 | 12000015 | Calling useriam to get auth info failed. | 访问useriam获取当前用户认证信息失败。 | - ## HuksKeyPurpose 表示密钥用途。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md b/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md index bfea0a61c68f384b4317ff43d4a7e60b81c3ea6d..3baf08fd65d5c60b7ae4950bbb4622c3a553465e 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md +++ b/zh-cn/application-dev/reference/apis/js-apis-particleAbility.md @@ -203,7 +203,7 @@ startBackgroundRunning(id: number, request: NotificationRequest, callback: Async | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | id | number | 是 | 长时任务通知id号 | - | request | NotificationRequest | 是 | 通知参数,用于显示通知栏的信息 | + | request | [NotificationRequest](js-apis-notification.md#notificationrequest) | 是 | 通知参数,用于显示通知栏的信息 | | callback | AsyncCallback<void> | 是 | callback形式返回启动长时任务的结果 | **示例**: @@ -215,7 +215,7 @@ import wantAgent from '@ohos.wantAgent'; function callback(err, data) { if (err) { - console.error("Operation failed Cause: " + err); + console.error("Operation failed cause: " + JSON.stringify(err)); } else { console.info("Operation succeeded"); } @@ -267,7 +267,7 @@ startBackgroundRunning(id: number, request: NotificationRequest): Promise<voi | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | | id | number | 是 | 长时任务通知id号 | -| request | NotificationRequest | 是 | 通知参数,用于显示通知栏的信息 | +| request | [NotificationRequest](js-apis-notification.md#notificationrequest) | 是 | 通知参数,用于显示通知栏的信息 | **返回值:** @@ -311,7 +311,7 @@ wantAgent.getWantAgent(wantAgentInfo).then((wantAgentObj) => { particleAbility.startBackgroundRunning(id, request).then(() => { console.info("Operation succeeded"); }).catch((err) => { - console.error("Operation failed Cause: " + err); + console.error("Operation failed cause: " + JSON.stringify(err)); }); }); @@ -338,7 +338,7 @@ import particleAbility from '@ohos.ability.particleAbility'; function callback(err, data) { if (err) { - console.error("Operation failed Cause: " + err); + console.error("Operation failed cause: " + JSON.stringify(err)); } else { console.info("Operation succeeded"); } @@ -370,7 +370,7 @@ import particleAbility from '@ohos.ability.particleAbility'; particleAbility.cancelBackgroundRunning().then(() => { console.info("Operation succeeded"); }).catch((err) => { - console.error("Operation failed Cause: " + err); + console.error("Operation failed cause: " + JSON.stringify(err)); }); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md index 18e7cbe45dc5a92acf7ab759b1c2819ac2da9f1b..038b1311f6fefab47e05daca0673c006cd410d86 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md +++ b/zh-cn/application-dev/reference/apis/js-apis-privacyManager.md @@ -1,10 +1,10 @@ # 隐私管理 -该模块主要提供权限使用记录等隐私管理接口。 +本模块主要提供权限使用记录等隐私管理接口。 > **说明:** > 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 -> 本模块接口为系统接口,三方应用不支持调用。 +> 本模块接口为系统接口。 ## 导入模块 @@ -39,6 +39,15 @@ addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: n | :------------ | :---------------------------------- | | Promise<void> | Promise对象。无返回结果的Promise对象。 | +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | + **示例:** ```js @@ -75,7 +84,16 @@ addPermissionUsedRecord(tokenID: number, permissionName: string, successCount: n | permissionName | string | 是 | 应用权限名称。 | | successCount | number | 是 | 访问成功的次数。 | | failCount | number | 是 | 访问失败的次数。 | -| callback | AsyncCallback<void> | 是 | 回调函数。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当添加使用记录成功时,err为undefine;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | **示例:** @@ -84,7 +102,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId try { - privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (data, err) => { + privacyManager.addPermissionUsedRecord(tokenID, "ohos.permission.PERMISSION_USED_STATS", 1, 0, (err, data) => { if (err) { console.log(`addPermissionUsedRecord fail, err->${JSON.stringify(err)}`); } else { @@ -100,7 +118,7 @@ try { getPermissionUsedRecords(request: PermissionUsedRequest): Promise<PermissionUsedResponse> -获取历史权限使用记录。 +获取历史权限使用记录。使用Promise异步回调。 **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 @@ -116,7 +134,16 @@ getPermissionUsedRecords(request: PermissionUsedRequest): Promise<PermissionU | 类型 | 说明 | | :------------ | :---------------------------------- | -| Promise<[PermissionUsedResponse](#permissionusedresponse)> | Promise对象。返回权限使用记录。| +| Promise<[PermissionUsedResponse](#permissionusedresponse)> | Promise对象。返回查询的权限使用记录。| + +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | **示例:** @@ -148,7 +175,7 @@ try { getPermissionUsedRecords(request: PermissionUsedRequest, callback: AsyncCallback<PermissionUsedResponse>): void -获取历史权限使用记录。 +获取历史权限使用记录。使用callback异步回调。 **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 @@ -159,7 +186,16 @@ getPermissionUsedRecords(request: PermissionUsedRequest, callback: AsyncCallback | 参数名 | 类型 | 必填 | 说明 | | -------- | ------------------- | ---- | ------------------------------------------ | | request | [PermissionUsedRequest](#permissionusedrequest) | 是 | 查询权限使用记录的请求。 | -| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | 是 | 回调函数。返回权限使用记录。 | +| callback | AsyncCallback<[PermissionUsedResponse](#permissionusedresponse)> | 是 | 回调函数。当查询记录成功时,err为undefine,data为查询到的权限使用记录;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | **示例:** @@ -193,7 +229,7 @@ try { startUsingPermission(tokenID: number, permissionName: string): Promise<void> -应用开始使用某项权限,可监听应用在前后台使用权限,并将使用权限的记录落盘,由系统服务调用。 +应用开始使用某项权限,可监听应用在前后台使用权限,并将使用权限的记录落盘,由系统服务调用。使用Promise异步回调。 **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 @@ -212,6 +248,16 @@ startUsingPermission(tokenID: number, permissionName: string): Promise<void&g | ------------- | --------------------------------------- | | Promise<void> | Promise对象。无返回结果的Promise对象。| +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100004 | The interface is not used together. | + **示例:** ```js @@ -233,7 +279,7 @@ try { startUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void -应用开始使用某项权限,可监听应用在前后台使用权限,并将使用权限的记录落盘,由系统服务调用。 +应用开始使用某项权限,可监听应用在前后台使用权限,并将使用权限的记录落盘,由系统服务调用。使用callback异步回调。 **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 @@ -245,7 +291,17 @@ startUsingPermission(tokenID: number, permissionName: string, callback: AsyncCal | -------------- | --------------------- | ---- | ------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | string | 是 | 需要使用的权限名。 | -| callback | AsyncCallback<void> | 是 | 异步回调,返回开始使用权限的结果。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当开始使用权限成功时,err为undefine;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100004 | The interface is not used together. | **示例:** @@ -254,7 +310,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId try { - privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (data, err) => { + privacyManager.startUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (err, data) => { if (err) { console.log(`startUsingPermission fail, err->${JSON.stringify(err)}`); } else { @@ -270,7 +326,7 @@ try { stopUsingPermission(tokenID: number, permissionName: string): Promise<void> -应用停止使用某项权限,与Start对应,由系统服务调用。 +应用停止使用某项权限,与Start对应,由系统服务调用。使用Promise异步回调。 **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 @@ -289,6 +345,16 @@ stopUsingPermission(tokenID: number, permissionName: string): Promise<void> | ------------- | --------------------------------------- | | Promise<void> | Promise对象。无返回结果的Promise对象。| +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100004 | The interface is not used together. | + **示例:** ```js @@ -310,7 +376,7 @@ try { stopUsingPermission(tokenID: number, permissionName: string, callback: AsyncCallback<void>): void -应用停止使用某项权限,与Start对应,由系统服务调用。 +应用停止使用某项权限,与Start对应,由系统服务调用。使用callback异步回调。 **需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 @@ -322,7 +388,17 @@ stopUsingPermission(tokenID: number, permissionName: string, callback: AsyncCall | -------------- | --------------------- | ---- | ------------------------------------ | | tokenID | number | 是 | 调用方的应用身份标识。可通过应用的[ApplicationInfo](js-apis-bundle-ApplicationInfo.md)获得。 | | permissionName | string | 是 | 需要使用的权限名。 | -| callback | AsyncCallback<void> | 是 | 异步回调,返回停止使用权限的结果。 | +| callback | AsyncCallback<void> | 是 | 回调函数。当停止使用权限成功时,err为undefine;否则为错误对象。 | + +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100002 | TokenId does not exist. | +| 12100003 | Permission does not exist. | +| 12100004 | The interface is not used together. | **示例:** @@ -331,7 +407,7 @@ import privacyManager from '@ohos.privacyManager'; let tokenID = 0; // 可以通过getApplicationInfo获取accessTokenId try { - privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (data, err) => { + privacyManager.stopUsingPermission(tokenID, "ohos.permission.PERMISSION_USED_STATS", (err, data) => { if (err) { console.log(`stopUsingPermission fail, err->${JSON.stringify(err)}`); } else { @@ -347,11 +423,9 @@ try { on(type: 'activeStateChange', permissionNameList: Array<string>, callback: Callback<ActiveChangeResponse>): void -订阅指定权限列表的权限使用状态变更事件,使用callback回调异步返回结果。 - -此接口为系统接口。 +订阅指定权限列表的权限使用状态变更事件。 -**需要权限:** ohos.permission.PERMISSION_USED_STATS +**需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -363,6 +437,15 @@ on(type: 'activeStateChange', permissionNameList: Array<string>, callback: | permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限使用状态变化。 | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | 是 | 订阅指定权限使用状态变更事件的回调。 | +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100004 | The interface is not used together. | +| 12100005 | The number of listeners exceeds the limit. | + **示例:** ```js @@ -382,11 +465,9 @@ try { off(type: 'activeStateChange', permissionNameList: Array<string>, callback?: Callback<ActiveChangeResponse>): void; -取消订阅指定权限列表的权限使用状态变更事件,使用callback回调异步返回结果。 - -此接口为系统接口。 +取消订阅指定权限列表的权限使用状态变更事件。 -**需要权限:** ohos.permission.PERMISSION_USED_STATS +**需要权限:** ohos.permission.PERMISSION_USED_STATS,仅系统应用可用。 **系统能力:** SystemCapability.Security.AccessToken @@ -398,6 +479,14 @@ off(type: 'activeStateChange', permissionNameList: Array<string>, callback | permissionNameList | Array<string> | 否 | 订阅的权限名列表,为空时表示订阅所有的权限状态变化,必须与on的输入一致。 | | callback | Callback<[ActiveChangeResponse](#activechangeresponse)> | 否 | 取消订阅指定tokenId与指定权限名状态变更事件的回调。| +**错误码:** + +以下错误码的详细介绍请参见[程序访问控制错误码](../errorcodes/errorcode-access-token.md)。 +| 错误码ID | 错误信息 | +| -------- | -------- | +| 12100001 | Parameter invalid. | +| 12100004 | The interface is not used together. | + **示例:** ```js @@ -426,7 +515,7 @@ try { 表示使用记录的查询请求。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Security.AccessToken +**系统能力:** SystemCapability.Security.AccessToken | 名称 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------------- | @@ -443,7 +532,7 @@ try { 表示所有应用的访问记录。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Security.AccessToken +**系统能力:** SystemCapability.Security.AccessToken | 名称 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------------- | @@ -455,7 +544,7 @@ try { 某个应用的访问记录。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Security.AccessToken +**系统能力:** SystemCapability.Security.AccessToken | 名称 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------------- | @@ -469,7 +558,7 @@ try { 某个权限的访问记录。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Security.AccessToken +**系统能力:** SystemCapability.Security.AccessToken | 名称 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------------- | @@ -486,7 +575,7 @@ try { 单次访问记录详情。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Security.AccessToken +**系统能力:** SystemCapability.Security.AccessToken | 名称 | 类型 | 必填 | 说明 | | -------- | -------------- | ---- | ---------------------------------------- | @@ -498,7 +587,7 @@ try { 表示权限使用状态变化类型的枚举。 -**系统能力:** 以下各项对应的系统能力均为SystemCapability.Security.AccessToken +**系统能力:** SystemCapability.Security.AccessToken | 名称 | 默认值 | 描述 | | ------------------------- | ------ | ---------------- | @@ -510,7 +599,7 @@ try { 表示某次权限使用状态变化的详情。 - **系统能力:** 以下各项对应的系统能力均为SystemCapability.Security.AccessToken + **系统能力:** SystemCapability.Security.AccessToken | 名称 | 类型 | 可读 | 可写 | 说明 | | -------------- | ---------------------- | ---- | ---- | --------------------- | diff --git a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md index 09b727f94f886a8887f489f2a8862b1b6bee11f1..e843ab5584ac8ec135c02e11a820b81206dc37d3 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md +++ b/zh-cn/application-dev/reference/apis/js-apis-reminderAgent.md @@ -10,7 +10,7 @@ ## 导入模块 -``` +```js import reminderAgent from'@ohos.reminderAgent'; ``` @@ -88,7 +88,7 @@ cancelReminder(reminderId: number, callback: AsyncCallback<void>): void | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| reminderId | number | 是 | 目标reminder的id号。 | +| reminderId | number | 是 | 目标reminder的id号,[publishReminder](#reminderagentpublishreminder)方法调用成功后获得。 | | callback | AsyncCallback<void> | 是 | 异步回调。 | **示例**: @@ -112,7 +112,7 @@ cancelReminder(reminderId: number): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| reminderId | number | 是 | 目标reminder的id号。 | +| reminderId | number | 是 | 目标reminder的id号,[publishReminder](#reminderagentpublishreminder)方法调用成功后获得。 | **返回值**: @@ -452,10 +452,10 @@ reminderAgent.removeNotificationSlot(notification.SlotType.CONTENT_INFORMATION). | 名称 | 参数类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| reminderType | ReminderType | 是 | 指明提醒类型。 | -| actionButton | [ActionButton?, ActionButton?] | 否 | 弹出的提醒通知栏中显示的按钮(参数可选,支持0/1/2个按钮)。 | -| wantAgent | WantAgent | 否 | 点击通知后需要跳转的目标ability信息。 | -| maxScreenWantAgent | MaxScreenWantAgent | 否 | 提醒到达时跳转的目标包。如果设备正在使用中,则弹出一个通知框。 | +| reminderType | [ReminderType](#remindertype) | 是 | 指明提醒类型。 | +| actionButton | [ActionButton](#actionbutton) | 否 | 弹出的提醒通知栏中显示的按钮(参数可选,支持0/1/2个按钮)。 | +| wantAgent | [WantAgent](#wantagent) | 否 | 点击通知后需要跳转的目标ability信息。 | +| maxScreenWantAgent | [MaxScreenWantAgent](#maxscreenwantagent) | 否 | 提醒到达时跳转的目标包。如果设备正在使用中,则弹出一个通知框。 | | ringDuration | number | 否 | 指明响铃时长。 | | snoozeTimes | number | 否 | 指明延迟提醒次数。 | | timeInterval | number | 否 | 执行延迟提醒间隔。 | diff --git a/zh-cn/application-dev/reference/apis/js-apis-request.md b/zh-cn/application-dev/reference/apis/js-apis-request.md index 1ba8a552f29850c589f0f192910fd6e7bb740ee7..c379b82a1b868a981002f162727565e9eb3dd773 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-request.md +++ b/zh-cn/application-dev/reference/apis/js-apis-request.md @@ -33,6 +33,7 @@ var config = { 在开发stage模型下的应用程序时,不涉及属性标识 "cleartextTraffic"。 +下载服务器需要支持http协议的header方法,能够通过content-length获取下载数据大小,否则下载任务失败,可通过[on('fail')7+)](#onfail7)查看失败原因。 ## 常量 @@ -53,6 +54,8 @@ var config = { | ERROR_INSUFFICIENT_SPACE7+ | number | 是 | 否 | 存储空间不足。 | | ERROR_TOO_MANY_REDIRECTS7+ | number | 是 | 否 | 网络重定向过多导致的错误。 | | ERROR_UNHANDLED_HTTP_CODE7+ | number | 是 | 否 | 无法识别的HTTP代码。 | +| ERROR_OFFLINE9+ | number | 是 | 否 | 网络未连接。 | +| ERROR_UNSUPPORTED_NETWORK_TYPE9+ | number | 是 | 否 | 网络类型不匹配。 | | ERROR_UNKNOWN7+ | number | 是 | 否 | 未知错误。 | | PAUSED_QUEUED_FOR_WIFI7+ | number | 是 | 否 | 下载被暂停并等待WLAN连接,因为文件大小超过了使用蜂窝网络的会话允许的最大值。 | | PAUSED_UNKNOWN7+ | number | 是 | 否 | 未知原因导致暂停下载。 | @@ -73,6 +76,8 @@ upload(config: UploadConfig): Promise<UploadTask> 此接口仅可在FA模型下使用 +> **说明:** 从API Version 9开始废弃,建议使用[request.uploadFile9+](#requestuploadfile9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Upload @@ -116,6 +121,8 @@ upload(config: UploadConfig, callback: AsyncCallback<UploadTask>): void 此接口仅可在FA模型下使用 +> **说明:** 从API Version 9开始废弃,建议使用[request.uploadFile9+](#requestuploadfile9-1)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Upload @@ -152,6 +159,8 @@ upload(context: BaseContext, config: UploadConfig): Promise<UploadTask> 上传,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[request.uploadFile9+](#requestuploadfile9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Upload @@ -195,6 +204,8 @@ upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<Up 上传,异步方法,使用callback形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[request.uploadFile9+](#requestuploadfile9-1)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Upload @@ -227,6 +238,103 @@ upload(context: BaseContext, config: UploadConfig, callback: AsyncCallback<Up }); ``` + +## request.uploadFile9+ + +uploadFile(context: BaseContext, config: UploadConfig): Promise<UploadTask> + +上传,异步方法,使用promise形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Upload + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| context | BaseContext | 是 | 基于应用程序的上下文。 | +| config | [UploadConfig](#uploadconfig) | 是 | 上传的配置信息。 | + + +**返回值:** + +| 类型 | 说明 | + | -------- | -------- | +| Promise<[UploadTask](#uploadtask)> | 返回上传任务。 | + +**错误码:** +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 13400002 | Bad file path. | + +**示例:** + + ```js + let uploadTask; + let uploadConfig = { + url: 'https://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) => { + uploadTask = data; + }).catch((err) => { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + }); + ``` + + +## request.uploadFile9+ + +uploadFile(context: BaseContext, config: UploadConfig, callback: AsyncCallback<UploadTask>): void + +上传,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Upload + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| context | BaseContext | 是 | 基于应用程序的上下文。 | +| config | [UploadConfig](#uploadconfig) | 是 | 上传的配置信息。 | +| callback | AsyncCallback<[UploadTask](#uploadtask)> | 否 | 回调函数,异步返回UploadTask对象。 | + +**错误码:** +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 13400002 | Bad file path. | + +**示例:** + + ```js + let uploadTask; + let uploadConfig = { + url: 'https://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) => { + if (err) { + console.error('Failed to request the upload. Cause: ' + JSON.stringify(err)); + return; + } + uploadTask = data; + }); + ``` + + ## UploadTask 上传任务,使用下列方法前,需要先获取UploadTask对象。 @@ -455,6 +563,8 @@ remove(): Promise<boolean> 移除上传的任务,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[delete9+](#delete9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Upload @@ -486,6 +596,8 @@ remove(callback: AsyncCallback<boolean>): void 移除上传的任务,异步方法,使用callback形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[delete9+](#delete9-1)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Upload @@ -513,6 +625,70 @@ remove(callback: AsyncCallback<boolean>): void ``` +### delete9+ + +delete(): Promise<boolean> + +移除上传的任务,异步方法,使用promise形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Upload + +**返回值:** + +| 类型 | 说明 | + | -------- | -------- | +| Promise<boolean> | 移除任务是否成功。true:成功,false:不成功。 | + +**示例:** + + ```js + uploadTask.delete().then((result) => { + if (result) { + console.info('Upload task removed successfully. '); + } else { + console.error('Failed to remove the upload task. '); + } + }).catch((err) => { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + }); + ``` + + +### delete9+ + +delete(callback: AsyncCallback<boolean>): void + +移除上传的任务,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Upload + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | 是 | 移除任务的回调函数。 | + +**示例:** + + ```js + uploadTask.delete((err, result) => { + if (err) { + console.error('Failed to remove the upload task. Cause: ' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Upload task removed successfully.'); + } else { + console.error('Failed to remove the upload task.'); + } + }); + ``` + + ## UploadConfig **需要权限**:ohos.permission.INTERNET @@ -543,21 +719,21 @@ remove(callback: AsyncCallback<boolean>): void **需要权限**:ohos.permission.INTERNET -**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download +**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。 | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | -| filename | string | 否 | multipart提交时,请求头中的文件名。 | -| name | string | 否 | multipart提交时,表单项目的名称,缺省为file。 | +| filename | string | 是 | multipart提交时,请求头中的文件名。 | +| name | string | 是 | multipart提交时,表单项目的名称,缺省为file。 | | uri | string | 是 | 文件的本地存储路径。
支持“dataability”和“internal”两种协议类型,但“internal”仅支持临时目录,示例:
dataability:///com.domainname.dataability.persondata/person/10/file.txt
internal://cache/path/to/file.txt | -| type | string | 否 | 文件的内容类型,默认根据文件名或路径的后缀获取。 | +| type | string | 是 | 文件的内容类型,默认根据文件名或路径的后缀获取。 | ## RequestData **需要权限**:ohos.permission.INTERNET -**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Download +**系统能力**: 以下各项对应的系统能力均为SystemCapability.MiscServices.Upload。 | 名称 | 类型 | 必填 | 说明 | | -------- | -------- | -------- | -------- | @@ -571,6 +747,8 @@ download(config: DownloadConfig): Promise<DownloadTask> 下载,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[request.downloadFile9+](#requestdownloadfile9)替代。 + 此接口仅可在FA模型下使用 **需要权限**:ohos.permission.INTERNET @@ -607,6 +785,8 @@ download(config: DownloadConfig, callback: AsyncCallback<DownloadTask>): v 下载,异步方法,使用callback形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[request.downloadFile9+](#requestdownloadfile9-1)替代。 + 此接口仅可在FA模型下使用 **需要权限**:ohos.permission.INTERNET @@ -640,6 +820,8 @@ download(context: BaseContext, config: DownloadConfig): Promise<DownloadTask& 下载,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[request.downloadFile9+](#requestdownloadfile9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -675,6 +857,8 @@ download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&l 下载,异步方法,使用callback形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[request.downloadFile9+](#requestdownloadfile9-1)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -700,6 +884,94 @@ download(context: BaseContext, config: DownloadConfig, callback: AsyncCallback&l downloadTask = data; }); ``` + + +## request.downloadFile9+ + +downloadFile(context: BaseContext, config: DownloadConfig): Promise<DownloadTask> + +下载,异步方法,使用promise形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| context | BaseContext | 是 | 基于应用程序的上下文。 | +| config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 | + +**返回值:** + +| 类型 | 说明 | + | -------- | -------- | +| Promise<[DownloadTask](#downloadtask)> | 返回下载任务。 | + +**错误码:** +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | + +**示例:** + + ```js + let downloadTask; + 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)); + }) + ``` + + +## request.downloadFile9+ + +downloadFile(context: BaseContext, config: DownloadConfig, callback: AsyncCallback<DownloadTask>): void; + +下载,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| context | BaseContext | 是 | 基于应用程序的上下文。 | +| config | [DownloadConfig](#downloadconfig) | 是 | 下载的配置信息。 | +| callback | AsyncCallback<[DownloadTask](#downloadtask)> | 否 | 下载接口的回调函数。 | + +**错误码:** +以下错误码的详细介绍请参见[上传下载错误码](../errorcodes/errorcodes-request.md)。 + +| 错误码ID | 错误码信息 | +| -------- | -------- | +| 13400001 | File operation error. | +| 13400002 | Bad file path. | +| 13400003 | Task manager service error. | + +**示例:** + + ```js + let downloadTask; + 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; + }); + ``` + + ## DownloadTask 下载任务。 @@ -899,6 +1171,8 @@ remove(): Promise<boolean> 移除下载的任务,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[delete9+](#delete9-2)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -930,6 +1204,8 @@ remove(callback: AsyncCallback<boolean>): void 移除下载的任务,异步方法,使用callback形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[delete9+](#delete9-3)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -963,6 +1239,8 @@ query(): Promise<DownloadInfo> 查询下载任务,异步方法,使用promise形式返回DownloadInfo里的信息。 +> **说明:** 从API Version 9开始废弃,建议使用[getTaskInfo9+](#gettaskinfo9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -989,6 +1267,8 @@ query(callback: AsyncCallback<DownloadInfo>): void 查询下载的任务,异步方法,使用callback形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[getTaskInfo9+](#gettaskinfo9-1)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -1018,6 +1298,8 @@ queryMimeType(): Promise<string> 查询下载的任务的 MimeType,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[getTaskMimeType9+](#gettaskmimetype9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -1045,6 +1327,8 @@ queryMimeType(callback: AsyncCallback<string>): void; 查询下载的任务的 MimeType,异步方法,使用callback形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[getTaskMimeType9+](#gettaskmimetype9-1)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -1074,6 +1358,8 @@ pause(): Promise<void> 暂停下载任务,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[suspend9+](#suspend9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -1103,6 +1389,8 @@ pause(): Promise<void> pause(callback: AsyncCallback<void>): void +> **说明:** 从API Version 9开始废弃,建议使用[suspend9+](#suspend9-1)替代。 + 暂停下载任务,异步方法,使用callback形式返回结果。 **需要权限**:ohos.permission.INTERNET @@ -1138,6 +1426,8 @@ resume(): Promise<void> 重新启动暂停的下载任务,异步方法,使用promise形式返回结果。 +> **说明:** 从API Version 9开始废弃,建议使用[restore9+](#restore9)替代。 + **需要权限**:ohos.permission.INTERNET **系统能力**: SystemCapability.MiscServices.Download @@ -1168,6 +1458,8 @@ resume(): Promise<void> resume(callback: AsyncCallback<void>): void +> **说明:** 从API Version 9开始废弃,建议使用[restore9+](#restore9-1)替代。 + 重新启动暂停的下载任务,异步方法,使用callback形式返回结果。 **需要权限**:ohos.permission.INTERNET @@ -1197,6 +1489,310 @@ resume(callback: AsyncCallback<void>): void ``` +### delete9+ + +delete(): Promise<boolean> + +移除下载的任务,异步方法,使用promise形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**返回值:** + +| 类型 | 说明 | + | -------- | -------- | +| Promise<boolean> | 移除任务是否成功。 | + +**示例:** + + ```js + downloadTask.delete().then((result) => { + if (result) { + console.info('Download task removed.'); + } else { + console.error('Failed to remove the download task.'); + } + }).catch ((err) => { + console.error('Failed to remove the download task.'); + }); + ``` + + +### delete9+ + +delete(callback: AsyncCallback<boolean>): void + +移除下载的任务,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| callback | AsyncCallback<boolean> | 是 | 移除任务是否成功。 | + +**示例:** + + ```js + downloadTask.delete((err, result)=>{ + if(err) { + console.error('Failed to remove the download task.'); + return; + } + if (result) { + console.info('Download task removed.'); + } else { + console.error('Failed to remove the download task.'); + } + }); + ``` + + +### getTaskInfo9+ + +getTaskInfo(): Promise<DownloadInfo> + +查询下载任务,异步方法,使用promise形式返回DownloadInfo里的信息。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** +| 类型 | 说明 | +| -------- | -------- | +| Promise<[DownloadInfo](#downloadinfo7)> | 查询下载任务信息。 | + +**示例:** + + ```js + 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) + }); + ``` + + +### getTaskInfo9+ + +query(callback: AsyncCallback<DownloadInfo>): void + +查询下载的任务,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| callback | AsyncCallback<[DownloadInfo](#downloadinfo7)> | 是 | 查询下载任务的回调函数。 | + +**示例:** + + ```js + downloadTask.getTaskInfo((err, downloadInfo)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('download query success. data:'+ JSON.stringify(downloadInfo)); + } + }); + ``` + + +### getTaskMimeType9+ + +getTaskMimeType(): Promise<string> + +查询下载的任务的 MimeType,异步方法,使用promise形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**返回值:** + +| 类型 | 说明 | + | -------- | -------- | +| Promise<string> | 查询下载任务的MimeType。 | + +**示例:** + + ```js + 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)) + }); + ``` + + +### getTaskMimeType9+ + +getTaskMimeType(callback: AsyncCallback<string>): void; + +查询下载的任务的 MimeType,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| callback | AsyncCallback<string> | 是 | 查询下载任务的MimeType的回调函数。 | + +**示例:** + + ```js + downloadTask.getTaskMimeType((err, data)=>{ + if(err) { + console.error('Failed to query the download mimeType. Cause:' + JSON.stringify(err)); + } else { + console.info('Download task queried. data:' + JSON.stringify(data)); + } + }); + ``` + + +### suspend9+ + +suspend(): Promise<void> + +暂停下载任务,异步方法,使用promise形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**返回值:** + +| 类型 | 说明 | + | -------- | -------- | +| Promise<void> | 暂停下载任务是否成功。 | + +**示例:** + + ```js + downloadTask.suspend().then((result) => { + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }).catch((err) => { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + }); + ``` + + +### suspend9+ + +suspend(callback: AsyncCallback<void>): void + +暂停下载任务,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | 是 | 暂停下载任务的回调函数。 | + +**示例:** + + ```js + downloadTask.suspend((err, result)=>{ + if(err) { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(err)); + return; + } + if (result) { + console.info('Download task paused. '); + } else { + console.error('Failed to pause the download task. Cause:' + JSON.stringify(result)); + } + }); + ``` + + +### restore9+ + +restore(): Promise<void> + +重新启动暂停的下载任务,异步方法,使用promise形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 类型 | 说明 | + | -------- | -------- | +| Promise<void> | 重新启动暂停的下载任务是否成功。 | + +**示例:** + + ```js + downloadTask.restore().then((result) => { + if (result) { + console.info('Download task resumed.') + } else { + console.error('Failed to resume the download task. '); + } + console.info('Download task resumed.') + }).catch((err) => { + console.error('Failed to resume the download task. Cause:' + err); + }); + ``` + + +### restore9+ + +restore(callback: AsyncCallback<void>): void + +重新启动暂停的下载任务,异步方法,使用callback形式返回结果。 + +**需要权限**:ohos.permission.INTERNET + +**系统能力**: SystemCapability.MiscServices.Download + +**参数:** + +| 参数名 | 参数类型 | 必填 | 说明 | + | -------- | -------- | -------- | -------- | +| callback | AsyncCallback<void> | 是 | 重新启动暂停的下载任务的回调函数。 | + +**示例:** + + ```js + downloadTask.restore((err, result)=>{ + if (err) { + console.error('Failed to resume the download task. Cause:' + err); + return; + } + if (result) { + console.info('Download task resumed.'); + } else { + console.error('Failed to resume the download task.'); + } + }); + ``` + + ## DownloadConfig **需要权限**:ohos.permission.INTERNET diff --git a/zh-cn/application-dev/reference/apis/js-apis-sensor.md b/zh-cn/application-dev/reference/apis/js-apis-sensor.md index 90c18d897092a30423a010bb41096440571f9964..de9ec2ae2b856bbf0f36bb7a98e41d90f0f584b1 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-sensor.md +++ b/zh-cn/application-dev/reference/apis/js-apis-sensor.md @@ -340,7 +340,7 @@ try { on(type: SensorId.HALL, callback: Callback<HallResponse>, options?: Options): void -订阅心率传感器数据。 +订阅霍尔传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -446,7 +446,7 @@ try { } ``` -### LINEAR_ACCELERATION9+ +### LINEAR_ACCELEROMETER9+ on(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>, options?: Options): void @@ -799,7 +799,7 @@ try { on(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>, options?: Options): void -订阅磨损检测传感器数据。 +订阅佩戴检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -1255,7 +1255,7 @@ try { } ``` -### LINEAR_ACCELERATION9+ +### LINEAR_ACCELEROMETER9+ once(type: SensorId.LINEAR_ACCELEROMETER, callback: Callback<LinearAccelerometerResponse>): void @@ -1603,7 +1603,7 @@ try { once(type: SensorId.WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void -订阅一次磨损检测传感器数据。 +订阅一次佩戴检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -2244,7 +2244,7 @@ try { off(type: SensorId.WEAR_DETECTION, callback?: Callback<WearDetectionResponse>): void -取消订阅磨损检测传感器数据。 +取消订阅佩戴检测传感器数据。 **系统能力**:SystemCapability.Sensors.Sensor @@ -3637,7 +3637,7 @@ on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Line 监听线性加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 -从API version 9 开始不再维护,建议使用[sensor.on.LINEAR_ACCELEROMETER](#linear_accelerometer9)代替。 +从API version 9 开始不再维护,建议使用[sensor.on.LINEAR_ACCELEROMETER](#linear_accelerometer9)代替。 **需要权限**:ohos.permission.ACCELEROMETER @@ -3651,36 +3651,6 @@ on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Line | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | | options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | -### LINEAR_ACCELEROMETER9+ - -on(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>, - options?: Options): void - -监听线性加速度传感器的数据变化。如果多次调用该接口,仅最后一次调用生效。 - -**需要权限**:ohos.permission.ACCELEROMETER - -**系统能力**:SystemCapability.Sensors.Sensor - -**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 要订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELEROMETER。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | -| options | [Options](#options) | 否 | 可选参数列表,设置上报频率,默认值为200000000ns。 | - -**示例:** - - ```js - sensor.on(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER,function(data){ - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - }, - {interval: 10000000} - ); - ``` - ### ACCELEROMETER_UNCALIBRATED(deprecated) on(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>, options?: Options): void @@ -4157,7 +4127,7 @@ on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateRe 监听心率传感器数据变化一次。 -从API version 9 开始不再维护,建议使用[sensor.on.HEART_BEAT_RATE](#heart_beat_rate9)代替。 +从API version 9 开始不再维护,建议使用[sensor.on.HEART_RATE](#heart_rate9)代替。 **需要权限**:ohos.permission.HEALTH_DATA @@ -4170,34 +4140,6 @@ on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateRe | type | [SensorType](#sensortype) | 是 | 要订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | | callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | -### HEART_BEAT_RATE9+ - -on(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>, - options?: Options): void - -监听心率传感器数据变化一次。 - -**需要权限**:ohos.permission.HEALTH_DATA - -**系统能力**:SystemCapability.Sensors.Sensor - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 要订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_BEAT_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | - -**示例:** - -```js -sensor.on(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE,function(data){ - console.info("Heart rate: " + data.heartRate); -}, - {interval: 10000000} -); -``` - ### ROTATION_VECTOR(deprecated) on(type: SensorType.SENSOR_TYPE_ID_ROTATION_VECTOR,callback: Callback<RotationVectorResponse>,options?: Options): void @@ -4292,7 +4234,7 @@ once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Li 监听线性加速度传感器数据变化一次。 -从API version 9 开始不再维护,建议使用[sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9)代替。 +从API version 9 开始不再维护,建议使用[sensor.once.LINEAR_ACCELEROMETER](#linear_accelerometer9-1)代替。 **需要权限**:ohos.permission.ACCELERATION @@ -4305,33 +4247,6 @@ once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<Li | type | [SensorType](#sensortype) | 是 | 线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册一次线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | -### LINEAR_ACCELEROMETER9+ - -once(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback:Callback<LinearAccelerometerResponse>): void - -订阅一次线性加速度传感器数据。 - -**需要权限**:ohos.permission.ACCELERATION - -**系统能力**:SystemCapability.Sensors.Sensor - -**参数:** -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELEROMETER。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 注册一次线性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | - -**示例:** - - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, function(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); - } - ); - ``` - ### ACCELEROMETER_UNCALIBRATED(deprecated) once(type: SensorType.SENSOR_TYPE_ID_ACCELEROMETER_UNCALIBRATED,callback: Callback<AccelerometerUncalibratedResponse>): void @@ -4800,7 +4715,7 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRate 监听心率传感器数据变化一次。 -从API version 9 开始不再维护,建议使用[sensor.once.HEART_BEAT_RATE](#heart_beat_rate9)代替。 +从API version 9 开始不再维护,建议使用[sensor.once.HEART_RATE](#heart_rate9-1)代替。 **需要权限**:ohos.permission.HEART_RATE @@ -4813,32 +4728,6 @@ once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRate | type | [SensorType](#sensortype) | 是 | 心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | | callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | -### HEART_BEAT_RATE9+ - -once(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback: Callback<HeartRateResponse>): void - -订阅一次心率传感器数据。 - -**需要权限**:ohos.permission.HEART_RATE - -**系统能力**:SystemCapability.Sensors.Sensor - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 心率传感器类型为SENSOR_TYPE_ID_HEART_BEAT_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | - -**示例:** - - ```js - sensor.once(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, function(data) { - console.info("Heart rate: " + data.heartRate); - } - ); - ``` - ### WEAR_DETECTION(deprecated) once(type: SensorType.SENSOR_TYPE_ID_WEAR_DETECTION, callback: Callback<WearDetectionResponse>): void @@ -5127,7 +5016,7 @@ off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRate 取消订阅传感器数据。 -从API version 9 开始不再维护,建议使用[sensor.off.HEART_BEAT_RATE](#heart_beat_rate9)代替。 +从API version 9 开始不再维护,建议使用[sensor.off.HEART_RATE](#heart_rate9-2)代替。 **需要权限**:ohos.permission.HEALTH_DATA @@ -5140,32 +5029,6 @@ off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRate | type | [SensorType](#sensortype) | 是 | 要取消订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_RATE。 | | callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 取消注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | -### HEART_BEAT_RATE9+ - -off(type: SensorType.SENSOR_TYPE_ID_HEART_RATE, callback?: Callback<HeartRateResponse>): void - -取消订阅传感器数据。 - -**需要权限**:ohos.permission.HEALTH_DATA - -**系统能力**:SystemCapability.Sensors.Sensor - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------- | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的心率传感器类型为SENSOR_TYPE_ID_HEART_BEAT_RATE。 | -| callback | Callback<[HeartRateResponse](#heartrateresponse)> | 是 | 取消注册一次心率传感器的回调函数,上报的数据类型为HeartRateResponse。 | - -**示例:** - -```js -function callback(data) { - console.info("Heart rate: " + data.heartRate); -} -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_HEART_BEAT_RATE, callback); -``` - ### HUMIDITY(deprecated) off(type: SensorType.SENSOR_TYPE_ID_HUMIDITY, callback?: Callback<HumidityResponse>): void @@ -5198,7 +5061,7 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback< 取消订阅传感器数据。 -从API version 9 开始不再维护,建议使用[sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9)代替。 +从API version 9 开始不再维护,建议使用[sensor.off.LINEAR_ACCELEROMETER](#linear_accelerometer9-2)代替。 **需要权限**:ohos.permission.ACCELEROMETER @@ -5211,34 +5074,6 @@ off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION, callback?: Callback< | type | [SensorType](#sensortype) | 是 | 要取消订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELERATION。 | | callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 取消注册性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | -### LINEAR_ACCELEROMETER9+ - -off(type: SensorType.SENSOR_TYPE_ID_LINEAR_ACCELERATION,callback?:Callback<LinearAccelerometerResponse>): void - -取消订阅传感器数据。 - -**需要权限**:ohos.permission.ACCELEROMETER - -**系统能力**:SystemCapability.Sensors.Sensor - -**参数:** - -| 参数名 | 类型 | 必填 | 说明 | -| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ | -| type | [SensorType](#sensortype) | 是 | 要取消订阅的线性加速度传感器类型为SENSOR_TYPE_ID_LINEAR_ACCELEROMETER。 | -| callback | Callback<[LinearAccelerometerResponse](#linearaccelerometerresponse)> | 是 | 取消注册性加速度传感器的回调函数,上报的数据类型为LinearAccelerometerResponse。 | - -**示例:** - -```js -function callback(data) { - console.info('X-coordinate component: ' + data.x); - console.info('Y-coordinate component: ' + data.y); - console.info('Z-coordinate component: ' + data.z); -} -sensor.off(sensor.SensorType.SENSOR_TYPE_ID_LINEAR_ACCELEROMETER, callback); -``` - ### MAGNETIC_FIELD(deprecated) off(type: SensorType.SENSOR_TYPE_ID_MAGNETIC_FIELD, callback?: Callback<MagneticFieldResponse>): void diff --git a/zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md b/zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md new file mode 100644 index 0000000000000000000000000000000000000000..0c20c4b3b4aa03f528d7d8b7a23f6887a95c34cf --- /dev/null +++ b/zh-cn/application-dev/reference/apis/js-apis-usb-deprecated.md @@ -0,0 +1,862 @@ +# USB管理 + +本模块主要提供管理USB设备的相关功能,包括查询USB设备列表、批量数据传输、控制命令传输、权限控制等。 + +> **说明:** +> +> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> +> 从API version 9开始,该接口不再维护,推荐使用新接口[`@ohos.usbV9`](js-apis-usb.md)。 + +## 导入模块 + +```js +import usb from "@ohos.usb"; +``` + +## usb.getDevices + +getDevices(): Array<Readonly<USBDevice>> + +获取USB设备列表。 + +**系统能力:** SystemCapability.USB.USBManager + +**返回值:** + +| 类型 | 说明 | +| ---------------------------------------------------- | ------- | +| Array<Readonly<[USBDevice](#usbdevice)>> | 设备信息列表。 | + +**示例:** + +```js +let devicesList = usb.getDevices(); +console.log(`devicesList = ${JSON.stringify(devicesList)}`); +//devicesList 返回的数据结构 +//此处提供一个简单的示例,如下 +[ + { + 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> + +打开USB设备。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备信息以及device,再调用[usb.requestRight](#usbrequestright)获取设备请求权限。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| device | [USBDevice](#usbdevice) | 是 | USB设备信息。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Readonly<[USBDevicePipe](#usbdevicepipe)> | 指定的传输通道对象。 | + +**示例:** + +```js +let devicepipe= usb.connectDevice(device); +console.log(`devicepipe = ${JSON.stringify(devicepipe)}`); +``` + +## usb.hasRight + +hasRight(deviceName: string): boolean + +判断是否有权访问该设备。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| deviceName | string | 是 | 设备名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | true表示有访问设备的权限,false表示没有访问设备的权限。 | + +**示例:** + +```js +let devicesName="1-1"; +let bool = usb.hasRight(devicesName); +console.log(bool); +``` + +## usb.requestRight + +requestRight(deviceName: string): Promise<boolean> + +请求软件包的临时权限以访问设备。使用Promise异步回调。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| deviceName | string | 是 | 设备名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<boolean> | Promise对象,返回临时权限的申请结果。返回true表示临时权限申请成功;返回false则表示临时权限申请失败。 | + +**示例:** + +```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 + +注册通信接口。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备信息以及interfaces;调用[usb.requestRight](#usbrequestright)获取设备请求权限;调用[usb.connectDevice](#usbconnectdevice)接口得到devicepipe作为参数。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定总线号和设备地址。 | +| iface | [USBInterface](#usbinterface) | 是 | 用于确定需要获取接口的索引。 | +| force | boolean | 否 | 可选参数,是否强制获取。默认值为false ,表示不强制获取。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 注册通信接口成功返回0;注册通信接口失败返回其他错误码。 | + +**示例:** + +```js +let ret = usb.claimInterface(devicepipe, interfaces); +console.log(`claimInterface = ${ret}`); +``` + +## usb.releaseInterface + +releaseInterface(pipe: USBDevicePipe, iface: USBInterface): number + +释放注册过的通信接口。 + +需要调用[usb.claimInterface](#usbclaiminterface)先获取接口,才能使用此方法释放接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定总线号和设备地址。 | +| iface | [USBInterface](#usbinterface) | 是 | 用于确定需要释放接口的索引。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 释放接口成功返回0;释放接口失败返回其他错误码。 | + +**示例:** + +```js +let ret = usb.releaseInterface(devicepipe, interfaces); +console.log(`releaseInterface = ${ret}`); +``` + +## usb.setConfiguration + +setConfiguration(pipe: USBDevicePipe, config: USBConfig): number + +设置设备配置。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备信息以及config;调用[usb.requestRight](#usbrequestright)获取设备请求权限;调用[usb.connectDevice](#usbconnectdevice)得到devicepipe作为参数。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定总线号和设备地址。 | +| config | [USBConfig](#usbconfig) | 是 | 用于确定需要设置的配置。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 设置设备配置成功返回0;设置设备配置失败返回其他错误码。 | + +**示例:** + +```js +let ret = usb.setConfiguration(devicepipe, config); +console.log(`setConfiguration = ${ret}`); +``` + +## usb.setInterface + +setInterface(pipe: USBDevicePipe, iface: USBInterface): number + +设置设备接口。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备列表以及interfaces;调用[usb.requestRight](#usbrequestright)获取设备请求权限;调用[usb.connectDevice](#usbconnectdevice)得到devicepipe作为参数;调用[usb.claimInterface](#usbclaiminterface)注册通信接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ----- | ------------------------------- | --- | ------------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定总线号和设备地址。 | +| iface | [USBInterface](#usbinterface) | 是 | 用于确定需要设置的接口。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 设置设备接口成功返回0;设置设备接口失败返回其他错误码。 | + +**示例:** + +```js +let ret = usb.setInterface(devicepipe, interfaces); +console.log(`setInterface = ${ret}`); +``` + +## usb.getRawDescriptor + +getRawDescriptor(pipe: USBDevicePipe): Uint8Array + +获取原始的USB描述符。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备列表;调用[usb.requestRight](#usbrequestright)获取设备请求权限;调用[usb.connectDevice](#usbconnectdevice)接口得到devicepipe作为参数。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定总线号和设备地址。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Uint8Array | 返回获取的原始数据;失败返回undefined。 | + +**示例:** + +```js +let ret = usb.getRawDescriptor(devicepipe); +``` + +## usb.getFileDescriptor + +getFileDescriptor(pipe: USBDevicePipe): number + +获取文件描述符。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备列表;调用[usb.requestRight](#usbrequestright)获取设备请求权限;调用[usb.connectDevice](#usbconnectdevice)接口得到devicepipe作为参数。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定总线号和设备地址。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | -------------------- | +| number | 返回设备对应的文件描述符;失败返回-1。 | + +**示例:** + +```js +let ret = usb.getFileDescriptor(devicepipe); +``` + +## usb.controlTransfer + +controlTransfer(pipe: USBDevicePipe, contrlparam: USBControlParams, timeout?: number): Promise<number> + +控制传输。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备列表;调用[usb.requestRight](#usbrequestright)获取设备请求权限;调用[usb.connectDevice](#usbconnectdevice)接口得到devicepipe作为参数。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定设备。 | +| contrlparam | [USBControlParams](#usbcontrolparams) | 是 | 控制传输参数。 | +| timeout | number | 否 | 超时时间(单位:ms),可选参数,默认为0不超时。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | Promise对象,获取传输或接收到的数据块大小。失败返回-1。 | + +**示例:** + +```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> + +批量传输。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备信息列表以及endpoint;再调用[usb.requestRight](#usbrequestright)获取设备请求权限;然后调用[usb.connectDevice](#usbconnectdevice)接口得到返回数据devicepipe之后,再次获取接口[usb.claimInterface](#usbclaiminterface);再调用usb.bulkTransfer接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定设备。 | +| endpoint | [USBEndpoint](#usbendpoint) | 是 | 用于确定传输的端口。 | +| buffer | Uint8Array | 是 | 用于写入或读取的缓冲区。 | +| timeout | number | 否 | 超时时间(单位:ms),可选参数,默认为0不超时。| + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| Promise<number> | Promise对象,获取传输或接收到的数据块大小。失败返回-1。 | + +**示例:** + +```js +//usb.getDevices 接口返回数据集合,取其中一个设备对象,并获取权限 。 +//把获取到的设备对象作为参数传入usb.connectDevice;当usb.connectDevice接口成功返回之后; +//才可以调用第三个接口usb.claimInterface.当usb.claimInterface 调用成功以后,再调用该接口。 +usb.bulkTransfer(devicepipe, endpoint, buffer).then((ret) => { + console.log(`bulkTransfer = ${JSON.stringify(ret)}`); +}); +``` + +## usb.closePipe + +closePipe(pipe: USBDevicePipe): number + +关闭设备消息控制通道。 + +需要调用[usb.getDevices](#usbgetdevices)获取设备列表;调用[usb.requestRight](#usbrequestright)获取设备请求权限;调用[usb.connectDevice](#usbconnectdevice)得到devicepipe作为参数。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| pipe | [USBDevicePipe](#usbdevicepipe) | 是 | 用于确定USB设备消息控制通道。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| number | 关闭设备消息控制通道成功返回0;关闭设备消息控制通道失败返回其他错误码。 | + +**示例:** + +```js +let ret = usb.closePipe(devicepipe); +console.log(`closePipe = ${ret}`); +``` + +## usb.usbFunctionsFromString9+ + +usbFunctionsFromString(funcs: string): number + +在设备模式下,将字符串形式的USB功能列表转化为数字掩码。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | ---------------------- | +| funcs | string | 是 | 字符串形式的功能列表。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------ | +| number | 转化后的数字掩码。 | + +**示例:** + +```js +let funcs = "acm"; +let ret = usb.usbFunctionsFromString(funcs); +``` + +## usb.usbFunctionsToString9+ + +usbFunctionsToString(funcs: FunctionType): string + +在设备模式下,将数字掩码形式的USB功能列表转化为字符串。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ----------------- | +| funcs | [FunctionType](#functiontype9) | 是 | USB功能数字掩码。 | + +**返回值:** + +| 类型 | 说明 | +| ------ | ------------------------------ | +| string | 转化后的字符串形式的功能列表。 | + +**示例:** + +```js +let funcs = ACM | ECM; +let ret = usb.usbFunctionsToString(funcs); +``` + +## usb.setCurrentFunctions9+ + +setCurrentFunctions(funcs: FunctionType): Promise\ + +在设备模式下,设置当前的USB功能列表。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------------------------------ | ---- | ----------------- | +| funcs | [FunctionType](#functiontype9) | 是 | USB功能数字掩码。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | Promise对象,返回设置成功与否的结果。true表示设置成功,false表示设置失败。 | + +**示例:** + +```js +let funcs = HDC; +let ret = usb.setCurrentFunctions(funcs); +``` + +## usb.getCurrentFunctions9+ + +getCurrentFunctions(): FunctionType + +在设备模式下,获取当前的USB功能列表的数字组合掩码。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | --------------------------------- | +| [FunctionType](#functiontype9) | 当前的USB功能列表的数字组合掩码。 | + +**示例:** + +```js +let ret = usb.getCurrentFunctions(); +``` + +## usb.getPorts9+ + +getPorts(): Array\ + +获取所有物理USB端口描述信息。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**返回值:** + +| 类型 | 说明 | +| ----------------------------- | --------------------- | +| [Array\](#usbport9) | USB端口描述信息列表。 | + +**示例:** + +```js +let ret = usb.getPorts(); +``` + +## usb.getSupportedModes9+ + +getSupportedModes(portId: number): PortModeType + +获取指定的端口支持的模式列表的组合掩码。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| ------ | ------ | ---- | -------- | +| portId | number | 是 | 端口号。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------------------ | -------------------------- | +| [PortModeType](#portmodetype9) | 支持的模式列表的组合掩码。 | + +**示例:** + +```js +let ret = usb.getSupportedModes(0); +``` + +## usb.setPortRoles9+ + +setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ + +设置指定的端口支持的角色模式,包含充电角色、数据传输角色。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| --------- | -------------------------------- | ---- | ---------------- | +| portId | number | 是 | 端口号。 | +| powerRole | [PowerRoleType](#powerroletype9) | 是 | 充电的角色。 | +| dataRole | [DataRoleType](#dataroletype9) | 是 | 数据传输的角色。 | + +**返回值:** + +| 类型 | 说明 | +| ------------------ | ------------------------------------------------------------ | +| Promise\ | Promise对象,返回设置成功与否的结果。true表示设置成功,false表示设置失败。 | + +**示例:** + +```js +let ret = usb.getSupportedModes(0); +``` + +## USBEndpoint + +通过USB发送和接收数据的端口。通过[USBInterface](#usbinterface)获取。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| ------------- | ------------------------------------------- | ------------- | +| address | number | 端点地址。 | +| attributes | number | 端点属性。 | +| interval | number | 端点间隔。 | +| maxPacketSize | number | 端点最大数据包大小。 | +| direction | [USBRequestDirection](#usbrequestdirection) | 端点的方向。 | +| number | number | 端点号。 | +| type | number | 端点类型。 | +| interfaceId | number | 端点所属的接口的唯一标识。 | + +## USBInterface + +一个[USBConfig](#usbconfig)中可以含有多个USBInterface,每个USBInterface提供一个功能。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| ---------------- | ---------------------------------------- | --------------------- | +| id | number | 接口的唯一标识。 | +| protocol | number | 接口的协议。 | +| clazz | number | 设备类型。 | +| subClass | number | 设备子类。 | +| alternateSetting | number | 在同一个接口中的多个描述符中进行切换设置。 | +| name | string | 接口名称。 | +| endpoints | Array<[USBEndpoint](#usbendpoint)> | 当前接口所包含的端点。 | + +## USBConfig + +USB配置,一个[USBDevice](#usbdevice)中可以含有多个配置。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| -------------- | ------------------------------------------------ | --------------- | +| id | number | 配置的唯一标识。 | +| attributes | number | 配置的属性。 | +| maxPower | number | 最大功耗,以毫安为单位。 | +| name | string | 配置的名称,可以为空。 | +| isRemoteWakeup | boolean | 检查当前配置是否支持远程唤醒。 | +| isSelfPowered | boolean | 检查当前配置是否支持独立电源。 | +| interfaces | Array <[USBInterface](#usbinterface)> | 配置支持的接口属性。 | + +## USBDevice + +USB设备信息。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| ---------------- | ------------------------------------ | ---------- | +| busNum | number | 总线地址。 | +| devAddress | number | 设备地址。 | +| serial | string | 序列号。 | +| name | string | 设备名字。 | +| manufacturerName | string | 产商信息。 | +| productName | string | 产品信息。 | +| version | string | 版本。 | +| vendorId | number | 厂商ID。 | +| productId | number | 产品ID。 | +| clazz | number | 设备类。 | +| subClass | number | 设备子类。 | +| protocol | number | 设备协议码。 | +| configs | Array<[USBConfig](#usbconfig)> | 设备配置描述符信息。 | + +## USBDevicePipe + +USB设备消息传输通道,用于确定设备。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| ---------- | ------ | ----- | +| busNum | number | 总线地址。 | +| devAddress | number | 设备地址。 | + +## USBControlParams + +控制传输参数。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| ------- | ----------------------------------------------- | ---------------- | +| request | number | 请求类型。 | +| target | [USBRequestTargetType](#usbrequesttargettype) | 请求目标类型。 | +| reqType | [USBControlRequestType](#usbcontrolrequesttype) | 请求控制类型。 | +| value | number | 请求参数。 | +| index | number | 请求参数value对应的索引值。 | +| data | Uint8Array | 用于写入或读取的缓冲区。 | + +## USBPort9+ + +USB设备端口。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| -------------- | -------------------------------- | ----------------------------------- | +| id | number | USB端口唯一标识。 | +| supportedModes | [PortModeType](#portmodetype9) | USB端口所支持的模式的数字组合掩码。 | +| status | [USBPortStatus](#usbportstatus9) | USB端口角色。 | + +## USBPortStatus9+ + +USB设备端口角色信息。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 参数类型 | 说明 | +| ---------------- | -------- | ---------------------- | +| currentMode | number | 当前的USB模式。 | +| currentPowerRole | number | 当前设备充电模式。 | +| currentDataRole | number | 当前设备数据传输模式。 | + +## USBRequestTargetType + +请求目标类型。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 值 | 说明 | +| ---------------------------- | ---- | ------ | +| USB_REQUEST_TARGET_DEVICE | 0 | 设备。 | +| USB_REQUEST_TARGET_INTERFACE | 1 | 接口。 | +| USB_REQUEST_TARGET_ENDPOINT | 2 | 端点。 | +| USB_REQUEST_TARGET_OTHER | 3 | 其他。 | + +## USBControlRequestType + +控制请求类型。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 值 | 说明 | +| ------------------------- | ---- | ------ | +| USB_REQUEST_TYPE_STANDARD | 0 | 标准。 | +| USB_REQUEST_TYPE_CLASS | 1 | 类。 | +| USB_REQUEST_TYPE_VENDOR | 2 | 厂商。 | + +## USBRequestDirection + +请求方向。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 值 | 说明 | +| --------------------------- | ---- | ------------------------ | +| USB_REQUEST_DIR_TO_DEVICE | 0 | 写数据,主设备往从设备。 | +| USB_REQUEST_DIR_FROM_DEVICE | 0x80 | 读数据,从设备往主设备。 | + +## FunctionType9+ + +USB设备侧功能。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 值 | 说明 | +| ------------ | ---- | ---------- | +| NONE | 0 | 没有功能。 | +| ACM | 1 | acm功能。 | +| ECM | 2 | ecm功能。 | +| HDC | 4 | hdc功能。 | +| MTP | 8 | 暂不支持。 | +| PTP | 16 | 暂不支持。 | +| RNDIS | 32 | 暂不支持。 | +| MIDI | 64 | 暂不支持。 | +| AUDIO_SOURCE | 128 | 暂不支持。 | +| NCM | 256 | 暂不支持。 | + +## PortModeType9+ + +USB端口模式类型。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 值 | 说明 | +| --------- | ---- | ---------------------------------------------------- | +| NONE | 0 | 无。 | +| UFP | 1 | 数据上行,需要外部供电。 | +| DFP | 2 | 数据下行,对外提供电源。 | +| DRP | 3 | 既可以做DFP(Host),也可以做UFP(Device),当前不支持。 | +| NUM_MODES | 4 | 当前不支持。 | + +## PowerRoleType9+ + +电源角色类型。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 值 | 说明 | +| ------ | ---- | ---------- | +| NONE | 0 | 无。 | +| SOURCE | 1 | 外部供电。 | +| SINK | 2 | 内部供电。 | + +## DataRoleType9+ + +数据角色类型。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +| 名称 | 值 | 说明 | +| ------ | ---- | ------------ | +| NONE | 0 | 无。 | +| HOST | 1 | 主设备角色。 | +| DEVICE | 2 | 从设备角色。 | + diff --git a/zh-cn/application-dev/reference/apis/js-apis-usb.md b/zh-cn/application-dev/reference/apis/js-apis-usb.md index 5e0aee35a77720f3510a1438876cc0f46ac9d200..ffa8e471f0e279279714c637cc16ecdd0f4a96f7 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-usb.md +++ b/zh-cn/application-dev/reference/apis/js-apis-usb.md @@ -1,22 +1,22 @@ # USB管理 -本模块主要提供管理USB设备的相关功能,包括查询USB设备列表、批量数据传输、控制命令传输、权限控制等。 +本模块主要提供管理USB设备的相关功能,包括主设备上查询USB设备列表、批量数据传输、控制命令传输、权限控制等;从设备上端口管理、功能切换及查询等。 > **说明:** > -> 本模块首批接口从API version 8开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 +> 本模块首批接口从API version 9开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。 ## 导入模块 ```js -import usb from "@ohos.usb"; +import usb from "@ohos.usbV9"; ``` ## usb.getDevices getDevices(): Array<Readonly<USBDevice>> -获取USB设备列表。 +获取接入主设备的USB设备列表。如果没有设备接入,那么将会返回一个空的列表。 **系统能力:** SystemCapability.USB.USBManager @@ -89,7 +89,7 @@ connectDevice(device: USBDevice): Readonly<USBDevicePipe> 打开USB设备。 -需要调用[usb.getDevices](#usbgetdevices)获取设备信息以及device,再调用[usb.requestRight](#usbrequestright)获取设备请求权限。 +需要调用[usb.getDevices](#usbgetdevices)获取设备信息以及device,再调用[usb.requestRight](#usbrequestright)请求使用该设备的权限。 **系统能力:** SystemCapability.USB.USBManager @@ -105,10 +105,26 @@ connectDevice(device: USBDevice): Readonly<USBDevicePipe> | -------- | -------- | | Readonly<[USBDevicePipe](#usbdevicepipe)> | 指定的传输通道对象。 | +**错误码:** + +以下错误码的详细介绍参见[USB错误码](../errorcodes/errcode-usb.md)。 + +| 错误码ID | 错误信息 | +| -------- | -------- | +| 14400001 |Permission denied. Need call requestRight to get permission. | + **示例:** ```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)}`); ``` @@ -169,6 +185,70 @@ usb.requestRight(devicesName).then((ret) => { }); ``` +## usb.removeRight + +removeRight(deviceName: string): boolean; + +移除软件包访问设备的权限。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| deviceName | string | 是 | 设备名称。 | + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 返回权限移除结果。返回true表示权限移除成功;返回false则表示权限移除失败。 | + +**示例:** + +```js +let devicesName="1-1"; +if (usb.removeRight(devicesName) { + console.log(`Succeed in removing right`); +} +``` + +## usb.addRight + +addRight(bundleName: string, deviceName: string): boolean; + +添加软件包访问设备的权限。 + +[requestRight](#usbrequestright)的会触发弹框请求用户授权;addRight不会触发弹框,而是直接添加软件包访问设备的权限。 + +**系统接口:** 此接口为系统接口。 + +**系统能力:** SystemCapability.USB.USBManager + +**参数:** + +| 参数名 | 类型 | 必填 | 说明 | +| -------- | -------- | -------- | -------- | +| deviceName | string | 是 | 设备名称。 | +| bundleName | string | 是 | 软件包名称。| + +**返回值:** + +| 类型 | 说明 | +| -------- | -------- | +| boolean | 返回权限添加结果。返回true表示权限添加成功;返回false则表示权限添加失败。 | + +**示例:** + +```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 @@ -443,7 +523,7 @@ let ret = usb.closePipe(devicepipe); console.log(`closePipe = ${ret}`); ``` -## usb.usbFunctionsFromString9+ +## usb.usbFunctionsFromString usbFunctionsFromString(funcs: string): number @@ -472,7 +552,7 @@ let funcs = "acm"; let ret = usb.usbFunctionsFromString(funcs); ``` -## usb.usbFunctionsToString9+ +## usb.usbFunctionsToString usbFunctionsToString(funcs: FunctionType): string @@ -486,7 +566,7 @@ usbFunctionsToString(funcs: FunctionType): string | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------ | ---- | ----------------- | -| funcs | [FunctionType](#functiontype9) | 是 | USB功能数字掩码。 | +| funcs | [FunctionType](#functiontype) | 是 | USB功能数字掩码。 | **返回值:** @@ -501,7 +581,7 @@ let funcs = ACM | ECM; let ret = usb.usbFunctionsToString(funcs); ``` -## usb.setCurrentFunctions9+ +## usb.setCurrentFunctions setCurrentFunctions(funcs: FunctionType): Promise\ @@ -515,7 +595,7 @@ setCurrentFunctions(funcs: FunctionType): Promise\ | 参数名 | 类型 | 必填 | 说明 | | ------ | ------------------------------ | ---- | ----------------- | -| funcs | [FunctionType](#functiontype9) | 是 | USB功能数字掩码。 | +| funcs | [FunctionType](#functiontype) | 是 | USB功能数字掩码。 | **返回值:** @@ -530,7 +610,7 @@ let funcs = HDC; let ret = usb.setCurrentFunctions(funcs); ``` -## usb.getCurrentFunctions9+ +## usb.getCurrentFunctions getCurrentFunctions(): FunctionType @@ -544,7 +624,7 @@ getCurrentFunctions(): FunctionType | 类型 | 说明 | | ------------------------------ | --------------------------------- | -| [FunctionType](#functiontype9) | 当前的USB功能列表的数字组合掩码。 | +| [FunctionType](#functiontype) | 当前的USB功能列表的数字组合掩码。 | **示例:** @@ -552,7 +632,7 @@ getCurrentFunctions(): FunctionType let ret = usb.getCurrentFunctions(); ``` -## usb.getPorts9+ +## usb.getPorts getPorts(): Array\ @@ -566,7 +646,7 @@ getPorts(): Array\ | 类型 | 说明 | | ----------------------------- | --------------------- | -| [Array\](#usbport9) | USB端口描述信息列表。 | +| [Array\](#usbport) | USB端口描述信息列表。 | **示例:** @@ -574,7 +654,7 @@ getPorts(): Array\ let ret = usb.getPorts(); ``` -## usb.getSupportedModes9+ +## usb.getSupportedModes getSupportedModes(portId: number): PortModeType @@ -594,7 +674,7 @@ getSupportedModes(portId: number): PortModeType | 类型 | 说明 | | ------------------------------ | -------------------------- | -| [PortModeType](#portmodetype9) | 支持的模式列表的组合掩码。 | +| [PortModeType](#portmodetype) | 支持的模式列表的组合掩码。 | **示例:** @@ -602,7 +682,7 @@ getSupportedModes(portId: number): PortModeType let ret = usb.getSupportedModes(0); ``` -## usb.setPortRoles9+ +## usb.setPortRoles setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): Promise\ @@ -617,8 +697,8 @@ setPortRoles(portId: number, powerRole: PowerRoleType, dataRole: DataRoleType): | 参数名 | 类型 | 必填 | 说明 | | --------- | -------------------------------- | ---- | ---------------- | | portId | number | 是 | 端口号。 | -| powerRole | [PowerRoleType](#powerroletype9) | 是 | 充电的角色。 | -| dataRole | [DataRoleType](#dataroletype9) | 是 | 数据传输的角色。 | +| powerRole | [PowerRoleType](#powerroletype) | 是 | 充电的角色。 | +| dataRole | [DataRoleType](#dataroletype) | 是 | 数据传输的角色。 | **返回值:** @@ -729,7 +809,7 @@ USB设备消息传输通道,用于确定设备。 | index | number | 请求参数value对应的索引值。 | | data | Uint8Array | 用于写入或读取的缓冲区。 | -## USBPort9+ +## USBPort USB设备端口。 @@ -740,10 +820,10 @@ USB设备端口。 | 名称 | 参数类型 | 说明 | | -------------- | -------------------------------- | ----------------------------------- | | id | number | USB端口唯一标识。 | -| supportedModes | [PortModeType](#portmodetype9) | USB端口所支持的模式的数字组合掩码。 | -| status | [USBPortStatus](#usbportstatus9) | USB端口角色。 | +| supportedModes | [PortModeType](#portmodetype) | USB端口所支持的模式的数字组合掩码。 | +| status | [USBPortStatus](#usbportstatus) | USB端口角色。 | -## USBPortStatus9+ +## USBPortStatus USB设备端口角色信息。 @@ -793,7 +873,7 @@ USB设备端口角色信息。 | USB_REQUEST_DIR_TO_DEVICE | 0 | 写数据,主设备往从设备。 | | USB_REQUEST_DIR_FROM_DEVICE | 0x80 | 读数据,从设备往主设备。 | -## FunctionType9+ +## FunctionType USB设备侧功能。 @@ -814,7 +894,7 @@ USB设备侧功能。 | AUDIO_SOURCE | 128 | 暂不支持。 | | NCM | 256 | 暂不支持。 | -## PortModeType9+ +## PortModeType USB端口模式类型。 @@ -830,7 +910,7 @@ USB端口模式类型。 | DRP | 3 | 既可以做DFP(Host),也可以做UFP(Device),当前不支持。 | | NUM_MODES | 4 | 当前不支持。 | -## PowerRoleType9+ +## PowerRoleType 电源角色类型。 @@ -844,7 +924,7 @@ USB端口模式类型。 | SOURCE | 1 | 外部供电。 | | SINK | 2 | 内部供电。 | -## DataRoleType9+ +## DataRoleType 数据角色类型。 diff --git a/zh-cn/application-dev/reference/apis/js-apis-window.md b/zh-cn/application-dev/reference/apis/js-apis-window.md index 0d28afc2ae1bc5b80f25077a4b9fa2837df5ec9f..126504770692cb365ca69305bb4cf6896ad3481b 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-window.md +++ b/zh-cn/application-dev/reference/apis/js-apis-window.md @@ -66,12 +66,12 @@ import window from '@ohos.window'; **系统能力:** SystemCapability.WindowManager.WindowManager.Core -| 名称 | 值 | 说明 | -|----------------------------------|-----| ----------------- | -| TYPE_SYSTEM | 0 | 表示系统默认区域。| -| TYPE_CUTOUT | 1 | 表示刘海屏区域。 | -| TYPE_SYSTEM_GESTURE9+ | 2 | 表示手势区域。 | -| TYPE_KEYBOARD9+ | 3 | 表示软键盘区域。 | +| 名称 | 值 | 说明 | +| -------------------------------- | ---- | ------------------------------------------------------------ | +| TYPE_SYSTEM | 0 | 表示系统默认区域。一般包括状态栏、导航栏和Dock栏,各设备系统定义可能不同。 | +| TYPE_CUTOUT | 1 | 表示刘海屏区域。 | +| TYPE_SYSTEM_GESTURE9+ | 2 | 表示手势区域。 | +| TYPE_KEYBOARD9+ | 3 | 表示软键盘区域。 | ## WindowMode7+ @@ -108,14 +108,14 @@ import window from '@ohos.window'; **系统能力:** SystemCapability.WindowManager.WindowManager.Core -| 名称 | 参数类型 | 可读 | 可写 | 说明 | -| -------------------------------------- | -------- | ---- | ---- | ------------------------------------------------------------ | -| statusBarColor | string | 否 | 是 | 状态栏背景颜色,为十六进制RGB或ARGB颜色,不区分大小写,例如`#00FF00`或`#FF00FF00`。 | -| isStatusBarLightIcon7+ | boolean | 否 | 是 | 状态栏图标是否为高亮状态。true表示高亮;false表示不高亮。 | -| statusBarContentColor8+ | string | 否 | 是 | 状态栏文字颜色。 | -| navigationBarColor | string | 否 | 是 | 导航栏背景颜色,为十六进制RGB或ARGB颜色,不区分大小写,例如`#00FF00`或`#FF00FF00`。 | -| isNavigationBarLightIcon7+ | boolean | 否 | 是 | 导航栏图标是否为高亮状态。true表示高亮;false表示不高亮。 | -| navigationBarContentColor8+ | string | 否 | 是 | 导航栏文字颜色。 | +| 名称 | 参数类型 | 可读 | 可写 | 必填 | 说明 | +| -------------------------------------- | -------- | ---- | ---- | ---- | ------------------------------------------------------------ | +| statusBarColor | string | 否 | 是 | 否 | 状态栏背景颜色,为十六进制RGB或ARGB颜色,不区分大小写,例如`#00FF00`或`#FF00FF00`。默认值:`#0x66000000`。 | +| isStatusBarLightIcon7+ | boolean | 否 | 是 | 否 | 状态栏图标是否为高亮状态。true表示高亮;false表示不高亮。默认值:false。 | +| statusBarContentColor8+ | string | 否 | 是 | 否 | 状态栏文字颜色。当设置此属性后, `isStatusBarLightIcon`属性设置无效。默认值:`0xE5FFFFFF。` | +| navigationBarColor | string | 否 | 是 | 否 | 导航栏背景颜色,为十六进制RGB或ARGB颜色,不区分大小写,例如`#00FF00`或`#FF00FF00`。默认值:`#0x66000000。` | +| isNavigationBarLightIcon7+ | boolean | 否 | 是 | 否 | 导航栏图标是否为高亮状态。true表示高亮;false表示不高亮。默认值:false。 | +| navigationBarContentColor8+ | string | 否 | 是 | 否 | 导航栏文字颜色。当设置此属性后, `isNavigationBarLightIcon`属性设置无效。默认值:`#0xE5FFFFFF。` | ## Orientation9+ @@ -2082,9 +2082,6 @@ setWindowSystemBarProperties(systemBarProperties: SystemBarProperties, callback: let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - //以下两个属性从API Version7开始支持 - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, //以下两个属性从API Version8开始支持 statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' @@ -2137,9 +2134,6 @@ setWindowSystemBarProperties(systemBarProperties: SystemBarProperties): Promise& let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - //以下两个属性从API Version7开始支持 - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, //以下两个属性从API Version8开始支持 statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' @@ -2339,7 +2333,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -2390,7 +2384,7 @@ loadContent(path: string, storage: LocalStorage): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | **返回值:** @@ -4878,9 +4872,6 @@ setSystemBarProperties(systemBarProperties: SystemBarProperties, callback: Async let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - //以下两个属性从API Version7开始支持 - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, //以下两个属性从API Version8开始支持 statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' @@ -4924,9 +4915,6 @@ setSystemBarProperties(systemBarProperties: SystemBarProperties): Promise<voi let SystemBarProperties={ statusBarColor: '#ff00ff', navigationBarColor: '#00ff00', - //以下两个属性从API Version7开始支持 - isStatusBarLightIcon: true, - isNavigationBarLightIcon:false, //以下两个属性从API Version8开始支持 statusBarContentColor:'#ffffff', navigationBarContentColor:'#00ffff' @@ -6197,7 +6185,7 @@ loadContent(path: string, storage: LocalStorage, callback: AsyncCallback<void | 参数名 | 类型 | 必填 | 说明 | | -------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 是 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | | callback | AsyncCallback<void> | 是 | 回调函数。 | **错误码:** @@ -6249,7 +6237,7 @@ loadContent(path: string, storage?: LocalStorage): Promise<void> | 参数名 | 类型 | 必填 | 说明 | | ------- | ----------------------------------------------- | ---- | ------------------------------------------------------------ | | path | string | 是 | 设置加载页面的路径。 | -| storage | [LocalStorage](../../ui/ui-ts-local-storage.md) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | +| storage | [LocalStorage](../../quick-start/arkts-state-mgmt-application-level.md#localstorage) | 否 | 存储单元,为应用程序范围内的可变状态属性和非可变状态属性提供存储。 | **返回值:** diff --git a/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md b/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md index a44870846919ed0e03521ea7a00ee1d41fdf7dec..bce80283f00a928ce65c96c45d783ee3717b608c 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md +++ b/zh-cn/application-dev/reference/apis/js-apis-workScheduler.md @@ -53,7 +53,7 @@ startWork(work: WorkInfo): boolean mykey3: 1.5 } } - var res = workScheduler.startWork(workInfo); + let res = workScheduler.startWork(workInfo); console.info(`workschedulerLog res: ${res}`); ``` @@ -94,7 +94,7 @@ stopWork(work: WorkInfo, needCancel?: boolean): boolean mykey3: 1.5 } } - var res = workScheduler.stopWork(workInfo, false); + let res = workScheduler.stopWork(workInfo, false); console.info(`workschedulerLog res: ${res}`); ``` diff --git a/zh-cn/application-dev/reference/apis/js-apis-worker.md b/zh-cn/application-dev/reference/apis/js-apis-worker.md index 6387c195e12bde4eda240530df58a452a2a28e68..14a34cc66e670faaa7a59280a4a3827722837217 100644 --- a/zh-cn/application-dev/reference/apis/js-apis-worker.md +++ b/zh-cn/application-dev/reference/apis/js-apis-worker.md @@ -80,7 +80,7 @@ const workerStageModel02 = new worker.Worker('entry/ets/pages/workers/worker.ts' ``` 同时,需在工程的模块级build-profile.json5文件的buildOption属性中添加配置信息,主要分为下面两种情况: -(1) 目录同级( **不添加也可以** ) +(1) 目录同级 FA模型: @@ -103,7 +103,7 @@ Stage模型: } } ``` -(2) 目录不同级( **必须添加** ) +(2) 目录不同级 FA模型: ```json @@ -700,8 +700,8 @@ parentPort.onerror = function(e){ | Array | | 是 | | Map | | 是 | | Set | | 是 | -| Object | 只支持Create from literal的简单Object,不支持带function的 | 是 | -| ArrayBuffer | 提供transfer能力 | 是 | +| Object | 只支持Plain Object,不支持带function的 | 是 | +| ArrayBuffer | 提供transfer能力 | 是 | | TypedArray | | 是 | ### 内存模型 diff --git a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md index 51c100cadd33b3f00b64fc5dfb44d3c8f23e9643..ab042734224a6df8031ae03a36a68578ef1bc302 100644 --- a/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md +++ b/zh-cn/application-dev/reference/arkui-ts/Readme-CN.md @@ -1,4 +1,4 @@ -# 基于eTS的声明式开发范式 +# 基于ArkTS的声明式开发范式 - 组件通用信息 - 通用事件 @@ -132,12 +132,12 @@ - 画布组件 - [Canvas](ts-components-canvas-canvas.md) - [CanvasRenderingContext2D对象](ts-canvasrenderingcontext2d.md) - - [OffscreenCanvasRenderingContext2D对象](ts-offscreencanvasrenderingcontext2d.md) - - [Lottie](ts-components-canvas-lottie.md) - - [Path2D对象](ts-components-canvas-path2d.md) - [CanvasGradient对象](ts-components-canvas-canvasgradient.md) - [ImageBitmap对象](ts-components-canvas-imagebitmap.md) - [ImageData对象](ts-components-canvas-imagedata.md) + - [OffscreenCanvasRenderingContext2D对象](ts-offscreencanvasrenderingcontext2d.md) + - [Path2D对象](ts-components-canvas-path2d.md) + - [Lottie](ts-components-canvas-lottie.md) - 动画 diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/grid-autofill.png b/zh-cn/application-dev/reference/arkui-ts/figures/grid-autofill.png deleted file mode 100644 index c45eee033be4548744fd84bbcb5ba29d17868e69..0000000000000000000000000000000000000000 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/grid-autofill.png and /dev/null differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872492.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872492.png index 5d649492978121a484c2a7a55d4548384c919149..c564bb26b539f1e48acbdb7f2aeeca8df4e4e798 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872492.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872492.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872498.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872498.png index 801bf97495213f41c2b196b2f170af85b156dd5b..6c136313fe0c8774d1209a398d16ecc4b58c2bcd 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872498.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001193872498.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032458.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032458.png index 50726d3e461d7a5dbfec674899fee603aaf41bee..a07986a04b7477eec14c81d08e442d7b332dab83 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032458.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032458.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032462.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032462.png index d3db21e0e3da6d8663f59b2ddabd9e50d6eb1e6a..3d93b0a0a8f5d0b527d407e450a4a13a1de991ab 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032462.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032462.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032480.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032480.png index 5d649492978121a484c2a7a55d4548384c919149..5c0a336a56d0e5a186bd235cd25f9f5e5e7e644f 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032480.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032480.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032666.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032666.png new file mode 100644 index 0000000000000000000000000000000000000000..2b9bc96da366d53da784c92620a69f602f7bff14 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194032666.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192436.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192436.png index e3b4b42aecaef72ed4a08b3566a895b3f9b12343..27556ea43f7c2ecc65b9425e243ea593f02b08ec 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192436.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192436.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192440.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192440.png index 138e011909c2d4738f3cd9671a79ea0c37cb5b87..2a5c5649cc0716abc024aa3656924a456216a4c2 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192440.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194192440.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194352436.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194352436.png index 4fb651372a67eca9de3848baa6b66cac0ee9f173..00097d258d585ec8ad981703c5b265679e867133 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194352436.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001194352436.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238712471.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238712471.png index 8c06945a1790bb0a741b330fe0a9170dd2a3a92d..81710c1186a0c0448d70a443db66c09a4e46d395 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238712471.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238712471.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238832389.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238832389.png index 2eed5759714b99dc039faab67acdfe6d67bfc6ac..5c75654b85d596a346fa5d793ca84991fe859a86 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238832389.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238832389.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238952377.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238952377.png index eb03ebe25132eb551b633d052cdfc984eda432ee..abc9a5667500a749dbceee88aef4caebf5d9df18 100644 Binary files a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238952377.png and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_0000001238952377.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777778.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777778.png new file mode 100644 index 0000000000000000000000000000000000000000..19e99b9ef490fff79e64e33192c97c1a39c6edf9 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777778.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777779.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777779.png new file mode 100644 index 0000000000000000000000000000000000000000..4558b332925757d97d70ee57182c260804629346 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777779.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777780.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777780.png new file mode 100644 index 0000000000000000000000000000000000000000..9b35e8e0fc4bb514584813b79e8889cfe65649a7 Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777780.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777781.png b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777781.png new file mode 100644 index 0000000000000000000000000000000000000000..9e0a95f73b1aec44e6bccd6750a1c9f2815178ee Binary files /dev/null and b/zh-cn/application-dev/reference/arkui-ts/figures/zh-cn_image_000000127777781.png differ diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md index a7d649f25f4546fcc44d145429b7a0f25f2ac07e..de1aaccb15c26e4ff9f7c225b22f4af295f3cfc2 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-canvasrenderingcontext2d.md @@ -1,12 +1,12 @@ # CanvasRenderingContext2D对象 +使用RenderingContext在Canvas组件上进行绘制,绘制对象可以是矩形、文本、图片等。 + > **说明:** > > 从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -使用RenderingContext在Canvas组件上进行绘制,绘制对象可以是矩形、文本、图片等。 - ## 接口 @@ -723,6 +723,7 @@ strokeRect(x: number, y: number, w: number, h: number): void struct StrokeRect { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -766,6 +767,7 @@ clearRect(x: number, y: number, w: number, h: number): void struct ClearRect { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -774,8 +776,8 @@ clearRect(x: number, y: number, w: number, h: number): void .backgroundColor('#ffffff') .onReady(() =>{ this.context.fillStyle = 'rgb(0,0,255)' - this.context.fillRect(0,0,500,500) - this.context.clearRect(20,20,150,100) + this.context.fillRect(20,20,200,200) + this.context.clearRect(30,30,150,100) }) } .width('100%') @@ -811,6 +813,7 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void struct FillText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -855,6 +858,7 @@ strokeText(text: string, x: number, y: number, maxWidth?:number): void struct StrokeText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -923,6 +927,7 @@ measureText(text: string): TextMetrics struct MeasureText { private settings: RenderingContextSettings = new RenderingContextSettings(true); private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -975,6 +980,8 @@ stroke(path?: Path2D): void .onReady(() =>{ this.context.moveTo(25, 25) this.context.lineTo(25, 105) + this.context.lineTo(75, 105) + this.context.lineTo(75, 25) this.context.strokeStyle = 'rgb(0,0,255)' this.context.stroke() }) @@ -1437,7 +1444,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number .backgroundColor('#ffff00') .onReady(() =>{ this.context.beginPath() - this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.context.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) this.context.stroke() }) } @@ -1618,11 +1625,11 @@ clip(fillRule?: CanvasFillRule): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.rect(0, 0, 200, 200) + this.context.rect(0, 0, 100, 200) this.context.stroke() this.context.clip() this.context.fillStyle = "rgb(255,0,0)" - this.context.fillRect(0, 0, 150, 150) + this.context.fillRect(0, 0, 200, 200) }) } .width('100%') @@ -1636,7 +1643,7 @@ clip(fillRule?: CanvasFillRule): void clip(path: Path2D, fillRule?: CanvasFillRule): void -对封闭路径进行填充。该接口为空接口。 +设置当前路径为剪切路径 **参数:** @@ -1646,6 +1653,38 @@ clip(path: Path2D, fillRule?: CanvasFillRule): void | fillRule | CanvasFillRule | 否 | "nonzero" | 指定要剪切对象的规则。
可选参数为:"nonzero", "evenodd"。 | +**示例:** + + ```ts + // xxx.ets +@Entry +@Component +struct Clip { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.rect(80,10,20,130); + region.rect(40,50,100,50); + this.context.clip(region,"evenodd") + this.context.fillStyle = "rgb(255,0,0)" + this.context.fillRect(0, 0, this.context.width, this.context.height) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![zh-cn_image_000000127777779](figures/zh-cn_image_000000127777779.png) + ### filter @@ -1753,9 +1792,10 @@ scale(x: number, y: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.strokeRect(10, 10, 25, 25) + this.context.lineWidth = 3 + this.context.strokeRect(30, 30, 50, 50) this.context.scale(2, 2) // Scale to 200% - this.context.strokeRect(10, 10, 25, 25) + this.context.strokeRect(30, 30, 50, 50) }) } .width('100%') @@ -1985,7 +2025,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: createImageData(sw: number, sh: number): ImageData -创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)。 +创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 **参数:** @@ -1995,23 +2035,21 @@ createImageData(sw: number, sh: number): ImageData | sh | number | 是 | 0 | ImageData的高度。 | -### createImageData - createImageData(imageData: ImageData): ImageData -创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)。 +创建新的ImageData 对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 **参数:** | 参数 | 类型 | 必填 | 默认 | 描述 | | --------- | ---------------------------------------- | ---- | ---- | ----------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | 是 | null | 复制现有的ImageData对象。 | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | 是 | null | 复制现有的ImageData对象。 | **返回值:** | 类型 | 说明 | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象。 | +| [ImageData](ts-components-canvas-imagedata.md) | 新的ImageData对象。 | ### getPixelMap @@ -2039,7 +2077,7 @@ getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap getImageData(sx: number, sy: number, sw: number, sh: number): ImageData -以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagebitmap.md)对象。 +以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagedata.md)对象。 **参数:** @@ -2054,7 +2092,39 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData | 类型 | 说明 | | ---------------------------------------- | -------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象。 | +| [ImageData](ts-components-canvas-imagedata.md) | 新的ImageData对象。 | + + +**示例:** + + ```ts + // xxx.ets +@Entry +@Component +struct GetImageData { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage(this.img,0,0,130,130); + var imagedata = this.context.getImageData(50,50,130,130); + this.context.putImageData(imagedata,150,150); + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![zh-cn_image_000000127777780](figures/zh-cn_image_000000127777780.png) ### putImageData @@ -2063,13 +2133,13 @@ putImageData(imageData: ImageData, dx: number, dy: number): void putImageData(imageData: ImageData, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth: number, dirtyHeight: number): void -使用[ImageData](ts-components-canvas-imagebitmap.md)数据填充新的矩形区域。 +使用[ImageData](ts-components-canvas-imagedata.md)数据填充新的矩形区域。 **参数:** | 参数 | 类型 | 必填 | 默认值 | 描述 | | ----------- | ---------------------------------------- | ---- | ------------ | ----------------------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | 是 | null | 包含像素值的ImageData对象。 | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | 是 | null | 包含像素值的ImageData对象。 | | dx | number | 是 | 0 | 填充区域在x轴方向的偏移量。 | | dy | number | 是 | 0 | 填充区域在y轴方向的偏移量。 | | dirtyX | number | 否 | 0 | 源图像数据矩形裁切范围左上角距离源图像左上角的x轴偏移量。 | @@ -2144,6 +2214,7 @@ setLineDash(segments: number[]): void .onReady(() =>{ this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) + this.context.stroke() }) } .width('100%') @@ -2167,24 +2238,34 @@ getLineDash(): number[] | -------- | ------------------------ | | number[] | 返回数组,该数组用来描述线段如何交替和间距长度。 | + **示例:** ```ts // xxx.ets - @Entry - @Component - struct GetLineDash { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { +@Entry +@Component +struct CanvasGetLineDash { + @State message: string = 'Hello World' + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + console.error('before getlinedash clicked') + let res = this.context.getLineDash() + console.error(JSON.stringify(res)) + }) Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) + .onReady(() => { this.context.arc(100, 75, 50, 0, 6.28) this.context.setLineDash([10,20]) this.context.stroke(); @@ -2192,10 +2273,13 @@ getLineDash(): number[] }) } .width('100%') - .height('100%') } + .height('100%') } +} ``` +![zh-cn_image_000000127777778](figures/zh-cn_image_000000127777778.png) + ### imageSmoothingQuality @@ -2222,7 +2306,7 @@ transferFromImageBitmap(bitmap: ImageBitmap): void | 参数 | 类型 | 描述 | | ------ | ---------------------------------------- | ------------------ | -| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | 待显示的ImageBitmap对象。 | +| bitmap | [ImageBitmap](ts-components-canvas-imagebitmap.md) | 待显示的ImageBitmap对象。 | **示例:** @@ -2230,7 +2314,7 @@ transferFromImageBitmap(bitmap: ImageBitmap): void // xxx.ets @Entry @Component - struct PutImageData { + struct TransferFromImageBitmap { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) @@ -2259,7 +2343,8 @@ transferFromImageBitmap(bitmap: ImageBitmap): void } } ``` - ![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png) + ![zh-cn_image_0000001238952387](figures/zh-cn_image_0000001238952387.png) + ### toDataURL @@ -2330,7 +2415,11 @@ restore(): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.restore() + this.context.save(); // save the default state + this.context.fillStyle = "green"; + this.context.fillRect(20, 20, 100, 100); + this.context.restore(); // restore to the default state + this.context.fillRect(150, 75, 100, 100); }) } .width('100%') @@ -2338,6 +2427,7 @@ restore(): void } } ``` + ![zh-cn_image_000000127777781](figures/zh-cn_image_000000127777781.png) ### save @@ -2363,14 +2453,19 @@ save(): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.context.save() - }) + this.context.save(); // save the default state + this.context.fillStyle = "green"; + this.context.fillRect(20, 20, 100, 100); + this.context.restore(); // restore to the default state + this.context.fillRect(150, 75, 100, 100); + }) } .width('100%') .height('100%') } } ``` + ![zh-cn_image_000000127777781](figures/zh-cn_image_000000127777781.png) ### createLinearGradient diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md index 1df79983e2e4560e438b22fe63e65952917e5fe8..d8d8bf52419bc243d81b7e3f47598560bc3851e0 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvas.md @@ -1,9 +1,13 @@ # Canvas -> **说明:** 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 - 提供画布组件,用于自定义绘制图形。 +> **说明:** +> +> 该组件从API Version 8开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 + + + ## 权限列表 无 @@ -18,9 +22,9 @@ Canvas(context?: CanvasRenderingContext2D) **参数:** - | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | - | ------- | ---------------------------------------- | ---- | ---- | ---------------------------- | - | context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | 否 | - | 见CanvasRenderingContext2D对象。 | +| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | +| ------- | ---------------------------------------- | ---- | ---- | ---------------------------- | +| context | [CanvasRenderingContext2D](ts-canvasrenderingcontext2d.md) | 否 | - | 见CanvasRenderingContext2D对象。 | ## 属性 @@ -34,7 +38,8 @@ Canvas(context?: CanvasRenderingContext2D) | ----------------------------- | ---- | -------------------- | | onReady(event: () => void) | 无 | Canvas组件初始化完成时的事件回调,该事件之后Canvas组件宽高确定且可获取,可使用Canvas相关API进行绘制。 | -## 示例 + +**示例:** ```ts // xxx.ets @@ -50,8 +55,8 @@ struct CanvasExample { .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - this.context.fillRect(0,30,100,100) + .onReady(() => { + this.context.fillRect(0, 30, 100, 100) }) } .width('100%') @@ -59,3 +64,4 @@ struct CanvasExample { } } ``` + ![zh-cn_image_0000001194032666](figures/zh-cn_image_0000001194032666.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md index df4ed8fcbe5e254392cfaeb77d38167b2d9c1dd9..191b9ffab8e744a75626d610f1ade17d89d61025 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-canvasgradient.md @@ -1,11 +1,12 @@ # CanvasGradient对象 +渐变对象。 + > **说明:** +> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -渐变对象。 - ## addColorStop @@ -13,13 +14,16 @@ addColorStop(offset: number, color: string): void 设置渐变断点值,包括偏移和颜色。 -- 参数 + +**参数:** + | 参数 | 类型 | 必填 | 默认值 | 描述 | | ------ | ------ | ---- | --------- | ---------------------------- | | offset | number | 是 | 0 | 设置渐变点距离起点的位置占总体长度的比例,范围为0到1。 | | color | string | 是 | '#ffffff' | 设置渐变的颜色。 | -- 示例 + +**示例:** ```ts // xxx.ets @@ -48,10 +52,6 @@ addColorStop(offset: number, color: string): void .height('100%') }} ``` - - - - ![zh-cn_image_0000001194032516](figures/zh-cn_image_0000001194032516.png) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md index e2f3f510bef985abf5c868223bf71f477219ea80..12063d494b68b2c694ec35090730d4625a81e620 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagebitmap.md @@ -1,11 +1,12 @@ # ImageBitmap对象 +ImageBitmap对象可以存储canvas渲染的像素数据。 + > **说明:** +> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -ImageBitmap对象可以存储canvas渲染的像素数据。 - ## 属性 @@ -14,6 +15,36 @@ ImageBitmap对象可以存储canvas渲染的像素数据。 | width | number | ImageBitmap的像素宽度。 | | height | number | ImageBitmap的像素高度。 | +**示例:** + + ```ts + // xxx.ets + @Entry + @Component + struct ImageExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("common/images/example.jpg"); + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage( this.img,0,0,500,500,0,0,400,200); + }) + } + .width('100%') + .height('100%') + } + } + ``` + + ![zh-cn_image_0000001194352442](figures/zh-cn_image_0000001194352442.png) + + ## 方法 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md index d1df7c7a5ec2294b75c43ee390e0cfb3ccfad0ff..00ca2d47e15d1efc2e71777f11fef69a70e1eeb7 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-imagedata.md @@ -1,11 +1,12 @@ # ImageData对象 +ImageData对象可以存储canvas渲染的像素数据。 + > **说明:** +> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -ImageData对象可以存储canvas渲染的像素数据。 - ## 属性 @@ -15,3 +16,34 @@ ImageData对象可以存储canvas渲染的像素数据。 | height | number | 矩形区域实际像素高度。 | | data | Uint8ClampedArray | 一维数组,保存了相应的颜色数据,数据值范围为0到255。 | +**示例:** + + ```ts + // xxx.ets +@Entry +@Component +struct Translate { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.context.drawImage(this.img,0,0,130,130); + var imagedata = this.context.getImageData(50,50,130,130); + this.context.putImageData(imagedata,150,150); + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![zh-cn_image_000000127777780](figures/zh-cn_image_000000127777780.png) + diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md index 7db2042a6b73a48a5b80283dc533a83a9d3f20b9..c7e75844c0510121776eff37d1688f11ee83f6aa 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-lottie.md @@ -3,13 +3,10 @@ 提供Lottie动画。 > **说明:** +> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -## 权限列表 - -无 - ## 导入模块 @@ -32,7 +29,8 @@ path: string, container: object, render: string, loop: boolean, autoplay: boolea 加载动画,须提前声明Animator('__lottie_ets')对象,并在Canvas完成布局后调用。可配合Canvas组件生命周期接口使用,比如onAppear()与onPageShow()。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | -------------- | --------------------------- | ---- | ---------------------------------------- | | path | string | 是 | hap包内动画资源文件路径,仅支持json格式。示例:path: "common/lottie/data.json" | @@ -50,12 +48,13 @@ destroy(name: string): void 销毁动画,页面退出时,必须调用。可配合Canvas组件生命周期接口使用,比如onDisappear()与onPageHide()。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | ---------------------------------------- | | name | string | 是 | 被指定的动画名,同loadAnimation接口参数name, 缺省时销毁所有动画。 | -- 示例 +**示例:** ```ts // xxx.ets import lottie from '@ohos/lottieETS' @@ -130,12 +129,14 @@ play(name: string): void 播放指定动画。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | ---------------------------------------- | | name | string | 是 | 被指定的动画名, 同loadAnimation接口参数name,缺省时播放所有动画。 | -- 示例 +**示例:** + ```ts lottie.play(this.animateName) ``` @@ -147,12 +148,14 @@ pause(name: string): void 暂停指定动画,下次调用lottie.play()从当前帧开始。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | ---------------------------------------- | | name | string | 是 | 被指定的动画名,同loadAnimation接口入参name,缺省时暂停所有动画。 | -- 示例 +**示例:** + ```ts lottie.pause(this.animateName) ``` @@ -164,12 +167,14 @@ togglePause(name: string): void 暂停或播放指定动画,等效于lottie.play()与lottie.pause()切换调用。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | ---------------------------------------- | | name | string | 是 | 被指定的动画名,同loadAnimation接口参数name,缺省时停止所有动画。 | -- 示例 +**示例:** + ```ts lottie.togglePause(this.animateName) ``` @@ -181,12 +186,14 @@ stop(name: string): void 停止指定动画,下次调用lottie.play()从第一帧开始。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | ---------------------------------------- | | name | string | 是 | 被指定的动画名,同loadAnimation接口参数name,缺省时停止所有动画。 | -- 示例 +**示例:** + ```ts lottie.stop(this.animateName) ``` @@ -198,13 +205,15 @@ setSpeed(speed: number, name: string): void 设置指定动画播放速度。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ----- | ------ | ---- | ---------------------------------------- | | speed | number | 是 | 值为浮点类型, speed>0正向播放, speed<0反向播放, speed=0暂停播放, speed=1.0/-1.0正常速度播放。 | | name | string | 是 | 被指定的动画,同loadAnimation接口参数name,缺省时停止所有动画。 | -- 示例 +**示例:** + ```ts lottie.setSpeed(5, this.animateName) ``` @@ -216,13 +225,15 @@ setDirection(direction: AnimationDirection, name: string): void 设置指定动画播放顺序。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | --------- | ------------------ | ---- | ---------------------------------------- | | direction | AnimationDirection | 是 | 1为正向,-1为反向; 当设置为反向时,从当前播放进度开始回播直到首帧,loop值为true时可无限倒放;speed<0叠加时也是倒放。
AnimationDirection:1 \| -1 | | name | string | 是 | 被指定的动画名,同loadAnimation接口参数name,缺省时设置所有动画方向。 | -- 示例 +**示例:** + ```ts lottie.setDirection(-1, this.animateName) ``` @@ -262,12 +273,14 @@ play(name?: string): void 播放动画。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | --------------- | | name | string | 否 | 被指定的动画名,缺省默认为空。 | -- 示例 +**示例:** + ```ts this.animateItem.play() ``` @@ -279,12 +292,14 @@ destroy(name?: string): void 销毁动画。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | --------------- | | name | string | 否 | 被指定的动画名,缺省默认为空。 | -- 示例 +**示例:** + ```ts this.animateItem.destroy() ``` @@ -296,12 +311,14 @@ pause(name?: string): void 暂停动画,下次调用play接口从当前帧开始播放。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | --------------- | | name | string | 否 | 被指定的动画名,缺省默认为空。 | -- 示例 +**示例:** + ```ts this.animateItem.pause() ``` @@ -313,12 +330,14 @@ togglePause(name?: string): void 暂停或播放动画,等效于play接口与pause接口之间轮换调用。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | --------------- | | name | string | 否 | 被指定的动画名,缺省默认为空。 | -- 示例 +**示例:** + ```ts this.animateItem.togglePause() ``` @@ -330,12 +349,14 @@ stop(name?: string): void 停止动画,下次调用play接口从第一帧开始播放。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------ | ---- | --------------- | | name | string | 否 | 被指定的动画名,缺省默认为空。 | -- 示例 +**示例:** + ```ts this.animateItem.stop() ``` @@ -347,12 +368,14 @@ setSpeed(speed: number): void 设置动画播放速度。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ----- | ------ | ---- | ---------------------------------------- | | speed | number | 是 | 值为浮点类型, speed>0正向播放, speed<0反向播放, speed=0暂停播放, speed=1.0 \| -1.0正常速度播放。 | -- 示例 +**示例:** + ```ts this.animateItem.setSpeed(5); ``` @@ -364,12 +387,14 @@ setDirection(direction: AnimationDirection): void 设置动画播放顺序。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | --------- | ------------------ | ---- | ---------------------------------------- | | direction | AnimationDirection | 是 | 1为正向,-1为反向; 当设置为反向时,从当前播放进度开始回播直到首帧,loop值为true时可无限倒放;speed<0叠加时也是倒放。
AnimationDirection:1 \| -1。 | -- 示例 +**示例:** + ```ts this.animateItem.setDirection(-1) ``` @@ -381,14 +406,16 @@ goToAndStop(value: number, isFrame?: boolean): void 设置动画停止在指定帧或时间进度。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ------- | ------- | ---- | ---------------------------------------- | | value | number | 是 | 帧号(值大于等于0)或时间进度(ms)。 | | isFrame | boolean | 否 | true: 按指定帧控制,false:按指定时间控制,缺省默认false。 | | name | string | 否 | 被指定的动画名,缺省默认为空。 | -- 示例 +**示例:** + ```ts // 按帧号控制 this.animateItem.goToAndStop(25, true) @@ -403,14 +430,16 @@ goToAndPlay(value: number, isFrame: boolean, name?: string): void 设置动画从指定帧或时间进度开始播放。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ------- | ------- | ---- | ---------------------------------------- | | value | number | 是 | 帧号(值大于等于0)或时间进度(ms) | | isFrame | boolean | 是 | true:按指定帧控制, false:按指定时间控制,缺省默认false。 | | name | string | 否 | 被指定的动画名,缺省默认为空。 | -- 示例 +**示例:** + ```ts // 按帧号控制 this.animateItem.goToAndPlay(25, true) @@ -425,13 +454,15 @@ playSegments(segments: AnimationSegment | AnimationSegment[], forceFlag: boolean 设置动画仅播放指定片段。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | --------- | ---------------------------------------- | ---- | ---------------------------------------- | | segments | AnimationSegment = [number, number] \| AnimationSegment[] | 是 | 片段或片段列表;
如果片段列表全部播放完毕后,下轮循环播放仅播放最后一个片段 | | forceFlag | boolean | 是 | true:即时生效播放,false:延迟到下轮循环播放再生效 | -- 示例 +**示例:** + ```ts // 指定播放片段 this.animateItem.playSegments([10, 20], false) @@ -446,12 +477,14 @@ resetSegments(forceFlag: boolean): void 重置动画播放片段,播放全帧。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | --------- | ------- | ---- | ------------------------------ | | forceFlag | boolean | 是 | true:即时生效播放,false:延迟到下轮循环播放再生效 | -- 示例 +**示例:** + ```ts this.animateItem.resetSegments(true) ``` @@ -463,7 +496,8 @@ resize(): void 刷新动画布局。 -- 示例 +**示例:** + ```ts this.animateItem.resize() ``` @@ -475,12 +509,14 @@ setSubframe(useSubFrame: boolean): void 设置属性currentFrame的精度显示浮点数。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ------------ | ------- | ---- | ---------------------------------------- | | useSubFrames | boolean | 是 | currentFrame属性默认显示浮点数,该接口参数将影响currentFrame属性的精度。
true:属性currentFrame显示浮点。
false:属性currentFrame去浮点数显示整数。 | -- 示例 +**示例:** + ```ts this.animateItem.setSubframe(false) ``` @@ -492,12 +528,14 @@ getDuration(inFrames?: boolean): void 获取动画单次完整播放的时间(与播放速度无关)或帧数, 与Lottie.loadAnimation接口入参initialSegment有关。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | -------- | ------- | ---- | ---------------------------------------- | | inFrames | boolean | 否 | true:获取帧数, false:获取时间(单位ms),缺省默认false。 | -- 示例 +**示例:** + ```ts this.animateItem.getDuration(true) ``` @@ -509,13 +547,15 @@ addEventListener<T = any>(name: AnimationEventName, callback: AnimationEve 添加侦听事件, 事件完成后会触发指定回调函数。返回可删除该侦听事件的函数对象。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | -------- | ------------------------------- | ---- | ---------------------------------------- | | name | AnimationEventName | 是 | 指定动画事件类型,Lottie内置动画事件类型AnimationEventName:
'enterFrame'、'loopComplete'、'complete'、'segmentStart'、'destroy'、'config_ready'、'data_ready'、'DOMLoaded'、'error'、'data_failed'、'loaded_images' | | callback | AnimationEventCallback<T> | 是 | 用户自定义回调函数 | -- 示例 +**示例:** + ```ts private callbackItem: any = function() { console.log("grunt loopComplete") @@ -533,13 +573,15 @@ removeEventListener<T = any>(name: AnimationEventName, callback?: Animatio 删除侦听事件。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | -------- | ------------------------------- | ---- | ---------------------------------------- | | name | AnimationEventName | 是 | 指定动画事件类型,Lottie内置动画事件类型AnimationEventName:
'enterFrame'、'loopComplete'、'complete'、'segmentStart'、'destroy'、'config_ready'、'data_ready'、'DOMLoaded'、'error'、'data_failed'、'loaded_images' | | callback | AnimationEventCallback<T> | 否 | 用户自定义回调函数;缺省为空时,删除此事件的所有回调函数。 | -- 示例 +**示例:** + ```ts this.animateItem.removeEventListener('loopComplete', this.animateName) ``` @@ -551,13 +593,15 @@ triggerEvent<T = any>(name: AnimationEventName, args: T): void 直接触发指定事件的所有已设置的回调函数。 -- 参数 +**参数:** + | 参数 | 类型 | 必填 | 描述 | | ---- | ------------------ | ---- | --------- | | name | AnimationEventName | 是 | 指定动画事件类型 | | args | any | 是 | 用户自定义回调参数 | -- 示例 +**示例:** + ```ts private triggerCallBack: any = function(item) { console.log("trigger loopComplete, name:" + item.name) diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md index 63004c2e78848e356e474a5ee4b38d13f6162c66..b37d56db73e7684aac0cb0c40b206f1d910d3bd6 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-components-canvas-path2d.md @@ -1,11 +1,12 @@ # Path2D对象 +路径对象,支持通过对象的接口进行路径的描述,并通过Canvas的stroke接口进行绘制。 + > **说明:** +> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -路径对象,支持通过对象的接口进行路径的描述,并通过Canvas的stroke接口进行绘制。 - ## addPath @@ -225,7 +226,8 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, .backgroundColor('#ffff00') .onReady(() =>{ this.path2Db.moveTo(10, 10) - this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20);this.context.stroke(this.path2Db) + this.path2Db.bezierCurveTo(20, 100, 200, 100, 200, 20) + this.context.stroke(this.path2Db) }) } .width('100%') @@ -319,7 +321,8 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.arc(100, 75, 50, 0, 6.28);this.context.stroke(this.path2Db) + this.path2Db.arc(100, 75, 50, 0, 6.28) + this.context.stroke(this.path2Db) }) } .width('100%') @@ -407,7 +410,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private path2Db: Path2D = new Path2D() - + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -415,7 +418,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.path2Db.ellipse(200, 200, 50, 100, 0, Math.PI * 1, Math.PI*2) this.context.stroke(this.path2Db) }) } @@ -461,7 +464,8 @@ rect(x: number, y: number, w: number, h: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.path2Db.rect(20, 20, 100, 100);this.context.stroke(this.path2Db) + this.path2Db.rect(20, 20, 100, 100); + this.context.stroke(this.path2Db) }) } .width('100%') diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md b/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md index d129eb383470472e841cc263483bc136ee63c31e..0f6a52a9b060be178339cc7c8002606484bccd23 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-container-grid.md @@ -27,8 +27,8 @@ Grid(scroller?: Scroller) | 名称 | 参数类型 | 描述 | | -------- | -------- | -------- | -| columnsTemplate | string | 设置当前网格布局列的数量,不设置时默认1列。
例如, '1fr 1fr 2fr' 是将父组件分3列,将父组件允许的宽分为4等份,第一列占1份,第二列占1份,第三列占2份。并支持[auto-fill](#auto-fill说明)。
默认值:'1fr' | -| rowsTemplate | string | 设置当前网格布局行的数量,不设置时默认1行。
例如, '1fr 1fr 2fr'是将父组件分三行,将父组件允许的高分为4等份,第一行占1份,第二行占一份,第三行占2份。并支持[auto-fill](#auto-fill说明)。
默认值:'1fr' | +| columnsTemplate | string | 设置当前网格布局列的数量,不设置时默认1列。
例如, '1fr 1fr 2fr' 是将父组件分3列,将父组件允许的宽分为4等份,第一列占1份,第二列占1份,第三列占2份。
默认值:'1fr' | +| rowsTemplate | string | 设置当前网格布局行的数量,不设置时默认1行。
例如, '1fr 1fr 2fr'是将父组件分三行,将父组件允许的高分为4等份,第一行占1份,第二行占一份,第三行占2份。
默认值:'1fr' | | columnsGap | Length | 设置列与列的间距。
默认值:0 | | rowsGap | Length | 设置行与行的间距。
默认值:0 | | scrollBar | [BarState](ts-appendix-enums.md#barstate) | 设置滚动条状态。
默认值:BarState.Off | @@ -65,16 +65,6 @@ Grid(scroller?: Scroller) | onItemDragLeave(event: (event: ItemDragInfo, itemIndex: number) => void) | 拖拽离开网格元素时触发。
- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。
- itemIndex: 拖拽离开的网格元素索引值。 | | onItemDrop(event: (event: ItemDragInfo, itemIndex: number, insertIndex: number, isSuccess: boolean) => void) | 绑定该事件的网格元素可作为拖拽释放目标,当在网格元素内停止拖拽时触发。
- event: 见[ItemDragInfo对象说明](#itemdraginfo对象说明)。
- itemIndex: 拖拽起始位置。
- insertIndex: 拖拽插入位置。
- isSuccess: 是否成功释放。 | -## auto-fill说明 - -Grid的columnsTemplate、rowsTemplate属性的auto-fill仅支持以下格式: - -```css -repeat(auto-fill, track-size) -``` - -其中repeat、auto-fill为关键字。track-size为行高或者列宽,支持的单位包括px、vp、%或有效数字,track-size至少包括一个有效行高或者列宽。 - ## ItemDragInfo对象说明 | 名称 | 类型 | 描述 | @@ -144,51 +134,4 @@ struct GridExample { } ``` -![zh-cn_image_0000001219744183](figures/zh-cn_image_0000001219744183.gif) - -**auto-fill示例** - -```ts -// grid-autofill.ets -@Entry -@Component -struct Index { - @State gridItemWidth: string = "100%" - @State gridItemHeight: string = "100%" - @State gridWidth: string = "100%" - @State gridHeight: string = "100%" - @State itemList: string[] = [] - build() { - Column() { - Grid() { - ForEach(this.itemList, (item) => { - GridItem() { - Text(item.toString()) - .fontSize(16) - .width('100%') - .textAlign(TextAlign.Center) - } - .width(this.gridItemWidth) - .height(this.gridItemHeight) - .backgroundColor(0xF9CF93) - }, item => item) - } - .columnsGap(1) - .rowsGap(1) - .border({ width: 4, color: 0xffdb7093, style: BorderStyle.Dashed, radius: 5 }) - .width(this.gridWidth) - .height(this.gridHeight) - .columnsTemplate("15% repeat(auto-fill, 10% 50px 20%) 50px") - .rowsTemplate("150px repeat(auto-fill, 20% 25%)") - }.margin(5) - } - - aboutToAppear() { - for(var i = 1; i < 50; i++) { - this.itemList.push(i.toString()) - } - } -} -``` - -![grid-autofill](figures/grid-autofill.png) \ No newline at end of file +![zh-cn_image_0000001219744183](figures/zh-cn_image_0000001219744183.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md index 709e897f90d1940b5388b18c148592a0e1f74361..c6634faf732e678e7609827cb81606410f185645 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-drawing-components-shape.md @@ -21,11 +21,10 @@ Shape(value?: PixelMap) -**参数:** - -| 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | -| -------- | -------- | -------- | -------- | -------- | -| value | PixelMap | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 | +- 参数 + | 参数名 | 参数类型 | 必填 | 默认值 | 参数描述 | + | -------- | -------- | -------- | -------- | -------- | + | value | [PixelMap](../apis/js-apis-image.md#pixelmap7) | 否 | - | 绘制目标,可将图形绘制在指定的PixelMap对象中,若未设置,则在当前绘制目标中进行绘制。 | ## 属性 diff --git a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md index 9a0caa9f125ab28009166ecebd0cf9d7dccc8eea..b84eef2a7be0bd0d10328d952c856d1b9dc35774 100644 --- a/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md +++ b/zh-cn/application-dev/reference/arkui-ts/ts-offscreencanvasrenderingcontext2d.md @@ -1,11 +1,12 @@ # OffscreenCanvasRenderingContext2D对象 +使用OffscreenCanvasRenderingContext2D在Canvas上进行离屏绘制,绘制对象可以是矩形、文本、图片等。离屏绘制是指将需要绘制的内容先绘制在缓存区,然后将其转换成图片,一次性绘制到canvas上,加快了绘制速度。 + > **说明:** +> > 从 API Version 8 开始支持。后续版本如有新增内容,则采用上角标单独标记该内容的起始版本。 -使用OffscreenCanvasRenderingContext2D在Canvas上进行离屏绘制,绘制对象可以是矩形、文本、图片等。离屏绘制是指将需要绘制的内容先绘制在缓存区,然后将其转换成图片,一次性绘制到canvas上,加快了绘制速度。 - ## 接口 @@ -41,7 +42,6 @@ OffscreenCanvasRenderingContext2D(width: number, height: number, setting: Render | [shadowOffsetX](#shadowoffsetx) | number | 设置绘制阴影时和原有对象的水平偏移值。 | | [shadowOffsetY](#shadowoffsety) | number | 设置绘制阴影时和原有对象的垂直偏移值。 | | [imageSmoothingEnabled](#imagesmoothingenabled) | boolean | 用于设置绘制图片时是否进行图像平滑度调整,true为启用,false为不启用。
- 默认值:true。 | -| imageSmoothingQuality | string | 用于设置图像平滑度,支持如下三种类型:'low', 'medium', 'high'。
- 默认值:'low'。 | > ![icon-note.gif](public_sys-resources/icon-note.gif) **说明:** > fillStyle、shadowColor与 strokeStyle 中string类型格式为 'rgb(255, 255, 255)','rgba(255, 255, 255, 1.0)','\#FFFFFF'。 @@ -572,8 +572,7 @@ struct ShadowColor { this.offContext.shadowColor = 'rgb(0,0,255)' this.offContext.fillStyle = 'rgb(255,0,0)' this.offContext.fillRect(30, 30, 100, 100) - var image = this.offContext.transferToImageBitmap -() + var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) } @@ -739,7 +738,7 @@ fillRect(x: number, y: number, w: number, h: number): void } ``` - ![zh-cn_image_0000001238832407](figures/zh-cn_image_0000001238832407.png) + ![zh-cn_image_0000001194192436](figures/zh-cn_image_0000001194192436.png) ### strokeRect @@ -767,6 +766,7 @@ strokeRect(x: number, y: number, w: number, h: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -785,7 +785,7 @@ strokeRect(x: number, y: number, w: number, h: number): void } ``` - ![zh-cn_image_0000001238712441](figures/zh-cn_image_0000001238712441.png) + ![zh-cn_image_0000001194352436](figures/zh-cn_image_0000001194352436.png) ### clearRect @@ -813,6 +813,7 @@ clearRect(x: number, y: number, w: number, h: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -821,8 +822,8 @@ clearRect(x: number, y: number, w: number, h: number): void .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.fillStyle = 'rgb(0,0,255)' - this.offContext.fillRect(0,0,500,500) - this.offContext.clearRect(20,20,150,100) + this.offContext.fillRect(20,20,200,200) + this.offContext.clearRect(30,30,150,100) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -833,7 +834,7 @@ clearRect(x: number, y: number, w: number, h: number): void } ``` - ![zh-cn_image_0000001194192458](figures/zh-cn_image_0000001194192458.png) + ![zh-cn_image_0000001238952377](figures/zh-cn_image_0000001238952377.png) ### fillText @@ -861,6 +862,7 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -880,7 +882,7 @@ fillText(text: string, x: number, y: number, maxWidth?: number): void } ``` - ![zh-cn_image_0000001194352454](figures/zh-cn_image_0000001194352454.png) + ![zh-cn_image_0000001194032458](figures/zh-cn_image_0000001194032458.png) ### strokeText @@ -908,6 +910,7 @@ strokeText(text: string, x: number, y: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -976,6 +979,7 @@ measureText(text: string): TextMetrics private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1012,7 +1016,7 @@ stroke(path?: Path2D): void | path | [Path2D](ts-components-canvas-path2d.md) | 否 | null | 需要绘制的Path2D。 | **示例:** - + ```ts // xxx.ets @Entry @@ -1021,6 +1025,7 @@ stroke(path?: Path2D): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1030,6 +1035,8 @@ stroke(path?: Path2D): void .onReady(() =>{ this.offContext.moveTo(25, 25) this.offContext.lineTo(25, 105) + this.offContext.lineTo(75, 105) + this.offContext.lineTo(75, 25) this.offContext.strokeStyle = 'rgb(0,0,255)' this.offContext.stroke() var image = this.offContext.transferToImageBitmap() @@ -1042,7 +1049,7 @@ stroke(path?: Path2D): void } ``` - ![zh-cn_image_0000001239032427](figures/zh-cn_image_0000001239032427.png) + ![zh-cn_image_0000001238832389](figures/zh-cn_image_0000001238832389.png) ### beginPath @@ -1061,6 +1068,7 @@ beginPath(): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1110,6 +1118,7 @@ moveTo(x: number, y: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1157,6 +1166,7 @@ lineTo(x: number, y: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1197,6 +1207,7 @@ closePath(): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1253,6 +1264,7 @@ createPattern(image: ImageBitmap, repetition: string | null): CanvasPattern | nu private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1303,6 +1315,7 @@ bezierCurveTo(cp1x: number, cp1y: number, cp2x: number, cp2y: number, x: number, private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1352,6 +1365,7 @@ quadraticCurveTo(cpx: number, cpy: number, x: number, y: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1403,6 +1417,7 @@ arc(x: number, y: number, radius: number, startAngle: number, endAngle: number, private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1452,6 +1467,7 @@ arcTo(x1: number, y1: number, x2: number, y2: number, radius: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1512,7 +1528,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number .backgroundColor('#ffff00') .onReady(() =>{ this.offContext.beginPath() - this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI) + this.offContext.ellipse(200, 200, 50, 100, Math.PI * 0.25, Math.PI * 0.5, Math.PI * 2) this.offContext.stroke() var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) @@ -1524,7 +1540,7 @@ ellipse(x: number, y: number, radiusX: number, radiusY: number, rotation: number } ``` - ![zh-cn_image_0000001238832411](figures/zh-cn_image_0000001238832411.png) + ![zh-cn_image_0000001194192440](figures/zh-cn_image_0000001194192440.png) ### rect @@ -1552,6 +1568,7 @@ rect(x: number, y: number, w: number, h: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1576,11 +1593,15 @@ rect(x: number, y: number, w: number, h: number): void ### fill -fill(): void +fill(fillRule?: CanvasFillRule): void 对封闭路径进行填充。 - **示例:** +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要填充对象的规则。
可选参数为:"nonzero", "evenodd"。 | ```ts // xxx.ets @@ -1590,6 +1611,7 @@ fill(): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1612,12 +1634,73 @@ fill(): void ![zh-cn_image_0000001194192462](figures/zh-cn_image_0000001194192462.png) +fill(path: Path2D, fillRule?: CanvasFillRule): void + +对封闭路径进行填充。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | 是 | | Path2D填充路径。 | +| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要填充对象的规则。
可选参数为:"nonzero", "evenodd"。 | + + +**示例:** + +```ts +// xxx.ets +@Entry +@Component +struct Fill { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.moveTo(30, 90); + region.lineTo(110, 20); + region.lineTo(240, 130); + region.lineTo(60, 130); + region.lineTo(190, 20); + region.lineTo(270, 90); + region.closePath(); + // Fill path + this.offContext.fillStyle = 'green'; + this.offContext.fill(region, "evenodd"); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} +``` + + ![zh-cn_image_000000127777775](figures/zh-cn_image_000000127777775.png) + + + ### clip -clip(): void +clip(fillRule?: CanvasFillRule): void 设置当前路径为剪切路径。 +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要剪切对象的规则。
可选参数为:"nonzero", "evenodd"。 | + **示例:** ```ts @@ -1628,6 +1711,7 @@ clip(): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1635,11 +1719,11 @@ clip(): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.rect(0, 0, 200, 200) + this.offContext.rect(0, 0, 100, 200) this.offContext.stroke() this.offContext.clip() this.offContext.fillStyle = "rgb(255,0,0)" - this.offContext.fillRect(0, 0, 150, 150) + this.offContext.fillRect(0, 0, 200, 200) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1650,7 +1734,90 @@ clip(): void } ``` - ![zh-cn_image_0000001194352458](figures/zh-cn_image_0000001194352458.png) + ![zh-cn_image_0000001194032462](figures/zh-cn_image_0000001194032462.png) + + +clip(path:Path2D, fillRule?: CanvasFillRule): void + +设置封闭路径为剪切路径。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 描述 | +| -------- | -------------- | ---- | --------- | ---------------------------------------- | +| path | Path2D | 是 | | Path2D剪切路径。 | +| fillRule | CanvasFillRule | 否 | "nonzero" | 指定要剪切对象的规则。
可选参数为:"nonzero", "evenodd"。 | + + **示例:** + + ```ts + // xxx.ets +@Entry +@Component +struct Clip { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + let region = new Path2D(); + region.rect(80,10,20,130); + region.rect(40,50,100,50); + this.offContext.clip(region,"evenodd") + this.offContext.fillStyle = "rgb(255,0,0)" + this.offContext.fillRect(0, 0, 600, 600) + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![zh-cn_image_000000127777779](figures/zh-cn_image_000000127777779.png) + + + +### filter + +filter(filter: string): void + +为Canvas图形设置各类滤镜效果。该接口为空接口。 + +**参数:** + +| 参数 | 类型 | 必填 | 默认值 | 说明 | +| ------ | ------ | ---- | ---- | ------------ | +| filter | string | 是 | - | 接受各类滤镜效果的函数。 | + + +### getTransform + +getTransform(): Matrix2D + +获取当前被应用到上下文的转换矩阵。该接口为空接口。 + + +### resetTransform + +resetTransform(): void + +使用单位矩阵重新设置当前变形。该接口为空接口。 + + +### direction + +direction(direction: CanvasDirection): void + +绘制文本时,描述当前文本方向的属性。该接口为空接口。 ### rotate @@ -1675,6 +1842,7 @@ rotate(angle: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1720,6 +1888,7 @@ scale(x: number, y: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1727,9 +1896,10 @@ scale(x: number, y: number): void .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.lineWidth = 3 + this.offContext.strokeRect(30, 30, 50, 50) this.offContext.scale(2, 2) // Scale to 200% - this.offContext.strokeRect(10, 10, 25, 25) + this.offContext.strokeRect(30, 30, 50, 50) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -1740,7 +1910,7 @@ scale(x: number, y: number): void } ``` - ![zh-cn_image_0000001194032484](figures/zh-cn_image_0000001194032484.png) + ![zh-cn_image_0000001193872498](figures/zh-cn_image_0000001193872498.png) ### transform @@ -1777,6 +1947,7 @@ transform方法对应一个变换矩阵,想对一个图形进行变化的时 private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1832,6 +2003,7 @@ setTransform方法使用的参数和transform()方法相同,但setTransform() private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1880,6 +2052,7 @@ translate(x: number, y: number): void private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -1934,7 +2107,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: // xxx.ets @Entry @Component - struct Index { + struct DrawImage { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private img:ImageBitmap = new ImageBitmap("common/images/icon.jpg") @@ -1964,7 +2137,7 @@ drawImage(image: ImageBitmap | PixelMap, sx: number, sy: number, sw: number, sh: createImageData(sw: number, sh: number): ImageData -根据宽高创建ImageData对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)。 +根据宽高创建ImageData对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 **参数:** @@ -1974,23 +2147,21 @@ createImageData(sw: number, sh: number): ImageData | sh | number | 是 | 0 | ImageData的高度。 | -### createImageData - createImageData(imageData: ImageData): ImageData -根据已创建的ImageData对象创建新的ImageData对象,请参考[ImageData](ts-components-canvas-imagebitmap.md)。 +根据已创建的ImageData对象创建新的ImageData对象,请参考[ImageData](ts-components-canvas-imagedata.md)。 **参数:** | 参数 | 类型 | 必填 | 默认 | 描述 | | --------- | ---------------------------------------- | ---- | ---- | ---------------- | -| imagedata | [ImageData](ts-components-canvas-imagebitmap.md) | 是 | null | 被复制的ImageData对象。 | +| imagedata | [ImageData](ts-components-canvas-imagedata.md) | 是 | null | 被复制的ImageData对象。 | **返回值:** | 类型 | 说明 | | ---------------------------------------- | ------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象 | +| [ImageData](ts-components-canvas-imagedata.md) | 新的ImageData对象 | ### getPixelMap @@ -2018,7 +2189,7 @@ getPixelMap(sx: number, sy: number, sw: number, sh: number): PixelMap getImageData(sx: number, sy: number, sw: number, sh: number): ImageData -以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagebitmap.md)对象。 +以当前canvas指定区域内的像素创建[ImageData](ts-components-canvas-imagedata.md)对象。 **参数:** @@ -2033,7 +2204,42 @@ getImageData(sx: number, sy: number, sw: number, sh: number): ImageData | 类型 | 说明 | | ---------------------------------------- | ------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | 新的ImageData对象 | +| [ImageData](ts-components-canvas-imagedata.md) | 新的ImageData对象 | + + +**示例:** + + ```ts + // xxx.ets +@Entry +@Component +struct GetImageData { + private settings: RenderingContextSettings = new RenderingContextSettings(true); + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings); + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + private img:ImageBitmap = new ImageBitmap("/common/images/1234.png") + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.drawImage(this.img,0,0,130,130); + var imagedata = this.offContext.getImageData(50,50,130,130); + this.offContext.putImageData(imagedata,150,150); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) + } + .width('100%') + .height('100%') + } +} + ``` + + ![zh-cn_image_000000127777780](figures/zh-cn_image_000000127777780.png) ### putImageData @@ -2042,7 +2248,7 @@ putImageData(imageData: Object, dx: number, dy: number): void putImageData(imageData: Object, dx: number, dy: number, dirtyX: number, dirtyY: number, dirtyWidth?: number, dirtyHeight: number): void -使用[ImageData](ts-components-canvas-imagebitmap.md)数据填充新的矩形区域。 +使用[ImageData](ts-components-canvas-imagedata.md)数据填充新的矩形区域。 **参数:** @@ -2153,21 +2359,29 @@ getLineDash(): number[] ```ts // xxx.ets - @Entry - @Component - struct GetLineDash { +@Entry +@Component +struct OffscreenCanvasGetLineDash { + @State message: string = 'Hello World' private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + .onClick(()=>{ + console.error('before getlinedash clicked') + let res = this.offContext.getLineDash() + console.error(JSON.stringify(res)) + }) Canvas(this.context) .width('100%') .height('100%') .backgroundColor('#ffff00') - .onReady(() =>{ - var grad = this.context.createLinearGradient(50,0, 300,100) + .onReady(() => { this.offContext.arc(100, 75, 50, 0, 6.28) this.offContext.setLineDash([10,20]) this.offContext.stroke(); @@ -2177,53 +2391,14 @@ getLineDash(): number[] }) } .width('100%') - .height('100%') } + .height('100%') } +} ``` +![zh-cn_image_000000127777778](figures/zh-cn_image_000000127777778.png) -### transferFromImageBitmap - -transferFromImageBitmap(bitmap: ImageBitmap): void - -显示给定的ImageBitmap对象。 - -**参数:** - -| 参数 | 类型 | 描述 | -| ------ | ---------------------------------------- | ------------------ | -| bitmap | [ImageData](ts-components-canvas-imagebitmap.md) | 待显示的ImageBitmap对象。 | - -**示例:** - - ```ts - // xxx.ets - @Entry - @Component - struct GetLineDash { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.fillRect(0, 0, 200, 200) - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') - } - } - ``` - ![zh-cn_image_000000127777773](figures/zh-cn_image_000000127777773.png) ### toDataURL @@ -2247,7 +2422,7 @@ toDataURL(type?: string, quality?: number): string **示例:** ```ts - // xxx.ets +// xxx.ets @Entry @Component struct ToDataURL { @@ -2272,6 +2447,19 @@ struct ToDataURL { ``` +### imageSmoothingQuality + +imageSmoothingQuality(quality: imageSmoothingQuality) + +用于设置图像平滑度。该接口为空接口。 + + **参数:** + +| 参数 | 类型 | 描述 | +| ------- | --------------------- | ---------------------------------------- | +| quality | imageSmoothingQuality | 支持如下三种类型:'low', 'medium', 'high'。 | + + ### transferToImageBitmap transferToImageBitmap(): ImageBitmap @@ -2282,7 +2470,7 @@ transferToImageBitmap(): ImageBitmap | 类型 | 说明 | | ---------------------------------------- | --------------- | -| [ImageData](ts-components-canvas-imagebitmap.md) | 存储离屏画布上渲染的像素数据。 | +| [ImageBitmap](ts-components-canvas-imagebitmap.md) | 存储离屏画布上渲染的像素数据。 | **示例:** @@ -2291,10 +2479,11 @@ transferToImageBitmap(): ImageBitmap // xxx.ets @Entry @Component - struct CanvasExample { + struct PutImageData { private settings: RenderingContextSettings = new RenderingContextSettings(true) private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + build() { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Canvas(this.context) @@ -2302,7 +2491,14 @@ transferToImageBitmap(): ImageBitmap .height('100%') .backgroundColor('#ffff00') .onReady(() =>{ - this.offContext.restore() + var imageData = this.offContext.createImageData(100, 100) + for (var i = 0; i < imageData.data.length; i += 4) { + imageData.data[i + 0] = 255 + imageData.data[i + 1] = 0 + imageData.data[i + 2] = 255 + imageData.data[i + 3] = 255 + } + this.offContext.putImageData(imageData, 10, 10) var image = this.offContext.transferToImageBitmap() this.context.transferFromImageBitmap(image) }) @@ -2312,6 +2508,7 @@ transferToImageBitmap(): ImageBitmap } } ``` +![zh-cn_image_0000001238952387](figures/zh-cn_image_0000001238952387.png) ### restore @@ -2323,29 +2520,35 @@ restore(): void ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.restore() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) - }) - } - .width('100%') - .height('100%') +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) + }) } + .width('100%') + .height('100%') } +} ``` +![zh-cn_image_000000127777781](figures/zh-cn_image_000000127777781.png) ### save @@ -2358,29 +2561,35 @@ save(): void ```ts // xxx.ets - @Entry - @Component - struct CanvasExample { - private settings: RenderingContextSettings = new RenderingContextSettings(true) - private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) - private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) - build() { - Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { - Canvas(this.context) - .width('100%') - .height('100%') - .backgroundColor('#ffff00') - .onReady(() =>{ - this.offContext.save() - var image = this.offContext.transferToImageBitmap() - this.context.transferFromImageBitmap(image) +@Entry +@Component +struct CanvasExample { + private settings: RenderingContextSettings = new RenderingContextSettings(true) + private context: CanvasRenderingContext2D = new CanvasRenderingContext2D(this.settings) + private offContext: OffscreenCanvasRenderingContext2D = new OffscreenCanvasRenderingContext2D(600, 600, this.settings) + + build() { + Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { + Canvas(this.context) + .width('100%') + .height('100%') + .backgroundColor('#ffff00') + .onReady(() =>{ + this.offContext.save(); // save the default state + this.offContext.fillStyle = "green"; + this.offContext.fillRect(20, 20, 100, 100); + this.offContext.restore(); // restore to the default state + this.offContext.fillRect(150, 75, 100, 100); + var image = this.offContext.transferToImageBitmap() + this.context.transferFromImageBitmap(image) }) - } - .width('100%') - .height('100%') } + .width('100%') + .height('100%') } +} ``` +![zh-cn_image_000000127777781](figures/zh-cn_image_000000127777781.png) ### createLinearGradient diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-DistributedSchedule.md b/zh-cn/application-dev/reference/errorcodes/errcode-DistributedSchedule.md index 1d048f15414bf7751dc8ff7fe4e4610c1438a9aa..01e19e15adf51882c02d5e484291087bac7c8cbf 100644 --- a/zh-cn/application-dev/reference/errorcodes/errcode-DistributedSchedule.md +++ b/zh-cn/application-dev/reference/errorcodes/errcode-DistributedSchedule.md @@ -5,6 +5,10 @@ ### 错误信息 Permission denied. +### 错误描述 + +当调用流转管理和迁移等接口时,若缺少ohos.permission.MANAGER_MISSIONS或ohos.permission.DISTRIBUTED_DATASYNC,会报此错误码。 + ### 可能原因 该错误码表示权限校验失败,可能原因是未配置对应权限。 @@ -16,6 +20,10 @@ Permission denied. ### 错误信息 The parameter check failed. +### 错误描述 + +当调用接口提供的入参出现类型、个数、数组大小以及合法性等错误时,会报此错误码。 + ### 可能原因 该错误码表示入参检查错误,可能原因是callback入参检查错误。 @@ -27,6 +35,10 @@ The parameter check failed. ### 错误信息 The system ability work abnormally. +### 错误描述 + +当系统服务工作异常时,会报此错误码。 + ### 可能原因 该错误码表示系统服务工作异常,可能原因如下。 1. DMS服务没有正常启动。 @@ -38,6 +50,10 @@ The system ability work abnormally. ## 16600002 指定的token或callback未注册 +### 错误描述 + +当调用continuationManager相关的接口时传入的token或callback未提前注册,会报此错误码。 + ### 错误信息 The specified token or callback has not registered. @@ -49,6 +65,10 @@ The specified token or callback has not registered. ## 16600003 应用注册token已达到最大次数限制 +### 错误描述 + +当调用continuationManager.registerContinuation接口时次数过多超出限制,会报此错误码。 + ### 错误信息 The number of token registration times has reached the upper limit. @@ -60,6 +80,10 @@ The number of token registration times has reached the upper limit. ## 16600004 指定的callback已注册 +### 错误描述 + +当使用相同的callback调用continuationManager的on接口时,会报此错误码。 + ### 错误信息 The specified callback has been registered. @@ -71,6 +95,10 @@ The specified callback has been registered. ## 16300501 系统服务工作异常 +### 错误描述 + +当系统服务工作异常时,会报此错误码。 + ### 错误信息 The system ability work abnormally. @@ -85,6 +113,10 @@ The system ability work abnormally. ## 16300502 获取指定的missionId的missionInfo失败 +### 错误描述 + +当调用distributedMissionManager.continueMission接口获取指定missionId的missionInfo失败时,会报此错误码。 + ### 错误信息 Failed to get the missionInfo of the specified missionId. @@ -98,6 +130,10 @@ Failed to get the missionInfo of the specified missionId. ## 16300503 远端未安装应用且不支持免安装 +### 错误描述 + +当调用distributedMissionManager.continueMission接口使用迁移功能时,若远端未安装应用且不支持免安装,会报此错误码。 + ### 错误信息 The application is not installed on the remote end and installation-free is not supported. @@ -110,6 +146,10 @@ The application is not installed on the remote end and installation-free is not ## 16300504 远端未安装应用但支持免安装,需使用免安装标识重试 +### 错误描述 + +当调用distributedMissionManager.continueMission接口使用迁移功能时,若远端未安装应用但支持免安装,会报此错误码。 + ### 错误信息 The application is not installed on the remote end but installation-free is supported, try again with freeInstall flag. @@ -121,6 +161,10 @@ The application is not installed on the remote end but installation-free is supp ## 16300505 操作设备必须是迁移的应用所在的设备或需迁移到的目标设备 +### 错误描述 + +当调用distributedMissionManager.continueMission接口使用迁移功能时,若操作设备不是迁移的应用所在的设备或需迁移到的目标设备,会报此错误码。 + ### 错误信息 The operation device must be the device where the application to be continued is located or the target device to be continued. @@ -132,6 +176,10 @@ The operation device must be the device where the application to be continued is ## 16300506 本地迁移任务已在进行中 +### 错误描述 + +当调用distributedMissionManager.continueMission接口使用迁移功能时,若本地迁移任务已在进行中,会报此错误码。 + ### 错误信息 The local continuation task is already in progress. @@ -143,6 +191,10 @@ The local continuation task is already in progress. ## 3 序列化对象失败 +### 错误描述 + +当调用continuationManager相关接口时,若系统参数DMS_PROXY_INTERFACE_TOKEN序列化写失败,会报此错误码。 + ### 错误信息 Failed to flatten the object. @@ -157,6 +209,10 @@ Failed to flatten the object. ### 错误信息 The object is null. +### 错误描述 + +当调用流转和迁移相关接口时,若出现dms以及其他对象为空或序列化读失败,会报此错误码。 + ### 可能原因 该错误码表示接口依赖的服务对象或参数对象为空,可能原因如下。 1. 入参序列化读失败。 @@ -170,6 +226,10 @@ The object is null. ## 29360207 注册超出最大次数 +### 错误描述 + +当调用continuationManager.register接口时次数过多超出限制,会报此错误码。 + ### 错误信息 The maximum number of registrations exceeded. @@ -181,6 +241,10 @@ The maximum number of registrations exceeded. ## 29360208 token未注册 +### 错误描述 + +当调用continuationManager相关接口时使用未注册的token,会报此错误码。 + ### 错误信息 The token has not registered. @@ -192,6 +256,10 @@ The token has not registered. ## 29360209 callback已注册 +### 错误描述 + +当使用相同的callback重复调用continuationManager.on接口时,会报此错误码。 + ### 错误信息 Callback has been registered. @@ -203,6 +271,10 @@ Callback has been registered. ## 29360210 callback未注册 +### 错误描述 + +当调用continuationManager的off、updateConnectStatus和startDeviceManager等接口时,若未提前调用on接口注册callback,会报此错误码。 + ### 错误信息 Callback has not been registered. @@ -214,6 +286,10 @@ Callback has not been registered. ## 29360211 连接ability失败 +### 错误描述 + +当调用continuationManager的startDeviceManager接口时,若连接相应Ability失败时,会报此错误码。 + ### 错误信息 Failed to connect ability. @@ -225,6 +301,10 @@ Failed to connect ability. ## 29360214 callback类型错误 +### 错误描述 + +当调用continuationManager的on和off接口时,若参数callback类型错误时,会报此错误码。 + ### 错误信息 The type of callback is not supported. @@ -236,8 +316,12 @@ The type of callback is not supported. ## 29360215 无效的连接状态 +### 错误描述 + +当调用continuationManager的updateConnectStatus接口时,若参数status为无效值时,会报此错误码。 + ### 错误信息 -Invalid continuation mode. +Invalid connect state. ### 可能原因 该错误码表示无效的连接状态,可能原因是入参DeviceConnectState为非指定值。 @@ -247,6 +331,10 @@ Invalid continuation mode. ## 29360216 无效的流转模式 +### 错误描述 + +当调用continuationManager的register和startDeviceManager接口时,若参数ContinuationExtraParams.continuationMode为无效值时,会报此错误码。 + ### 错误信息 Invalid continuation mode. diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-bundle.md b/zh-cn/application-dev/reference/errorcodes/errcode-bundle.md new file mode 100644 index 0000000000000000000000000000000000000000..509944b152d70c4c7062af64456e1bd82a7d9f18 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errcode-bundle.md @@ -0,0 +1,367 @@ +# 包管理子系统通用错误码 + +## 17700001 指定的bundleName不存在 + +**错误信息**
+The specified bundle name is not found. + +**错误描述**
+调用接口时,传入的bundleName不存在。 + +**可能原因**
+1. 输入的bundleName有误。 +2. 系统中对应的应用没有安装。 + +**处理步骤**
+1. 检查bundleName拼写是否正确。 +2. 确认对应的应用是否安装。 + +## 17700002 指定的moduleName不存在 + +**错误信息**
+The specified module name is not found. + +**错误描述**
+调用接口时,传入的moduleName不存在。 + +**可能原因**
+1. 输入的moduleName有误。 +2. 系统中对应的应用没有安装该模块。 + +**处理步骤**
+1. 检查bundleName拼写是否正确。 +2. 确认对应的应用是否安装该模块。 + +## 17700003 指定的abilityName不存在 + +**错误信息**
+The specified ability name is not found. + +**错误描述**
+调用接口时,传入的abilityName不存在。 + +**可能原因**
+1. 输入的abilityName有误。 +2. 系统中对应的应用没有安装。 + +**处理步骤**
+1. 检查abilityName拼写是否正确。 +2. 确认对应的应用是否安装该模块。 + +## 17700004 指定的用户不存在 + +**错误信息**
+The specified user id is not found. + +**错误描述**
+调用接口时,传入的用户不存在。 + +**可能原因**
+输入的用户名有误,系统中没有该用户。 + +**处理步骤**
+1. 检查用户名拼写是否正确。 +2. 确认系统中存在该用户。 + +## 17700005 指定的appId不存在 + +**错误信息**
+The specified appId is not found. + +**错误描述**
+调用接口时,传入的appId为空字符串。 + +**可能原因**
+传入的appId为空字符串。 + +**处理步骤**
+检查appId是否为空字符串。 + +## 17700006 查询的权限不存在 + +**错误信息**
+The specified permission is not found. + +**错误描述**
+调用接口时,传入的权限不存在。 + +**可能原因**
+1. 传入的permission名称拼写有误。 +2. 系统中不存在对应的权限。 + +**处理步骤**
+1. 检查permission拼写是否正确。 +2. 确认系统中是否有该权限。 + +## 17700007 输入的设备Id有误 + +**错误信息**
+The specified deviceId is not found. + +**错误描述**
+调用接口时,传入的设备id有误。 + +**可能原因**
+1. 传入的deviceId拼写有误。 +2. deviceId不存在。 + +**处理步骤**
+1. 检查deviceId拼写是否正确。 +2. 确认deviceId是否存在。 + +## 17700010 文件解析失败导致应用安装失败 + +**错误信息**
+Failed to install the hap since the hap fails to be parsed. + +**错误描述**
+文件解析失败导致应用安装失败。 + +**可能原因**
+1. hap包的格式不是zip格式。 +2. hap包的配置文件不满足json格式。 +3. hap包的配置文件缺少必要的字段。 + +**处理步骤**
+1. 确认hap的格式是zip。 +2. 确认hap的配置文件满足[配置文件json格式](../../quick-start/stage-structure.md)。 +3. 检查DevEco Studio编译hap时是否有错误提示,缺省字段时会有相应的报错。 + +## 17700011 签名校验失败失败导致应用安装失败 + +**错误信息**
+Failed to install the hap since the hap signature fails to be verified. + +**错误描述**
+签名校验失败失败导致应用安装失败。 + +**可能原因**
+1. hap包没有签名。 +2. hap签名信息来源不可靠。 +3. 升级的hap包与已安装的hap包签名信息不一致。 +4. 多个hap的签名信息不一致。 + +**处理步骤**
+1. 确认hap是否签名成功。 +2. 确认多个hap签名时使用的证书相同。 +3. 确认升级的hap签名证书与已安装的hap相同。 + +## 17700012 安装包路径无效导致应用安装失败 + +**错误信息**
+Failed to install the hap since the path of the hap is invalid. + +**错误描述**
+安装包路径无效导致应用安装失败。 + +**可能原因**
+1. 输入错误,hap包的文件路径不存在。 +2. hap包的路径无法访问。 + +**处理步骤**
+1. 确认hap是否存在。 +2. 查看hap的可执行权限,是否可读。 + +## 17700013 应用包过大导致应用安装失败 + +**错误信息**
+Failed to install the hap since the hap is too large. + +**错误描述**
+应用包过大导致应用安装失败。 + +**可能原因**
+hap包过大,一个hap不能超过4GB。 + +**处理步骤**
+确认hap包的大小。 + +## 17700014 应用包后缀有误导致应用安装失败 + +**错误信息**
+Failed to install the hap since the extension name of the hap is not .hap. + +**错误描述**
+应用包后缀有误导致应用安装失败。 + +**可能原因**
+hap包的文件后缀名不为.hap。 + +**处理步骤**
+确认hap包的后缀是否为.hap。 + +## 17700015 多个hap包配置信息不同导致应用安装失败 + +**错误信息**
+Failed to install haps since the configuration information of multi haps is inconsistent. + +**错误描述**
+多个hap包配置信息不同导致应用安装失败。 + +**可能原因**
+多个hap包中配置文件app下面的字段不一致。 + +**处理步骤**
+确认多个hap包中配置文件app下面的字段是否一致。 + +## 17700016 系统磁盘空间不足导致应用安装失败 + +**错误信息**
+Failed to install the hap since the system disk space is insufficient. + +**错误描述**
+系统磁盘空间不足导致应用安装失败。 + +**可能原因**
+系统空间不足。 + +**处理步骤**
+确认系统是否有足够的空间。 + +## 17700017 新安装的应用版本号低于已安装的版本号导致应用安装失败 + +**错误信息**
+Failed to install the hap since the version of the newly installed hap is too early. + +**错误描述**
+新安装的应用版本号低于已安装的版本号导致应用安装失败。 + +**可能原因**
+新安装的应用版本号低于已安装的版本号。 + +**处理步骤**
+确认新安装的应用版本号是否比已安装的同应用版本号高。 + +## 17700020 预置应用无法卸载 + +**错误信息**
+The preinstalled app cannot be uninstalled. + +**错误描述**
+预置应用无法卸载。 + +**可能原因**
+1. 传入的bundleName拼写有误。 +2. 对应的预置应用无法卸载。 + +**处理步骤**
+1. 确认bundleName是否拼写正确。 +1. 确认对应的预置应用是否可卸载。 + +## 17700021 指定的uid无效 + +**错误信息**
+The specified uid is invalid. + +**错误描述**
+指定的uid无效。 + +**可能原因**
+1. 传入的uid拼写有误。 +2. 传入的uid在系统中不存在。 + +**处理步骤**
+1. 检查uid的拼写。 +2. 检查系统中是否存在该uid。 + +## 17700022 输入的待解析源文件无效 + +**错误信息**
+The input source file is invalid. + +**错误描述**
+输入的待解析源文件无效。 + +**可能原因**
+1. 待解析的源文件不存在。 +2. 待解析的源文件不符合zip格式。 + +**处理步骤**
+1. 确认待解析的源文件是否存在。 +2. 确认待解析的源文件符合zip格式。 + +## 17700023 指定的默认应用不存在 + +**错误信息**
+The specified default app does not exist. + +**错误描述**
+指定的默认应用不存在。 + +**可能原因**
+设备没有设置对应的默认应用。 + +**处理步骤**
+确认设备是否设置了对应的默认应用。 + +## 17700024 没有相应的配置文件 + +**错误信息**
+Failed to get profile since no profile in the hap. + +**错误描述**
+没有相应的配置文件。 + +**可能原因**
+1. 输入的metadata name在配置文件中不存在。 +2. 配置文件的内容不是json格式。 + +**处理步骤**
+1. 确认要查询的ability或者extensionAbility中的metadata name是否存在。 +2. 确认指定查询的profile文件的内容是否为json格式。 + +## 17700025 输入的type无效 + +**错误信息**
+The specified type is invalid. + +**错误描述**
+输入的type无效。 + +**可能原因**
+1. 输入的type拼写有误。 +2. 输入的type不存在。 + +**处理步骤**
+确认输入的type是否拼写正确。 + +## 17700026 指定应用被禁用 + +**错误信息**
+The specified bundle is disabled. + +**错误描述**
+指定应用被禁用。 + +**可能原因**
+设备上对应的应用已经被禁用,无法查询。 + +**处理步骤**
+确认设备上对应的应用是否被禁用。 + +## 17700027 分布式服务未启动 + +**错误信息**
+The distributed service is not running. + +**错误描述**
+分布式服务未启动。 + +**可能原因**
+设备未组网。 + +**处理步骤**
+确认设备是否组网成功。 +## 17700028 输入的ability与type不匹配 + +**错误信息**
+The distributed service is not running. + +**错误描述**
+输入的ability与type不匹配。 + +**可能原因**
+输入的ability和type拼写有误。 + +**处理步骤**
+确认输入的ability和type拼写是否正确。 diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-hiviewdfx-hiappevent.md b/zh-cn/application-dev/reference/errorcodes/errcode-hiviewdfx-hiappevent.md new file mode 100644 index 0000000000000000000000000000000000000000..c36645d3d21788f24bddabcf644ca4f438bb8cab --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errcode-hiviewdfx-hiappevent.md @@ -0,0 +1,278 @@ +# 应用事件打点错误码 + +## 11100001 打点功能被关闭 + +**错误信息** + +Function is disabled. + +**错误描述** + +在调用write接口进行应用事件打点时,由于打点功能未开启,系统将忽略相关事件。 + +**可能原因** + +应用事件打点功能被关闭了。 + +**处理步骤** +调用配置接口开启打点功能。 + + ```js + hiAppEvent.configure({ + disable: false + }); + ``` + +## 11101001 非法的事件领域名称 +**错误信息** + +Invalid event domain. + +**错误描述** + +在调用write接口进行应用事件打点时,由于传入了非法的事件领域名称,系统将忽略相关事件。 + +**可能原因** + +传入的事件领域名称不符合以下规则: + +- 事件领域名称只包含数字、小写字母、下划线字符。 +- 事件领域名称以小写字母开头,不以下划线结尾。 +- 事件领域名称非空且长度不超过32个字符。 + +**处理步骤** +传入合法的事件领域名称。 + +## 11101002 非法的事件名称 + +**错误信息** + +Invalid event name. + +**错误描述** + +在调用write接口进行应用事件打点时,由于传入了非法的事件名称,系统将忽略相关事件。 + +**可能原因** + +传入的事件名称不符合以下规则: + +- 事件名称只包含数字、小写字母、下划线字符。 +- 事件名称以小写字母开头,不以下划线结尾。 +- 事件名称非空且长度不超过48个字符。 + +**处理步骤** + +传入合法的事件名称。 + +## 11101003 非法的事件参数数量 + +**错误信息** + +Invalid number of event parameters. + +**错误描述** + +在调用write接口进行应用事件打点时,由于传入了非法的事件参数数量,额外的事件参数将被丢弃。 + +**可能原因** + +传入的事件参数数量超过32个。 + +**处理步骤** + +传入合法数量的事件参数。 + +## 11101004 非法的事件参数字符串长度 + +**错误信息** + +Invalid string length of the event parameter. + +**错误描述** + +在调用write接口进行应用事件打点时,由于事件参数值传入了超长的字符串,超出长度的字符将被丢弃。 + +**可能原因** + +传入的事件参数值中的字符串长度超过8*1024个字符。 + +**处理步骤** + +传入合法字符串长度的事件参数值。 + +## 11101005 非法的事件参数名称 + +**错误信息** + +Invalid event parameter name. + +**错误描述** + +在调用write接口进行应用事件打点时,由于传入了非法的事件参数名称,系统将忽略相关事件参数。 + +**可能原因** + +传入的事件名称不符合以下规则: + +- 事件名称只包含数字、小写字母、下划线字符。 +- 事件名称以小写字母开头,不以下划线结尾。 +- 事件名称非空且长度不超过16个字符。 + +**处理步骤** + +传入合法的事件参数名称。 + +## 11101006 非法的事件参数数组长度 + +**错误信息** + +Invalid array length of the event parameter. + +**错误描述** + +在调用write接口进行应用事件打点时,由于事件参数值传入了超出长度的数组,额外的数组元素将被丢弃。 + +**可能原因** + +传入的事件参数值中的数组长度超过100。 + +**处理步骤** + +传入合法长度数组的事件参数值。 + +## 11102001 非法的观察者名称 + +**错误信息** + +Invalid watcher name. + +**错误描述** + +在调用addWatcher接口进行事件订阅时,由于传入了非法的观察者名称,系统将忽略此次订阅。 + +**可能原因** + +传入的观察者名称不符合以下规则: + +- 观察者名称只包含数字、小写字母、下划线字符。 +- 观察者名称以小写字母开头,不以下划线结尾。 +- 观察者名称非空且长度不超过32个字符。 + +**处理步骤** + +传入合法的观察者名称。 + +## 11102002 非法的过滤事件领域 + +**错误信息** + +Invalid filtering event domain. + +**错误描述** + +在调用addWatcher接口进行事件订阅时,由于传入了非法的过滤事件领域,系统将忽略此次订阅。 + +**可能原因** + +传入的过滤事件领域名称不符合以下规则: + +- 事件领域名称只包含数字、小写字母、下划线字符。 +- 事件领域名称以小写字母开头,不以下划线结尾。 +- 事件领域名称非空且长度不超过32个字符。 + +**处理步骤** + +传入合法的过滤事件领域名称。 + +## 11102003 非法的条数值 + +**错误信息** + +Invalid row value. + +**错误描述** + +在调用addWatcher接口进行事件订阅时,由于回调触发条件传入了非法的事件个数值,系统将忽略此次订阅。 + +**可能原因** + +传入的回调触发条件中的条数值为负数。 + +**处理步骤** + +传入自然数值的条数值。 + +## 11102004 非法的大小值 + +**错误信息** + +Invalid size value. + +**错误描述** + +在调用addWatcher接口进行事件订阅时,由于回调触发条件传入了非法的事件大小值,系统将忽略此次订阅。 + +**可能原因** + +传入的回调触发条件中的大小值为负数。 + +**处理步骤** + +传入自然数值的大小值。 + +## 11102005 非法的超时值 + +**错误信息** + +Invalid timeout value. + +**错误描述** + +在调用addWatcher接口进行事件订阅时,由于回调触发条件传入了非法的超时值,系统将忽略此次订阅。 + +**可能原因** + +传入的回调触发条件中的超时值为负数。 + +**处理步骤** + +传入自然数值的超时值。 + +## 11103001 非法的最大存储配额值 + +**错误信息** + +Invalid max storage quota value. + +**错误描述** + +在调用configure接口进行打点配置时,由于传入了非法的最大存储配额值,系统将忽略此次配置。 + +**可能原因** + +传入的最大存储配额值字符串不符合以下规则: + +- 最大存储配额值以数字开头,以大小单位(单位字符支持[b|k|kb|m|mb|g|gb|t|tb],不区分大小写)结尾,且不包含其他字符。 + +**处理步骤** + +传入合法的最大存储配额值字符串。 + +## 11104001 非法的事件包大小值 + +**错误信息** + +Invalid size value. + +**错误描述** + +在调用setSize接口对每次取出的事件包大小阈值进行设置时,由于传入了非法的事件包大小值,系统将忽略此次设置。 + +**可能原因** + +传入的事件包大小值为负数。 + +**处理步骤** + +传入自然数值的事件包大小。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errcode-usb.md b/zh-cn/application-dev/reference/errorcodes/errcode-usb.md new file mode 100644 index 0000000000000000000000000000000000000000..4a7910cc0b9a9074c002185ab880e9a3030a91ac --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errcode-usb.md @@ -0,0 +1,19 @@ +# USB服务错误码 + +## 14400001 连接USB设备被拒绝 + +**错误信息** + +Permission denied. Need call requestRight to get permission. + +**错误描述** + +当调用USB模块部分接口时,如果没有相关权限,会报此错误码。 + +**可能原因** + +没有获取到设备的使用权限。 + +**处理步骤** + +调用requestRight方法申请设备的使用权限。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md b/zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md index 03e236d1efa66912b05626dc691b0e945b3211ed..16a8cf53764e369e6b3f916063da3c10c5bb4b9c 100644 --- a/zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-access-token.md @@ -56,7 +56,7 @@ Permission does not exist. **错误信息** -The listener interface is not used together. +The interface is not used together. **可能原因** diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-device-manager.md b/zh-cn/application-dev/reference/errorcodes/errorcode-device-manager.md new file mode 100644 index 0000000000000000000000000000000000000000..1884284f55f3636e0b366820dffa7d48a225da72 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-device-manager.md @@ -0,0 +1,71 @@ +# 设备管理错误码 + +## 11600101 服务调用异常 + +**错误信息** + +Failed to execute the function. + +**可能原因** + +服务内部调用异常。 + +**处理步骤** + +重新调用接口再次触发调用。 + +## 11600102 获取服务失败 + +**错误信息** + +Failed to obtain the service. + +**可能原因** + +服务未启动或者服务启动失败。 + +**处理步骤** + +检查服务是否正常启动,重新获取服务。 + +## 11600103 认证业务不可用 + +**错误信息** + +Authentication invalid. + +**可能原因** + +上一次认证业务未结束。 + +**处理步骤** + +等待上一次认证业务结束,重新发起认证调用。 + +## 11600104 发现业务不可用 + +**错误信息** + +Discovery invalid. + +**可能原因** + +上一次发现业务未结束。 + +**处理步骤** + +等待上一次发现业务结束,重新发起发现调用。 + +## 11600105 发布业务不可用 + +**错误信息** + +Publish invalid. + +**可能原因** + +上一次发布业务未结束。 + +**处理步骤** + +等待上一次发布业务结束,重新发起发布调用。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md b/zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md new file mode 100644 index 0000000000000000000000000000000000000000..397279658180123ee8d4b8989810ff549e29b6bd --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-faultlogger.md @@ -0,0 +1,19 @@ +# faultlogger 错误码 + +## 10600001 服务未启动或故障 + +**错误信息** + +The service is not running or broken. + +**错误描述** + +服务未启动/故障。 + +**可能原因** + +hiview服务未启动。 + +**处理步骤** + +不应该发生的场景,考虑重试。 \ No newline at end of file diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-hisysevent.md b/zh-cn/application-dev/reference/errorcodes/errorcode-hisysevent.md new file mode 100644 index 0000000000000000000000000000000000000000..0d573cf63851c5a46fffafb7c43b9b132947d7a6 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-hisysevent.md @@ -0,0 +1,284 @@ +# 系统事件错误码 + +## 1120001 非法的事件领域 + +**错误信息** + +Invalid event domain. + +**错误描述** + +在调用write接口进行系统事件打点时,由于传入了非法的事件领域名称,系统将忽略此次系统事件打点。 + +**可能原因** + +1.系统事件领域名称长度超过16个字符; +2.系统事件领域名称包含特殊字符; +3.系统事件领域名称为空。 + +**处理步骤** + +检查系统事件领域名称是否合法。 + +## 1120002 非法的事件名称 + +**错误信息** + +Invalid event name. + +**错误描述** + +在调用write接口进行系统事件打点时,由于传入了非法的事件名称,系统将忽略此次系统事件打点。 + +**可能原因** + +1.系统事件名称长度超过32个字符; +2.系统事件名称包含特殊字符; +3.系统事件名称为空。 + +**处理步骤** + +检查系统事件名称是否合法。 + +## 11200003 环境异常 + +**错误信息** + +Abnormal environment. + +**错误描述** + +在调用write接口进行系统事件打点时,由于环境异常,系统将忽略此次系统事件打点。 + +**可能原因** + +1.hiview服务未成功启动; +2.hiview服务socket异常。 + +**处理步骤** + +尝试重新调用write接口进行打点。 + +## 11200004 事件长度超过限制 + +**错误信息** + +Length of the event is over limit. + +**错误描述** + +在调用write接口进行系统事件打点时,由于传入的事件总长度超过限制,系统将忽略此次系统事件打点。 + +**可能原因** + +系统事件总长度超过384K。 + +**处理步骤** + +检查系统事件总长度是否大于384K。 + +## 11200051 非法的事件参数 + +**错误信息** + +Invalid event parameter. + +**错误描述** + +在调用write接口进行系统事件打点时,由于传入了非法的参数名称,系统将忽略此次系统事件打点。 + +**可能原因** + +1.系统事件参数名称长度超过32个字符; +2.系统事件参数名称包含特殊字符; +3.系统事件参数名为空。 + +**处理步骤** + +检查系统事件参数名称是否合法。 + +## 11200052 字符串类型的事件参数值的长度超过限制 + +**错误信息** + +Size of the event parameter of the string type is over limit. + +**错误描述** + +在调用write接口进行系统事件打点时,由于传入了长度超限的字符串类型参数,系统将忽略此次系统事件打点。 + +**可能原因** + +字符串类型的参数值的长度超过256K。 + +**处理步骤** + +检查系统事件中字符串类型的参数值的长度是否超过256K。 + +## 11200053 事件参数的数量超过限制 + +**错误信息** + +Count of event parameters is over limit. + +**错误描述** + +在调用write接口进行系统事件打点时,由于传入的事件参数数量超过限制,系统将将忽略此次系统事件打点。 + +**可能原因** + +系统事件的参数数量超过128个。 + +**处理步骤** + +检查系统事件的参数数量是否超过了128个。 + + +## 11200054 数组类型的事件参数值的长度超过限制 + +**错误信息** + +Count of event parameter of the array type is over limit. + +**错误描述** + +在调用write接口进行系统事件打点时,由于传入了长度超过限制的数组类型的参数,系统将忽略此次系统事件打点。 + +**可能原因** + +系统事件中有数组类型的参数值的长度超过100。 + +**处理步骤** + +检查数组类型的参数值的长度是否超过100. + +## 11200101 事件监听者的数量超过限制 + +**错误信息** + +Count of watchers is over limit. + +**错误描述** + +在调用addWatcher接口添加系统事件监听者时,由于添加的监听者数量超过限制,系统将拒绝此系统事件监听者的添加。 + +**可能原因** + +hiview服务已添加30个系统事件监听者,无法添加新的系统事件监听者。 + +**处理步骤** + +检查已成功添加的系统事件监听者数量是否超过了30个。 + +## 11200102 事件监听者包含的监听规则数量超过限制 + +**错误信息** + +Count of watch rules is over limit. + +**错误描述** + +在调用addWatcher接口添加系统事件监听者时,由于该系统事件监听者包含的监听规则数量超过限制,系统将拒绝此系统事件监听者的添加。 + +**可能原因** + +系统事件监听者包含的监听规则的数量超过20个。 + +**处理步骤** + +检查系统事件监听者包含的监听规则数量是否超过20个。 + +## 11200201 事件监听者不存在 + +**错误信息** + +The watcher does not exist. + +**错误描述** + +在调用removeWatcher移除系统事件监听者时,由于该系统事件监听者不在监听队列,系统将拒绝此系统事件监听者的移除。 + +**可能原因** + +1.尝试移除的系统事件监听者为空; +2.尝试移除的系统事件监听者没有被成功添加过。 + +**处理步骤** + +检查移除的系统事件监听者是否为空,或者是否成功添加过此系统事件监听者。 + +## 11200301 查询规则的数量超过限制 + +**错误信息** + +Count of query rules is over limit. + +**错误描述** + +在调用query接口查询系统事件时,由于传入的查询规则数量超限,系统将忽略此次系统事件的查询。 + +**可能原因** + +查询规则个数超过10个。 + +**处理步骤** + +检查查询规则数量是否超过10个。 + + +## 11200302 非法的查询规则 + +**错误信息** + +Invalid query rule. + + +**错误描述** + +在调用query接口查询系统事件时,由于传入了非法的查询规则,系统将忽略此次系统事件的查询。 + +**可能原因** + +1.查询规则中的事件领域名称长度超过16个字符或者事件名称长度超过32个字符; +2.查询规则中的事件领域名称或者事件名称包含特殊字符; +3.查询规则中的事件领域名称或者事件名称为空。 + +**处理步骤** + +检查查询规则中配置的事件领域名称及事件名称是否合法。 + +## 11200303 并发查询的数量超过限制 + +**错误信息** + +Count of concurrent queriers is over limit. + +**错误描述** + +在调用query接口查询系统事件时,由于在同一时间点并发查询的数量超过限制,系统将忽略此次系统事件的查询。 + +**可能原因** + +并发查询的数量超过4个。 + +**处理步骤** + +检查在同一时间点是否有4个以上的查询操作。 + +## 11200304 查询频率超过限制 + +**错误信息** + +Query frequency is over limit. + +**错误描述** + +在调用query接口查询系统事件时,由于查询频率超过限制,系统将忽略此次系统事件的查询。 + +**可能原因** + +查询频率超过1次/秒。 + +**处理步骤** + +检查是否在1秒内进行1次以上的查询。 diff --git a/zh-cn/application-dev/reference/errorcodes/errorcode-hiviewdfx-hidebug.md b/zh-cn/application-dev/reference/errorcodes/errorcode-hiviewdfx-hidebug.md new file mode 100644 index 0000000000000000000000000000000000000000..4c843b8bbde55cd2fe27b1d4a47c10126a023c0f --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcode-hiviewdfx-hidebug.md @@ -0,0 +1,20 @@ +# Hidebug错误码 + + +## 11400101 系统服务获取失败 + +**错误信息** + +ServiceId is invalid, systemAbility is not exist. + +**错误描述** +当前serviceId未查询到对应的系统服务。 + +**可能原因** + +当前serviceId未查询到对应的系统服务。 + +**处理步骤** + +传入正确的系统服务id。 + diff --git a/zh-cn/application-dev/reference/errorcodes/errorcodes-request.md b/zh-cn/application-dev/reference/errorcodes/errorcodes-request.md new file mode 100644 index 0000000000000000000000000000000000000000..2f7063b797dea8ff1f61361128ef7105252b8172 --- /dev/null +++ b/zh-cn/application-dev/reference/errorcodes/errorcodes-request.md @@ -0,0 +1,55 @@ +# 上传下载错误码 + +## 13400001 文件操作异常 + +**错误信息** + +File operation error. + +**错误描述** + +在调用uploadFile或downloadFile接口时,文件权限不足或操作失败。 + +**可能原因** + +该错误码表示文件操作异常,可能原因文件权限不足。 + +**处理步骤** + +请检查文件权限是否合理。 + +## 13400002 文件路径异常 + +**错误信息** + +Bad file path. + +**错误描述** + +在调用uploadFile或downloadFile接口时,文件路径不合法。 + +**可能原因** + +该错误码表示文件路径异常,可能原因文件路径错误。 + +**处理步骤** + +请检查上传下载的文件路径是否正确。 + +## 13400003 服务异常 + +**错误信息** + +Task manager service error. + +**错误描述** + +在调用downloadFile接口时,下载任务后台服务失败。 + +**可能原因** + +该错误码表示服务异常,,可能原因任务创建失败 + +**处理步骤** + +请检查任务配置是否正确。 diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-button.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-button.md index 85c5e3f991f074293020d6c8bda91d552e128f76..e2f30cc43202e020269f86c48ce063e8c0288207 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-button.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-button.md @@ -18,7 +18,7 @@ | 名称 | 类型 | 默认值 | 必填 | 描述 | | -------- | -------- | -------- | -------- | -------- | -| type | string | - | 否 | 不支持动态修改。如果该属性缺省,展示类胶囊型按钮,不同于胶囊类型,四边圆角可以通过border-radius分别指定,如果需要设置该属性,可选值如下:
- "capsule":胶囊型按钮,带圆角按钮,有背景色和文本。
- "circle":圆形按钮,支持放置图标。
- "text":文本按钮,仅包含文本显示。 | +| type | string | capsule | 否 | 不支持动态修改。如果该属性缺省,展示类胶囊型按钮,不同于胶囊类型,四边圆角可以通过border-radius分别指定,如果需要设置该属性,可选值如下:
- "capsule":胶囊型按钮,带圆角按钮,有背景色和文本。
- "circle":圆形按钮,支持放置图标。
- "text":文本按钮,仅包含文本显示。 | | value | string | - | 否 | button的文本值,circle类型不生效。 | | icon | string | - | 否 | button的图标路径,图标格式为jpg,png和svg。 | | placement | string | end | 否 | 仅在type属性为缺省时生效,设置图标位于文本的位置,可选值为:
- "start":图标位于文本起始处。
- "end":图标位于文本结束处。
- "top":图标位于文本上方。
- "bottom":图标位于文本下方。 | diff --git a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-chart.md b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-chart.md index b33a056112da8b5298eb5cd3a79eefb458deeda7..42fab229cffde0dc14d0e99ff49bb00b0f91b6b2 100644 --- a/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-chart.md +++ b/zh-cn/application-dev/reference/js-service-widget-ui/js-service-widget-basic-chart.md @@ -16,14 +16,14 @@ 除支持[通用属性](js-service-widget-common-attributes.md)外,还支持如下属性: -| 名称 | 类型 | 默认值 | 必填 | 描述 | -| ----------------- | ---------------------------------- | ---- | ---- | ---------------------------------------- | -| type | string | line | 否 | 设置图表类型(不支持动态修改),可选项有:
- bar:柱状图。
- line:线形图。
- gauge:量规图。
- progress:进度类圆形图表。
- loading:加载类圆形图表。
- rainbow:占比类圆形图表。 | -| options | ChartOptions | - | 否 | 图表参数设置,柱状图和线形图必须设置参数设置,量规图不生效。可以设置x轴、y轴的最小值、最大值、刻度数、是否显示,线条宽度、是否平滑等。(不支持动态修改) | -| datasets | Array\ | - | 否 | 数据集合,柱状图和线形图必须设置数据集合,量规图不生效。可以设置多条数据集及其背景色。 | -| segments | DataSegment \| Array\ | | 否 | 进度类、加载类和占比类圆形图表使用的数据结构。
DataSegment针对进度类和加载类圆形图表使用,Array\针对占比类图标使用,DataSegment最多9个。 | -| effects | boolean | true | 否 | 是否开启占比类、进度类圆形图表特效。 | -| animationduration | number | 3000 | 否 | 设置占比类圆形图表展开动画时长,单位为ms。 | +| 名称 | 类型 | 默认值 | 必填 | 描述 | +| ----------------- | ---------------------------------- | ------ | ---- | ------------------------------------------------------------ | +| type | string | line | 否 | 设置图表类型(不支持动态修改),可选项有:
- bar:柱状图。
- line:线形图。
- gauge:量规图。
- progress:进度类圆形图表。
- loading:加载类圆形图表。
- rainbow:占比类圆形图表。 | +| options | ChartOptions | - | 否 | 图表参数设置,用于设置x轴、y轴的最小值、最大值、刻度数、是否显示,线条宽度、是否平滑等。(不支持动态修改),量规图不生效。 | +| datasets | Array\ | - | 否 | 数据集合,用于设置多条数据集及其背景色,量规图不生效。 | +| segments | DataSegment \| Array\ | | 否 | 进度类、加载类和占比类圆形图表使用的数据结构。
DataSegment针对进度类和加载类圆形图表使用,Array\针对占比类图标使用,DataSegment最多9个。 | +| effects | boolean | true | 否 | 是否开启占比类、进度类圆形图表特效。 | +| animationduration | number | 3000 | 否 | 设置占比类圆形图表展开动画时长,单位为ms。 | **表1** ChartOptions diff --git a/zh-cn/application-dev/security/accesstoken-guidelines.md b/zh-cn/application-dev/security/accesstoken-guidelines.md index 45cd9279b55872bed403e2b1ce8e3e74a34a591e..408d90afdf1bcfb3883f8dd74dde5a1d1222306c 100644 --- a/zh-cn/application-dev/security/accesstoken-guidelines.md +++ b/zh-cn/application-dev/security/accesstoken-guidelines.md @@ -171,5 +171,5 @@ 针对访问控制,有以下相关实例可供参考: -- [`AbilityAccessCtrl`:访问权限控制(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Safety/AbilityAccessCtrl) -- [为应用添加运行时权限(eTS)(API 9)](https://gitee.com/openharmony/codelabs/tree/master/Ability/AccessPermission) \ No newline at end of file +- [`AbilityAccessCtrl`:访问权限控制(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/Safety/AbilityAccessCtrl) +- [为应用添加运行时权限(ArkTS)(API 9)](https://gitee.com/openharmony/codelabs/tree/master/Ability/AccessPermission) \ No newline at end of file diff --git a/zh-cn/application-dev/security/cryptoFramework-guidelines.md b/zh-cn/application-dev/security/cryptoFramework-guidelines.md index 368108ba13572fde86046d1e30febc4dae2551ed..734dcf92c03846e7755e29005c5fd9914d5a3195 100644 --- a/zh-cn/application-dev/security/cryptoFramework-guidelines.md +++ b/zh-cn/application-dev/security/cryptoFramework-guidelines.md @@ -100,7 +100,7 @@ function testGenerateAesKey() { 示例3:根据指定的RSA非对称密钥二进制数据,生成KeyPair对象(场景2) -1. 获取RSA二进制密钥数据封装成DataBlob对象,按keysize(32位) 、nsize(keysize/8)、 esize(e实际长度)、dsize(keysize/8)、nval(大数n的二进制数据)、eval(大数e的二进制数据)和dval(大数d的二进制数据)拼接形成。 +1. 获取RSA二进制密钥数据封装成DataBlob对象,按keysize(32位的密钥位数) 、nsize(32位,值为keysize/8)、 esize(32位的大数e的实际长度,单位Byte)、dsize(32位,值位keysize/8)、nval(大数n的二进制数据)、eval(大数e的二进制数据)和dval(大数d的二进制数据)拼接形成。 2. 调用convertKey方法,传入公钥二进制和私钥二进制(二者非必选项,可只传入其中一个),转换为KeyPair对象。 ```javascript @@ -649,7 +649,7 @@ function signMessageCallback() { } function verifyMessageCallback() { - let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25"); + let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256"); verifyer.init(globalKeyPair.pubKey, function (err, data) { verifyer.update(input1, function(err, data) { verifyer.verify(input2, SignMessageBlob, function(err, data) { @@ -875,15 +875,6 @@ function doMdByCallback(algName) { ```javascript import cryptoFramework from "@ohos.security.cryptoFramework" -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; function ecdhPromise() { diff --git a/zh-cn/application-dev/security/huks-guidelines.md b/zh-cn/application-dev/security/huks-guidelines.md index ad21dacc614d44fe52b4829ebe8cdef4d5e7ff6d..be627e670fcd7250d050e319c31179d5830f2b0c 100644 --- a/zh-cn/application-dev/security/huks-guidelines.md +++ b/zh-cn/application-dev/security/huks-guidelines.md @@ -625,7 +625,7 @@ struct Index { | ------------------------------------------------------------ | -------------------------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------- | ----------- | | HUKS_ALG_SM4 (支持长度: HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | 【非必选】 | HUKS_PADDING_NONE | HUKS_MODE_CTR HUKS_MODE_ECB HUKS_MODE_CBC | 【必选】 | | HUKS_ALG_SM4 (支持长度: HUKS_SM4_KEY_SIZE_128) | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | 【非必选】 | HUKS_PADDING_PKCS7 | HUKS_MODE_ECB HUKS_MODE_CBC | 【必选】 | -| HUKS_ALG_RSA (支持长度: HUKS_SM4_KEY_SIZE_512 HUKS_SM4_KEY_SIZE_768 HUKS_SM4_KEY_SIZE_1024 HUKS_SM4_KEY_SIZE_2048 HUKS_SM4_KEY_SIZE_3072 HUKS_SM4_KEY_SIZE_4096) | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | HUKS_PADDING_NONE HUKS_PADDING_PKCS1_V1_5 HUKS_PADDING_OAEP | HUKS_MODE_ECB | 【非必选】 | +| HUKS_ALG_RSA (支持长度: HUKS_RSA_KEY_SIZE_512 HUKS_RSA_KEY_SIZE_768 HUKS_RSA_KEY_SIZE_1024 HUKS_RSA_KEY_SIZE_2048 HUKS_RSA_KEY_SIZE_3072 HUKS_RSA_KEY_SIZE_4096) | HUKS_KEY_PURPOSE_ENCRYPT HUKS_KEY_PURPOSE_DECRYPT | HUKS_DIGEST_SHA1 HUKS_DIGEST_SHA224 HUKS_DIGEST_SHA256 HUKS_DIGEST_SHA384 HUKS_DIGEST_SHA512 | HUKS_PADDING_NONE HUKS_PADDING_PKCS1_V1_5 HUKS_PADDING_OAEP | HUKS_MODE_ECB | 【非必选】 | | HUKS_ALG_ALGORITHM | HUKS_TAG_PURPOSE | HUKS_TAG_PADDING | HUKS_TAG_BLOCK_MODE | HUKS_TAG_IV | HUKS_TAG_NONCE | HUKS_TAG_ASSOCIATED_DATA | HUKS_TAG_AE_TAG | | ------------------------------------------------------------ | ------------------------ | ------------------------------------- | ---------------------------- | ----------- | -------------- | ------------------------ | --------------- | diff --git a/zh-cn/application-dev/security/permission-list.md b/zh-cn/application-dev/security/permission-list.md index 93151a0c682a67f4d0f661cc0f4c0ac51d3fae34..4173342f15e987ded3dfcbddf12d775707cfd2ae 100644 --- a/zh-cn/application-dev/security/permission-list.md +++ b/zh-cn/application-dev/security/permission-list.md @@ -148,4 +148,5 @@ | ohos.permission.ACCESS_CERT_MANAGER_INTERNAL | system_basic | system_grant | FALSE | 允许应用进行证书及凭据的安装、卸载、启用、禁用等操作。 | | ohos.permission.ACCESS_CERT_MANAGER | normal | system_grant | FALSE | 允许应用进行私有凭据的相关操作、查询证书状态等操作。 | | ohos.permission.ACCESS_PUSH_SERVICE | system_basic | system_grant | TRUE | 允许应用访问推送服务的Ability。 | -| ohos.permission.RECEIVER_STARTUP_COMPLETED | system_basic | system_grant | FALSE | 允许应用订阅开机广播。 | \ No newline at end of file +| ohos.permission.RECEIVER_STARTUP_COMPLETED | system_basic | system_grant | FALSE | 允许应用订阅开机广播。 | +| ohos.permission.MANAGE_CAMERA_CONFIG | system_basic | system_grant | FALSE | 允许应用进行全局相机开关等操作。 | \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-guide.md b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-guide.md index ca596efaaa2537e895135f474c1ab6bc2bc71619..f442fa9914b821e1009fc3452a41e531d2c518a0 100644 --- a/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-guide.md +++ b/zh-cn/application-dev/task-management/background-agent-scheduled-reminder-guide.md @@ -170,8 +170,8 @@ reminderAgent:封装了发布、取消提醒类通知的方法。 基于后台代理提醒开发,有以下相关实例可供参考: -- [`AlarmClock`:后台代理提醒(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) +- [`AlarmClock`:后台代理提醒(ArkTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/Notification/AlarmClock) -- [`FlipClock`:翻页时钟(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/CompleteApps/FlipClock) +- [`FlipClock`:翻页时钟(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/CompleteApps/FlipClock) -- [闹钟应用(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/CommonEventAndNotification/AlarmClock) \ No newline at end of file +- [闹钟应用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/CommonEventAndNotification/AlarmClock) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/background-task-dev-guide.md b/zh-cn/application-dev/task-management/background-task-dev-guide.md index b279133c7705c8940cddf4721847b00b50156daa..fd4d3c3948b6ed69680c9294b10bb1838654b35f 100644 --- a/zh-cn/application-dev/task-management/background-task-dev-guide.md +++ b/zh-cn/application-dev/task-management/background-task-dev-guide.md @@ -579,4 +579,4 @@ backgroundTaskManager.backgroundTaskManager.resetAllEfficiencyResources(); 基于后台任务管理,有以下相关实例可供参考: -- [`BackgroundTaskManager`:后台任务管理(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) \ No newline at end of file +- [`BackgroundTaskManager`:后台任务管理(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/BackgroundTaskManager) \ No newline at end of file diff --git a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md index 300086d76e88216b98d0e7f67b0a112ec95b7913..625b3046cc8f3c16e03de8ecc96dab436b722c38 100644 --- a/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md +++ b/zh-cn/application-dev/task-management/work-scheduler-dev-guide.md @@ -198,4 +198,4 @@ onWorkStop(work: WorkInfo): void | 延迟调度任务结束回调 基于延迟任务调度,有以下相关实例可供参考: -- [`WorkScheduler`:延迟任务调度(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/WorkScheduler) \ No newline at end of file +- [`WorkScheduler`:延迟任务调度(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/WorkScheduler) \ No newline at end of file diff --git a/zh-cn/application-dev/telephony/cellular-network-signal-info.md b/zh-cn/application-dev/telephony/cellular-network-signal-info.md index 8c308e38578da07e19b7fe129fa0af7f47db0ca4..2e37ff8134208b978720953229ee445d8cd922e6 100644 --- a/zh-cn/application-dev/telephony/cellular-network-signal-info.md +++ b/zh-cn/application-dev/telephony/cellular-network-signal-info.md @@ -53,4 +53,4 @@ radio模块提供了获取当前网络信号信息的方法。observer模块为 ## 相关实例 针对蜂窝网络数据开发,有以下相关实例可供参考: -- [`MobileNetwork`:蜂窝数据(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/MobileNetwork) \ No newline at end of file +- [`MobileNetwork`:蜂窝数据(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Telephony/MobileNetwork) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/Readme-CN.md b/zh-cn/application-dev/ui/Readme-CN.md index 43a36d9c018f9e9b7679c5a6a64117f38e91d9b1..8131710e12f0374526d018ad93b998b7aff41f45 100755 --- a/zh-cn/application-dev/ui/Readme-CN.md +++ b/zh-cn/application-dev/ui/Readme-CN.md @@ -1,8 +1,7 @@ # UI开发 - [方舟开发框架(ArkUI)概述](arkui-overview.md) - -- UI开发(基于eTS的声明式开发范式) +- UI开发(基于ArkTS的声明式开发范式) - [概述](ui-ts-overview.md) - 框架说明 - 文件组织 diff --git a/zh-cn/application-dev/ui/arkui-overview.md b/zh-cn/application-dev/ui/arkui-overview.md index fa6a13c44764b405d9233895a71216803086f671..842f41437ad61473148e93a21923e70e045c1052 100644 --- a/zh-cn/application-dev/ui/arkui-overview.md +++ b/zh-cn/application-dev/ui/arkui-overview.md @@ -26,7 +26,7 @@ | 开发范式名称 | 简介 | 适用场景 | 适用人群 | | -------- | ---------------------------------------- | ---------------- | ------------------- | - | 声明式开发范式 | 采用基于TypeScript进行声明式UI语法扩展而来的[ArkTS语言](../quick-start/ets-get-started.md),从组件、动画和状态管理三个维度提供了UI绘制能力。声明式开发范式更接近自然语义的编程方式,让开发者直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。 | 复杂度较大、团队合作度较高的应用 | 移动系统应用开发人员、系统应用开发人员 | + | 声明式开发范式 | 采用基于TypeScript进行声明式UI语法扩展而来的[ArkTS语言](../quick-start/arkts-get-started.md),从组件、动画和状态管理三个维度提供了UI绘制能力。声明式开发范式更接近自然语义的编程方式,让开发者直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。 | 复杂度较大、团队合作度较高的应用 | 移动系统应用开发人员、系统应用开发人员 | | 类Web开发范式 | 采用经典的HML、CSS、JavaScript三段式开发方式,使用HML标签文件进行布局搭建,使用CSS文件进行样式描述,使用JavaScript文件进行逻辑处理。UI组件与数据之间通过单向数据绑定的方式建立关联,当数据发生变化时,UI界面自动触发刷新。该开发方式更接近Web前端开发者的使用习惯,便于快速将已有的Web应用改造成方舟开发框架应用。 | 界面较简单的中小型应用和卡片 | Web前端开发人员 | ## 框架结构 diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_00000011.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_00000011.gif new file mode 100644 index 0000000000000000000000000000000000000000..9dd23bf2e649eb1e9c7a71281a8f26dcd90d6f26 Binary files /dev/null and b/zh-cn/application-dev/ui/figures/zh-cn_image_00000011.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif index 7d8da86f2f1cf71ca9bc5d6cb65564bb64ae5fd1..16e7ff213bd5caf5a9802001d3ced2996c66e0bc 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001176075554.gif differ diff --git a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif index 9e313e1e87059572aa036b06881381da7b070641..0cbcaa3ff368a2a2ad63c8729acc0f66ae874437 100644 Binary files a/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif and b/zh-cn/application-dev/ui/figures/zh-cn_image_0000001227701867.gif differ diff --git a/zh-cn/application-dev/ui/ts-framework-directory.md b/zh-cn/application-dev/ui/ts-framework-directory.md index c64f4439911f8f0580a7d9f3092c0dcda80f1481..b20e3023475a0ced28afa89fb94ad2f02a75e077 100644 --- a/zh-cn/application-dev/ui/ts-framework-directory.md +++ b/zh-cn/application-dev/ui/ts-framework-directory.md @@ -1,7 +1,7 @@ # 目录结构 -FA应用的eTS模块(entry/src/main)的典型开发目录结构如下: +FA应用的ArkTS模块(entry/src/main)的典型开发目录结构如下: ![zh-cn_image_0000001182200571](figures/zh-cn_image_0000001182200571.png) @@ -10,7 +10,7 @@ FA应用的eTS模块(entry/src/main)的典型开发目录结构如下: **目录结构中文件分类如下:** -.ets结尾的eTS(extended TypeScript)文件,用于描述UI布局、样式、事件交互和页面逻辑。 +.ets结尾的ArkTS文件,用于描述UI布局、样式、事件交互和页面逻辑。 **各个文件夹和文件的作用:** diff --git a/zh-cn/application-dev/ui/ts-pixel-units.md b/zh-cn/application-dev/ui/ts-pixel-units.md index 0385cfbf9d1a11bf7adb4ab41a09ccac536634b3..3a4c5c7e6a0ef27361f80529265cff853e5600db 100644 --- a/zh-cn/application-dev/ui/ts-pixel-units.md +++ b/zh-cn/application-dev/ui/ts-pixel-units.md @@ -78,4 +78,4 @@ struct Example { 基于像素转换,有以下相关实例可供参考: -- [像素转换(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/PixelUnitsDemo) +- [像素转换(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/PixelUnitsDemo) diff --git a/zh-cn/application-dev/ui/ts-resource-access.md b/zh-cn/application-dev/ui/ts-resource-access.md index 5ab95b5eba3fbf1a325dea0b9f6fdd7a10ba6193..a2ea1141108398203160e8fa752d1cc4727c5889 100644 --- a/zh-cn/application-dev/ui/ts-resource-access.md +++ b/zh-cn/application-dev/ui/ts-resource-access.md @@ -151,4 +151,4 @@ plural.json文件的内容如下: 针对访问应用资源,有以下相关实例可供参考: -- [`ResourceManager`:资源管理器(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager) +- [`ResourceManager`:资源管理器(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/common/ResourceManager) diff --git a/zh-cn/application-dev/ui/ui-js-building-ui-event.md b/zh-cn/application-dev/ui/ui-js-building-ui-event.md index 9c09ebb86f3b0a6177307deb7d7cd6b5ebca2bc2..e1aa990223059ba6190c147f6753e5fc48de85d7 100755 --- a/zh-cn/application-dev/ui/ui-js-building-ui-event.md +++ b/zh-cn/application-dev/ui/ui-js-building-ui-event.md @@ -48,16 +48,18 @@ longpress:用户在相同位置长时间保持与屏幕接触。 ```css /* xxx.css */ .container { + width: 100%; + height: 100%; flex-direction: column; justify-content: center; align-items: center; } .text-container { - margin-top: 10px; + margin-top: 30px; flex-direction: column; - width: 750px; - height: 50px; - background-color: #09ba07; + width: 600px; + height: 70px; + background-color: #0000FF; } .text-style { width: 100%; @@ -99,3 +101,5 @@ export default { }, } ``` + +![zh-cn_image_00000011](figures/zh-cn_image_00000011.gif) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-js-components-canvas.md b/zh-cn/application-dev/ui/ui-js-components-canvas.md index c46363421b6eddd6b9c6376feb171017c0f39126..9410a9d4ceda10a4fd7cb2169ca71afe7ec51a6c 100644 --- a/zh-cn/application-dev/ui/ui-js-components-canvas.md +++ b/zh-cn/application-dev/ui/ui-js-components-canvas.md @@ -118,8 +118,6 @@ import prompt from '@system.prompt'; export default { data:{ dataURL:null, - antialia: false, - porc:'open', }, onShow(){ let el = this.$refs.canvas1; diff --git a/zh-cn/application-dev/ui/ui-js-components-marquee.md b/zh-cn/application-dev/ui/ui-js-components-marquee.md index f711b61e755f78da710ee8d41f987845a4b78fe8..f755e9807c056a25788fb999e9826f9c80f8bf67 100644 --- a/zh-cn/application-dev/ui/ui-js-components-marquee.md +++ b/zh-cn/application-dev/ui/ui-js-components-marquee.md @@ -79,7 +79,7 @@ marquee通过color和font-weight属性设置跑马灯中文本的颜色、字体
- It's a racing lamp + Life is a journey, not the destination.
@@ -128,7 +128,9 @@ button{ // xxx.js export default { private: { - loopval: -1, scroll: 10, isleft: "left", + loopval: -1, + scroll: 10, + isleft: "left", }, onInit(){ }, @@ -163,7 +165,7 @@ export default {
- It's a racing lamp + Life is a journey, not the destination.
diff --git a/zh-cn/application-dev/ui/ui-js-components-search.md b/zh-cn/application-dev/ui/ui-js-components-search.md index 5c712126e14d8c24c396dd84808e4bdcae395564..85bd2730eec8c3f7a8391c608f9f42f179407ed4 100644 --- a/zh-cn/application-dev/ui/ui-js-components-search.md +++ b/zh-cn/application-dev/ui/ui-js-components-search.md @@ -62,7 +62,7 @@ ## 添加样式 -通过color、placeholder和caret-color样式来设置搜索框的文本颜色、提示文本颜色和光标颜色。 +通过color、placeholder-color和caret-color样式来设置搜索框的文本颜色、提示文本颜色和光标颜色。 ```html @@ -84,7 +84,9 @@ background-color: #F1F3F5; } search{ - color: black; placeholder-color: black; caret-color: red; + color: black; + placeholder-color: black; + caret-color: red; } ``` diff --git a/zh-cn/application-dev/ui/ui-ts-building-data-model.md b/zh-cn/application-dev/ui/ui-ts-building-data-model.md index fe8843dd0050a63c369cfb2b4bb92c518b28e9a7..b0627fe491d6207825bf775dcc9a95d1c50c9d12 100644 --- a/zh-cn/application-dev/ui/ui-ts-building-data-model.md +++ b/zh-cn/application-dev/ui/ui-ts-building-data-model.md @@ -11,7 +11,7 @@ ![zh-cn_image_0000001195119619](figures/zh-cn_image_0000001195119619.png) 2. 定义食物数据的存储模型FoodData和枚举变量Category,FoodData类包含食物id、名称(name)、分类(category)、图片(image)、热量(calories)、蛋白质(protein)、脂肪(fat)、碳水(carbohydrates)和维生素C(vitaminC)属性。 - eTS语言是在ts语言的基础上的扩展,同样支持ts语法。 + ArkTS语言是在ts语言的基础上的扩展,同样支持ts语法。 ``` enum Category { @@ -87,4 +87,4 @@ ## 相关实例 针对构建食物分类列表页面和食物详情页,有以下相关实例可供参考: -- [DefiningPageLayoutAndConnection:页面布局和连接(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/DefiningPageLayoutAndConnection) +- [DefiningPageLayoutAndConnection:页面布局和连接(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/DefiningPageLayoutAndConnection) diff --git a/zh-cn/application-dev/ui/ui-ts-components-web.md b/zh-cn/application-dev/ui/ui-ts-components-web.md index 6a72cc647601e6f072b59a61b58805df0d16c0b8..6f4acc31caca52b4bab2e97e9913922dd86904fa 100644 --- a/zh-cn/application-dev/ui/ui-ts-components-web.md +++ b/zh-cn/application-dev/ui/ui-ts-components-web.md @@ -198,6 +198,6 @@ struct WebComponent { 针对Web开发,有以下相关实例可供参考: -- [`Web`:Web(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Web) +- [`Web`:Web(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Web) -- [Web组件加载本地H5小程序(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebComponent) \ No newline at end of file +- [Web组件加载本地H5小程序(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebComponent) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md index a58772dcd84f01f7d4e52c8bd7a7a2e9430e4727..18152fe84e1c3ff337bd9db0b41ce9c3359adcfa 100644 --- a/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md +++ b/zh-cn/application-dev/ui/ui-ts-creating-simple-page.md @@ -445,7 +445,7 @@ 5. 使用自定义构造函数\@Builder简化代码。可以发现,每个成分表中的成分单元其实都是一样的UI结构。 ![zh-cn_image_0000001169599582](figures/zh-cn_image_0000001169599582.png) - 当前对每个成分单元都进行了声明,造成了代码的重复和冗余。可以使用\@Builder来构建自定义方法,抽象出相同的UI结构声明。\@Builder修饰的方法和Component的build方法都是为了声明一些UI渲染结构,遵循一样的eTS语法。开发者可以定义一个或者多个\@Builder修饰的方法,但Component的build方法必须只有一个。 + 当前对每个成分单元都进行了声明,造成了代码的重复和冗余。可以使用\@Builder来构建自定义方法,抽象出相同的UI结构声明。\@Builder修饰的方法和Component的build方法都是为了声明一些UI渲染结构,遵循一样的ArkTS语法。开发者可以定义一个或者多个\@Builder修饰的方法,但Component的build方法必须只有一个。 在ContentTable内声明\@Builder修饰的IngredientItem方法,用于声明分类名、成分名称和成分含量UI描述。 @@ -551,6 +551,6 @@ 针对创建简单视图,有以下示例工程可供参考: -- [`BuildCommonView`:创建简单视图(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/BuildCommonView) +- [`BuildCommonView`:创建简单视图(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/BuildCommonView) 本示例为构建了简单页面展示食物番茄的图片和营养信息,主要为了展示简单页面的Stack布局和Flex布局。 diff --git a/zh-cn/application-dev/ui/ui-ts-layout-flex.md b/zh-cn/application-dev/ui/ui-ts-layout-flex.md index 2fe5474f2ac9a6ebee04cb63cb4ebe0311112758..16479a4c171c4459bebb61ca67e9ca9058a80c19 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-flex.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-flex.md @@ -374,6 +374,6 @@ struct FlexExample { 针对弹性布局开发,有以下相关实例可供参考: -- [弹性布局(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/FlowLayoutEts) +- [弹性布局(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/FlowLayoutEts) -- [ArkUI常用布局容器对齐方式(eTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/LayoutAlignmentDemo) +- [ArkUI常用布局容器对齐方式(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/LayoutAlignmentDemo) diff --git a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md index f6159c9d12c3b8a25232ef70b2a2339c6bba41a5..27147d07fe719c98db76dd1a6ff57e3569a4faa6 100644 --- a/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md +++ b/zh-cn/application-dev/ui/ui-ts-layout-mediaquery.md @@ -154,5 +154,5 @@ listener.on('change', onPortrait) 针对媒体查询开发,有以下相关实例可供参考: -- [`MediaQuery`:媒体查询(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MediaQuery) +- [`MediaQuery`:媒体查询(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MediaQuery) diff --git a/zh-cn/application-dev/ui/ui-ts-overview.md b/zh-cn/application-dev/ui/ui-ts-overview.md index e14132c51fc147d8f1844070ae9887de52986b6b..348ce1cde17b33f3a6bb7fe393e74427f6852a63 100644 --- a/zh-cn/application-dev/ui/ui-ts-overview.md +++ b/zh-cn/application-dev/ui/ui-ts-overview.md @@ -1,13 +1,13 @@ # 概述 -基于eTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、跨设备应用的UI开发框架,支持开发者高效的构建跨设备应用UI界面。 +基于ArkTS的声明式开发范式的方舟开发框架是一套开发极简、高性能、跨设备应用的UI开发框架,支持开发者高效的构建跨设备应用UI界面。 ## 基础能力 -使用基于eTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动效和状态管理三个维度来提供UI能力,还提供了系统能力接口,实现系统能力的极简调用。 +使用基于ArkTS的声明式开发范式的方舟开发框架,采用更接近自然语义的编程方式,让开发者可以直观地描述UI界面,不必关心框架如何实现UI绘制和渲染,实现极简高效开发。开发框架不仅从组件、动效和状态管理三个维度来提供UI能力,还提供了系统能力接口,实现系统能力的极简调用。 -请参考[基于eTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解组件,更好地开发应用。 +请参考[基于ArkTS的声明式开发范式API](../reference/arkui-ts/ts-universal-events-click.md)文档,全面地了解组件,更好地开发应用。 - **开箱即用的组件** @@ -22,12 +22,12 @@ - **状态与数据管理** - 状态数据管理作为基于eTS的声明式开发范式的特色,通过功能不同的装饰器给开发者提供了清晰的页面更新渲染流程和管道。状态管理包括UI组件状态和应用程序状态,两者协作可以使开发者完整地构建整个应用的数据更新和UI渲染。 + 状态数据管理作为基于ArkTS的声明式开发范式的特色,通过功能不同的装饰器给开发者提供了清晰的页面更新渲染流程和管道。状态管理包括UI组件状态和应用程序状态,两者协作可以使开发者完整地构建整个应用的数据更新和UI渲染。 - **系统能力接口** - 使用基于eTS的声明式开发范式的方舟开发框架,还封装了丰富的系统能力接口,开发者可以通过简单的接口调用,实现从UI设计到系统能力调用的极简开发。 + 使用基于ArkTS的声明式开发范式的方舟开发框架,还封装了丰富的系统能力接口,开发者可以通过简单的接口调用,实现从UI设计到系统能力调用的极简开发。 ## 整体架构 @@ -59,54 +59,54 @@ ## 相关实例 -基于eTS的声明式开发范式的方舟开发框架,有以下相关实例可供参考: +基于ArkTS的声明式开发范式的方舟开发框架,有以下相关实例可供参考: -- [`Canvas`:画布组件(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Canvas) +- [`Canvas`:画布组件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Canvas) -- [`Drag`:拖拽事件(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Drag) +- [`Drag`:拖拽事件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Drag) -- [`ArkUIAnimation`:动画(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/ArkUIAnimation) +- [`ArkUIAnimation`:动画(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/ArkUIAnimation) -- [`Xcomponent`:XComponent(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/XComponent) +- [`Xcomponent`:XComponent(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/XComponent) -- [`MouseEvent`:鼠标事件(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) +- [`MouseEvent`:鼠标事件(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/MouseEvent) -- [`Gallery`:组件集合(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) +- [`Gallery`:组件集合(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Gallery) -- [`BringApp`:拉起系统应用(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/BringApp) +- [`BringApp`:拉起系统应用(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/BringApp) -- [`Chat`:聊天示例应用(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/AppSample/Chat) +- [`Chat`:聊天示例应用(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/AppSample/Chat) -- [`Shopping`:购物示例应用(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/AppSample/Shopping) +- [`Shopping`:购物示例应用(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/AppSample/Shopping) -- [`Lottie`:Lottie(eTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Lottie) +- [`Lottie`:Lottie(ArkTS)(API8)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Lottie) -- [`Clock`:简单时钟(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) +- [`Clock`:简单时钟(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Preset/Clock) -- [`Flybird`:小鸟避障游戏(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/Flybird) +- [`Flybird`:小鸟避障游戏(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ResourcesSchedule/Flybird) -- [`AdaptiveCapabilities`:多设备自适应能力(eTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities) +- [`AdaptiveCapabilities`:多设备自适应能力(ArkTS)(API9)](https://gitee.com/openharmony/app_samples/tree/master/MultiDeviceAppDev/AdaptiveCapabilities) -- [`Game2048`:2048游戏(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Game2048) +- [`Game2048`:2048游戏(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Game2048) -- [`TransitionAnimation`:转场动画(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/TransitionAnimation) +- [`TransitionAnimation`:转场动画(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/TransitionAnimation) -- [`PatternLock`:图案密码锁组件(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/PatternLock) +- [`PatternLock`:图案密码锁组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/PatternLock) -- [`Search`:Search组件(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Search) +- [`Search`:Search组件(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/Search) -- [`QRCode`:二维码(eTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/QRCode) +- [`QRCode`:二维码(ArkTS)(API9)(Full SDK)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/QRCode) -- [极简声明式UI范式(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts) +- [极简声明式UI范式(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SimpleGalleryEts) -- [购物应用(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts) +- [购物应用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/ShoppingEts) -- [转场动画的使用(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimtaionEts) +- [转场动画的使用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/TransitionAnimtaionEts) -- [基础组件Slider的使用(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderApplicationEts) +- [基础组件Slider的使用(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/SliderApplicationEts) -- [弹窗(eTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts) +- [弹窗(ArkTS)(API8)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/CustomDialogEts) -- [`UpgradePopup`:自定义弹窗(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/UpgradePopup) +- [`UpgradePopup`:自定义弹窗(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/UpgradePopup) -- [CustomComponent:组件化(eTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/CustomComponent) \ No newline at end of file +- [CustomComponent:组件化(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/ETSUI/CustomComponent) \ No newline at end of file diff --git a/zh-cn/application-dev/ui/ui-ts-page-redirection-data-transmission.md b/zh-cn/application-dev/ui/ui-ts-page-redirection-data-transmission.md index 4c55c3a16abd697931b08fe0eb6589cdabeb74f5..493f5f60fa0c53a26a34673afa4ee7d7d29f26c3 100644 --- a/zh-cn/application-dev/ui/ui-ts-page-redirection-data-transmission.md +++ b/zh-cn/application-dev/ui/ui-ts-page-redirection-data-transmission.md @@ -267,6 +267,6 @@ 针对页面布局与连接,有以下示例工程可供参考: -- [`DefiningPageLayoutAndConnection`:页面布局和连接(eTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/DefiningPageLayoutAndConnection) +- [`DefiningPageLayoutAndConnection`:页面布局和连接(ArkTS)(API8)](https://gitee.com/openharmony/app_samples/tree/master/ETSUI/DefiningPageLayoutAndConnection) 本示例构建了食物分类列表页面和食物详情页,向开发者展示了List布局、Grid布局以及页面路由的基本用法。 diff --git a/zh-cn/application-dev/windowmanager/application-window-stage.md b/zh-cn/application-dev/windowmanager/application-window-stage.md index 661d379df7f0e29626aab080c37eeb092a68a67a..51b969f34e611a7a23ee8f115389590737b11a11 100644 --- a/zh-cn/application-dev/windowmanager/application-window-stage.md +++ b/zh-cn/application-dev/windowmanager/application-window-stage.md @@ -396,4 +396,4 @@ class MainAbility extends Ability { 针对window开发(Stage模型),有以下相关实例可供参考: -- [`Window`:窗口(eTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/Window) \ No newline at end of file +- [`Window`:窗口(ArkTS)(API9)](https://gitee.com/openharmony/applications_app_samples/tree/master/Graphics/Window) \ No newline at end of file diff --git a/zh-cn/device-dev/driver/driver-peripherals-usb-des.md b/zh-cn/device-dev/driver/driver-peripherals-usb-des.md index bdb313049f79ebdcb397c7668b35cff66ecaa9cb..c7dc8513b9e69d1dc158868e95350200c7952c6c 100644 --- a/zh-cn/device-dev/driver/driver-peripherals-usb-des.md +++ b/zh-cn/device-dev/driver/driver-peripherals-usb-des.md @@ -36,51 +36,51 @@ USB驱动模型Host侧开放的API接口功能,参考USB Host驱动模型图 | int32_t UsbInitHostSdk(struct UsbSession \*\*session); | USB主机端驱动开发工具包初始化 | | int32_t UsbExitHostSdk(const struct UsbSession
\*session); | USB主机端驱动开发工具包退出 | | const struct UsbInterface \*UsbClaimInterface(const
struct UsbSession \*session, uint8_t busNum, uint8_t
usbAddr, uint8_t interfaceIndex); | 获取USB接口对象 | -| int UsbReleaseInterface(const struct UsbInterface
\*interfaceObj); | 释放USB接口对象 | -| int UsbAddOrRemoveInterface(const struct UsbSession
\*session, uint8_t busNum, uint8_t usbAddr, uint8_t
interfaceIndex, UsbInterfaceStatus status); | 增加移除接口 | +| int32_t UsbReleaseInterface(const struct UsbInterface
\*interfaceObj); | 释放USB接口对象 | +| int32_t UsbAddOrRemoveInterface(const struct UsbSession
\*session, uint8_t busNum, uint8_t usbAddr, uint8_t
interfaceIndex, UsbInterfaceStatus status); | 增加移除接口 | | UsbInterfaceHandle \*UsbOpenInterface(const struct
UsbInterface \*interfaceObj); | 打开USB对象接口 | | int32_t UsbCloseInterface(const UsbInterfaceHandle
\*interfaceHandle); | 关闭USB接口对象 | | int32_t UsbSelectInterfaceSetting(const
UsbInterfaceHandle \*interfaceHandle, uint8_t
settingIndex, struct UsbInterface \*\*interfaceObj); | 设置可选配置 | | int32_t UsbGetPipeInfo(const UsbInterfaceHandle
\*interfaceHandle, uint8_t settingIndex, uint8_t pipeId,
struct UsbPipeInfo \*pipeInfo); | 获取指定可选设置的管道信息 | | int32_t UsbClearInterfaceHalt(const
UsbInterfaceHandle \*interfaceHandle, uint8_t
pipeAddress); | 清除指定索引的管道状态 | -| struct UsbRequest \*UsbAllocRequest(const
UsbInterfaceHandle \*interfaceHandle, int isoPackets
, int length); | 分配请求对象 | -| int UsbFreeRequest(const struct UsbRequest
\*request); | 释放请求对象 | -| int UsbSubmitRequestAsync(const struct UsbRequest
\*request); | 发送异步请求 | +| struct UsbRequest \*UsbAllocRequest(const
UsbInterfaceHandle \*interfaceHandle, int32_t isoPackets
, int32_t length); | 分配请求对象 | +| int32_t UsbFreeRequest(const struct UsbRequest
\*request); | 释放请求对象 | +| int32_t UsbSubmitRequestAsync(const struct UsbRequest
\*request); | 发送异步请求 | | int32_t UsbFillRequest(const struct UsbRequest
\*request, const UsbInterfaceHandle \*interfaceHandle,
const struct UsbRequestParams \*params); | 填充请求 | -| sint UsbCancelRequest(const struct UsbRequest
\*request); | 取消异步请求 | -| int UsbSubmitRequestSync(const struct UsbRequest
\*request); | 发送同步请求 | +| int32_t UsbCancelRequest(const struct UsbRequest
\*request); | 取消异步请求 | +| int32_t UsbSubmitRequestSync(const struct UsbRequest
\*request); | 发送同步请求 | **表2** usb_raw_api.h | 接口名称 | 功能描述 | | -------- | -------- | -| int UsbRawInit(struct UsbSession \*\*session); | USB驱动开发工具包专家模式初始化 | -| int UsbRawExit(const struct UsbSession \*session); | USB驱动开发工具包专家模式退出 | +| int32_t UsbRawInit(struct UsbSession \*\*session); | USB驱动开发工具包专家模式初始化 | +| int32_t UsbRawExit(const struct UsbSession \*session); | USB驱动开发工具包专家模式退出 | | UsbRawHandle \*UsbRawOpenDevice(const struct
UsbSession \*session, uint8_t busNum, uint8_t
usbAddr); | 打开USB设备对象 | -| int UsbRawCloseDevice(const UsbRawHandle
\*devHandle); | 关闭USB设备对象 | -| int UsbRawSendControlRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbControlRequestData
\*requestData); | 执行同步控制传输 | -| int UsbRawSendBulkRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步批量传输 | -| int UsbRawSendInterruptRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步中断传输 | -| int UsbRawGetConfigDescriptor(const UsbRawDevice
\*rawDev, uint8_t configIndex, struct
UsbRawConfigDescriptor \*\*config); | 获取给定设备指定ID的设备配置描述符 | +| int32_t UsbRawCloseDevice(const UsbRawHandle
\*devHandle); | 关闭USB设备对象 | +| int32_t UsbRawSendControlRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbControlRequestData
\*requestData); | 执行同步控制传输 | +| int32_t UsbRawSendBulkRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步批量传输 | +| int32_t UsbRawSendInterruptRequest(const struct
UsbRawRequest \*request, const UsbRawHandle
\*devHandle, const struct UsbRequestData
\*requestData); | 执行同步中断传输 | +| int32_t UsbRawGetConfigDescriptor(const UsbRawDevice
\*rawDev, uint8_t configIndex, struct
UsbRawConfigDescriptor \*\*config); | 获取给定设备指定ID的设备配置描述符 | | void UsbRawFreeConfigDescriptor(const struct
UsbRawConfigDescriptor \*config); | 释放配置描述符内存空间 | -| int UsbRawGetConfiguration(const UsbRawHandle
\*devHandle, int \*config); | 获取当前激活配置 | -| int UsbRawSetConfiguration(const UsbRawHandle
\*devHandle, int config); | 设置当前激活配置 | -| int UsbRawGetDescriptor(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawDescriptorParam \*param, const unsigned char
\*data); | 获取描述符信息 | +| int32_t UsbRawGetConfiguration(const UsbRawHandle
\*devHandle, int32_t \*config); | 获取当前激活配置 | +| int32_t UsbRawSetConfiguration(const UsbRawHandle
\*devHandle, int32_t config); | 设置当前激活配置 | +| int32_t UsbRawGetDescriptor(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawDescriptorParam \*param, const unsigned char
\*data); | 获取描述符信息 | | UsbRawDevice \*UsbRawGetDevice(const UsbRawHandle
\*devHandle); | 由设备句柄获取设备指针 | -| int UsbRawGetDeviceDescriptor(const UsbRawDevice
\*rawDev, struct
UsbDeviceDescriptor \*desc); | 获取给定设备的USB设备描述符 | -| int UsbRawClaimInterface(const UsbRawHandle
\*devHandle, int
interfaceNumber); | 声明给定设备句柄上的接口 | -| int UsbRawReleaseInterface(const UsbRawHandle
\*devHandle, in
t interfaceNumber); | 释放之前声明的接口 | -| int UsbRawResetDevice(const UsbRawHandle
\*devHandle); | 复位设备 | -| struct UsbRawRequest \*UsbRawAllocRequest(const
UsbRawHandle
\*devHandle, int isoPackets, int length); | 分配一个带有指定数量的同步包描述符的传输请求 | -| int UsbRawFreeRequest(const struct UsbRawRequest
\*request); | 释放之前分配的传输请求 | -| int UsbRawFillBulkRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充批量传输请求所需信息 | -| int UsbRawFillControlSetup(const unsigned char \*setup,
const struct UsbControlRequestData \*requestData); | 填充控制传输设置包所需信息 | -| int UsbRawFillControlRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充控制传输请求所需信息 | -| int UsbRawFillInterruptRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充中断传输请求所需信息 | -| int UsbRawFillIsoRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充同步传输(Isochronous Transfers)请求所需信息 | -| int UsbRawSubmitRequest(const struct UsbRawRequest
\*request); | 提交一个传输请求 | -| int UsbRawCancelRequest(const struct UsbRawRequest
\*request); | 取消一个传输请求 | -| int UsbRawHandleRequests(const UsbRawHandle
\*devHandle); | 传输请求事件完成处理 | +| int32_t UsbRawGetDeviceDescriptor(const UsbRawDevice
\*rawDev, struct
UsbDeviceDescriptor \*desc); | 获取给定设备的USB设备描述符 | +| int32_t UsbRawClaimInterface(const UsbRawHandle
\*devHandle, int32_t
interfaceNumber); | 声明给定设备句柄上的接口 | +| int32_t UsbRawReleaseInterface(const UsbRawHandle
\*devHandle, in
t interfaceNumber); | 释放之前声明的接口 | +| int32_t UsbRawResetDevice(const UsbRawHandle
\*devHandle); | 复位设备 | +| struct UsbRawRequest \*UsbRawAllocRequest(const
UsbRawHandle
\*devHandle, int32_t isoPackets, int32_t length); | 分配一个带有指定数量的同步包描述符的传输请求 | +| int32_t UsbRawFreeRequest(const struct UsbRawRequest
\*request); | 释放之前分配的传输请求 | +| int32_t UsbRawFillBulkRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充批量传输请求所需信息 | +| int32_t UsbRawFillControlSetup(const unsigned char \*setup,
const struct UsbControlRequestData \*requestData); | 填充控制传输设置包所需信息 | +| int32_t UsbRawFillControlRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充控制传输请求所需信息 | +| int32_t UsbRawFillInterruptRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充中断传输请求所需信息 | +| int32_t UsbRawFillIsoRequest(const struct UsbRawRequest
\*request, const UsbRawHandle \*devHandle, const struct
UsbRawFillRequestData \*fillData); | 填充同步传输(Isochronous Transfers)请求所需信息 | +| int32_t UsbRawSubmitRequest(const struct UsbRawRequest
\*request); | 提交一个传输请求 | +| int32_t UsbRawCancelRequest(const struct UsbRawRequest
\*request); | 取消一个传输请求 | +| int32_t UsbRawHandleRequests(const UsbRawHandle
\*devHandle); | 传输请求事件完成处理 | USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型图。 @@ -89,19 +89,19 @@ USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型 | 接口名称 | 功能描述 | | -------- | -------- | | const struct UsbFnDevice \*UsbFnCreateDevice(const
char \*udcName, const struct UsbFnDescriptorData
\*descriptor); | 创建USB设备 | -| int UsbFnRemoveDevice(struct UsbFnDevice
\*fnDevice); | 删除USB设备 | +| int32_t UsbFnRemoveDevice(struct UsbFnDevice
\*fnDevice); | 删除USB设备 | | const struct UsbFnDevice \*UsbFnGetDevice(const char
\*udcName); | 获取USB设备 | **表4** usbfn_interface.h | 接口名称 | 功能描述 | | -------- | -------- | -| int UsbFnStartRecvInterfaceEvent(struct
UsbFnInterface \*interface, uint32_t eventMask,
UsbFnEventCallback callback, void \*context); | 开始接受Event事件 | -| int UsbFnStopRecvInterfaceEvent(struct
UsbFnInterface \*interface); | 停止接受Event事件 | +| int32_t UsbFnStartRecvInterfaceEvent(struct
UsbFnInterface \*interface, uint32_t eventMask,
UsbFnEventCallback callback, void \*context); | 开始接受Event事件 | +| int32_t UsbFnStopRecvInterfaceEvent(struct
UsbFnInterface \*interface); | 停止接受Event事件 | | UsbFnInterfaceHandle UsbFnOpenInterface(struct UsbFnInterface \*interface); | 打开一个接口 | -| int UsbFnCloseInterface(UsbFnInterfaceHandle handle); | 关闭一个接口 | -| int UsbFnGetInterfacePipeInfo(struct UsbFnInterface
\*interface, uint8_t pipeId, struct UsbFnPipeInfo \*info); | 获取管道信息 | -| int UsbFnSetInterfaceProp(const struct UsbFnInterface
\*interface, const char \*name, const char \*value); | 设置自定义属性 | +| int32_t UsbFnCloseInterface(UsbFnInterfaceHandle handle); | 关闭一个接口 | +| int32_t UsbFnGetInterfacePipeInfo(struct UsbFnInterface
\*interface, uint8_t pipeId, struct UsbFnPipeInfo \*info); | 获取管道信息 | +| int32_t UsbFnSetInterfaceProp(const struct UsbFnInterface
\*interface, const char \*name, const char \*value); | 设置自定义属性 | **表5** usbfn_request.h @@ -109,10 +109,10 @@ USB驱动模型Device侧开放的API接口功能,参考USB Device驱动模型 | -------- | -------- | | struct UsbFnRequest
\*UsbFnAllocCtrlRequest(UsbFnInterfaceHandle handle,
uint32_t len); | 申请一个控制请求 | | struct UsbFnRequest \*UsbFnAllocRequest(UsbFnInterfaceHandle handle,
uint8_t pipe, uint32_t len); | 申请一个数据请求 | -| int UsbFnFreeRequest(struct UsbFnRequest \*req); | 释放一个请求 | -| int UsbFnSubmitRequestAsync(struct UsbFnRequest
\*req); | 发送异步请求 | -| int UsbFnSubmitRequestSync(struct UsbFnRequest
\*req, uint32_t timeout); | 发送同步请求 | -| int UsbFnCancelRequest(struct UsbFnRequest \*req); | 取消请求 | +| int32_t UsbFnFreeRequest(struct UsbFnRequest \*req); | 释放一个请求 | +| int32_t UsbFnSubmitRequestAsync(struct UsbFnRequest
\*req); | 发送异步请求 | +| int32_t UsbFnSubmitRequestSync(struct UsbFnRequest
\*req, uint32_t timeout); | 发送同步请求 | +| int32_t UsbFnCancelRequest(struct UsbFnRequest \*req); | 取消请求 | ## 开发步骤 @@ -218,6 +218,9 @@ root { } } } +``` + +```cpp #include "usb_serial.h" #include "hdf_base.h" @@ -236,10 +239,10 @@ static struct UsbRequest *g_ctrlCmdRequest = NULL; static bool g_acmReleaseFlag = false; static uint8_t *g_acmReadBuffer = NULL; ... -static int SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, +static int32_t SerialCtrlMsg(struct AcmDevice *acm, uint8_t request, uint16_t value, void *buf, uint16_t len) { - int ret; + int32_t ret; uint16_t index = acm->intPipe->interfaceId; struct UsbControlParams controlParams; struct UsbRequestParams params; @@ -299,7 +302,7 @@ static struct UsbPipeInfo *EnumePipe(const struct AcmDevice *acm, uint8_t interfaceIndex, UsbPipeType pipeType, UsbPipeDirection pipeDirection) { uint8_t i; - int ret; + int32_t ret; struct UsbInterfaceInfo *info = NULL; UsbInterfaceHandle *interfaceHandle = NULL; if (pipeType == USB_PIPE_TYPE_CONTROL) @@ -408,11 +411,11 @@ error: return HDF_FAILURE; } ... -static int AcmAllocReadRequests(struct AcmDevice *acm) +static int32_t AcmAllocReadRequests(struct AcmDevice *acm) { - int ret; + int32_t ret; struct UsbRequestParams readParams; - for (int i = 0; i < ACM_NR; i++) { + for (int32_t i = 0; i < ACM_NR; i++) { acm->readReq[i] = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataInPipe->interfaceId), 0, acm->readSize); // 分配待发送的readReq IO Request对象 if (!acm->readReq[i]) { HDF_LOGE("readReq request failed"); @@ -441,9 +444,9 @@ error: return HDF_ERR_MALLOC_FAIL; } -static int AcmAllocNotifyRequest(struct AcmDevice *acm) +static int32_t AcmAllocNotifyRequest(struct AcmDevice *acm) { - int ret; + int32_t ret; struct UsbRequestParams intParams = {}; acm->notifyReq = UsbAllocRequest(InterfaceIdToHandle(acm, acm->intPipe->interfaceId), 0, acm->intSize); // 分配待发送的中断IO Request对象 if (!acm->notifyReq) { @@ -474,7 +477,7 @@ error: static void AcmReleaseInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->iface[i]) { UsbReleaseInterface(acm->iface[i]); acm->iface[i] = NULL; @@ -488,7 +491,7 @@ static void AcmReleaseInterfaces(struct AcmDevice *acm) static int32_t AcmClaimInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { acm->iface[i] = GetUsbInterfaceById((const struct AcmDevice *)acm, acm->interfaceIndex[i]); // 获取UsbInterface接口对象 if (acm->iface[i] == NULL) { HDF_LOGE("%s: interface%d is null", __func__, acm->interfaceIndex[i]); @@ -511,7 +514,7 @@ static int32_t AcmClaimInterfaces(struct AcmDevice *acm) static void AcmCloseInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->devHandle[i]) { UsbCloseInterface(acm->devHandle[i]); acm->devHandle[i] = NULL; @@ -525,7 +528,7 @@ static void AcmCloseInterfaces(struct AcmDevice *acm) static int32_t AcmOpenInterfaces(struct AcmDevice *acm) { - for (int i = 0; i < acm->interfaceCnt; i++) { + for (int32_t i = 0; i < acm->interfaceCnt; i++) { if (acm->iface[i]) { acm->devHandle[i] = UsbOpenInterface(acm->iface[i]); // 打开获取到的UsbInterface接口对象 if (acm->devHandle[i] == NULL) { @@ -606,7 +609,7 @@ static int32_t AcmAllocRequests(struct AcmDevice *acm) return HDF_ERR_MALLOC_FAIL; } - for (int i = 0; i < ACM_NW; i++) { + for (int32_t i = 0; i < ACM_NW; i++) { struct AcmWb *snd = &(acm->wb[i]); snd->request = UsbAllocRequest(InterfaceIdToHandle(acm, acm->dataOutPipe->interfaceId), 0, acm->writeSize); //分配待发送的IO Request对象 snd->instance = acm; @@ -789,7 +792,7 @@ HDF_INIT(g_usbSerialDriverEntry); ### Host RAW API驱动开发 -``` +```cpp root { module = "usb_pnp_device"; usb_pnp_config { @@ -836,7 +839,9 @@ root { } } } +``` +```cpp #include "usb_serial_rawapi.h" #include #include "osal_mem.h" @@ -858,11 +863,11 @@ struct OsalMutex g_stopIoLock; static bool g_rawAcmReleaseFlag = false; ...... -static int UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDescriptor **config) +static int32_t UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDescriptor **config) { UsbRawDevice *dev = NULL; - int activeConfig; - int ret; + int32_t activeConfig; + int32_t ret; if (devHandle == NULL) { HDF_LOGE("%s:%d devHandle is NULL", @@ -893,9 +898,9 @@ static int UsbGetConfigDescriptor(UsbRawHandle *devHandle, struct UsbRawConfigDe return HDF_SUCCESS; } ... -static int UsbAllocWriteRequests(struct AcmDevice *acm) +static int32_t UsbAllocWriteRequests(struct AcmDevice *acm) { - int i; + int32_t i; for (i = 0; i < ACM_NW; i++) { struct AcmWb *snd = &acm->wb[i]; @@ -965,13 +970,13 @@ error: return HDF_FAILURE; } ... -static int UsbAllocReadRequests(struct AcmDevice *acm) +static int32_t UsbAllocReadRequests(struct AcmDevice *acm) { struct UsbRawFillRequestData reqData; - int size = acm->dataInEp->maxPacketSize; - int ret; + int32_t size = acm->dataInEp->maxPacketSize; + int32_t ret; - for (int i = 0; i < ACM_NR; i++) { + for (int32_t i = 0; i < ACM_NR; i++) { acm->readReq[i] = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->readReq[i]) { HDF_LOGE("readReq request failed"); @@ -996,11 +1001,11 @@ static int UsbAllocReadRequests(struct AcmDevice *acm) return HDF_SUCCESS; } ... -static int UsbAllocNotifyRequest(struct AcmDevice *acm) +static int32_t UsbAllocNotifyRequest(struct AcmDevice *acm) { struct UsbRawFillRequestData fillRequestData; - int size = acm->notifyEp->maxPacketSize; - int ret; + int32_t size = acm->notifyEp->maxPacketSize; + int32_t ret; acm->notifyReq = UsbRawAllocRequest(acm->devHandle, 0, size); if (!acm->notifyReq) { @@ -1226,9 +1231,8 @@ HDF_INIT(g_usbSerialRawDriverEntry); USB ACM设备核心代码路径为drivers\peripheral\usb\gadget\function\acm\cdcacm.c。其使用示例如下所示,首先根据描述符创建设备,然后获取接口,打开接口,获取Pipe信息,接收Event事件,接着进行USB通信(读写等),设备卸载时候,关闭接口,停止Event接收,删除设备。 - -``` 1、创建设备 +```cpp static int32_t AcmCreateFuncDevice(struct UsbAcmDevice *acm, struct DeviceResourceIface *iface) { @@ -1251,7 +1255,9 @@ if (useHcs == 0) { } ... } +``` 2、获取接口,打开接口,获取Pipe信息 +```cpp static int32_t AcmParseEachPipe(struct UsbAcmDevice *acm, struct UsbAcmInterface *iface) { ... @@ -1277,8 +1283,11 @@ static int32_t AcmParseEachIface(struct UsbAcmDevice *acm, struct UsbFnDevice *f } return HDF_SUCCESS; } +``` + 3、接收Event事件 -static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int num) +```cpp +static int32_t AcmAllocCtrlRequests(struct UsbAcmDevice *acm, int32_t num) { ... req = UsbFnCtrlRequestAlloc(acm->ctrlIface.handle, @@ -1292,7 +1301,9 @@ static int32_t AcmDriverInit(struct HdfDeviceObject *device) ret = UsbFnInterfaceStartRecvEvent(acm->ctrlIface.fn, 0xff, UsbAcmEventCallback, acm); ... } +``` 4、进行USB通信(读写等) +```cpp static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type, uint16_t value, void *data, uint32_t length) { @@ -1301,7 +1312,9 @@ static int32_t AcmSendNotifyRequest(struct UsbAcmDevice *acm, uint8_t type, ret = UsbFnRequestSubmitAsync(req); ... } +``` 5、关闭接口,停止Event接收,删除设备 +```cpp static int32_t AcmReleaseFuncDevice(struct UsbAcmDevice *acm) { int32_t ret; diff --git a/zh-cn/device-dev/faqs/faqs-startup.md b/zh-cn/device-dev/faqs/faqs-startup.md index 9db1d8a011326bf14d1a272f5703656899f0b3d7..d1c02d9d674dc1a9202a1bbca80bca265cf1a614 100644 --- a/zh-cn/device-dev/faqs/faqs-startup.md +++ b/zh-cn/device-dev/faqs/faqs-startup.md @@ -191,6 +191,42 @@ OpenHarmony-3.0-LTS 设备进入hdc shell下, 执行sandbox -s service_name命令,模拟当前服务进入沙盒场景, 通过 ls 等shell命令查看当前服务沙盒目录。具体参考[沙盒命令](../subsystems/subsys-boot-init-plugin.md) +### Bootevent部分事件的ready阶段的时间戳为0 + +**现象描述** + +Bootevent手动模式下,开机完成之后在执行dump_service all bootevent命令后有部分事件的ready阶段的时间戳为0。 + +**可能原因** + +1. 服务没有发送bootevent事件。 +2. 服务发送bootevent事件, 但是没有相关权限。 + +**解决方法** + +1. 服务配置了bootevent,但是没有发送该bootevent事件,请相关服务在代码中发送该bootevent事件。 +2. 在代码中已经执行到设置bootevent的操作,但是ready的状态就是为零,此时请检查服务是否有设置bootevent参数的权限。 + +### A/B分区启动过程因只烧写原始分区导致的无法启动 + +**现象描述** + +烧写完成后系统无法正常启动,并且可以在串口日志中找到类似如下打印: + +``` +wait for file:/dev/block/platform/fe310000.sdhci/by-name/system_b failed after 5 second. +Mount /dev/block/platform/fe310000.sdhci/by-name/system_b to /usr failed 2 +``` + +**可能原因** + +当前系统已经支持了A/B分区启动,根据日志可知本次启动尝试挂载了带"_b"后缀的system分区,即本次启动从B分区启动,但是并没有找到设备,导致挂载失败。这种情况是由于当前misc分区中的active slot值被设置为了2(B分区),但是并没有烧写对应B分区导致的。 + +**解决方法** + +1. 可以清空misc分区(使用空misc镜像烧写对应分区),将其中的active slot值擦除,再次启动即可从默认分区启动。 +2. 使用配置了B分区的分区表将system_b和vendor_b镜像烧写到开发板中,再次启动即可从对应B分区正常启动。 + ## Appspawn应用孵化常见问题 ### 设备启动中,appspawn启动失败 @@ -221,11 +257,15 @@ OpenHarmony-3.0-LTS 1. 冷启动状态未打开。 2. 冷启动命令参数输入错误。 +3. socket请求超时。 +4. selinux打开。 **解决办法** -1. 冷启动不使能, 通过param get appspawn.cold.boot命令查看状态,如果冷启动状态是false, 通过param set appspawn.cold.boot true 命令打开冷启动状态。 +1. 冷启动不使能, 通过param get startup.appspawn.cold.boot命令查看状态,如果冷启动状态是0, 通过param set startup.appspawn.cold.boot 1 命令打开冷启动状态。 2. 冷启动命令参数不正确, 查看并确认冷启动参数。 +3. 设置超时时间>3秒,执行 param set persist.appspawn.client.timeout 5 命令。 +4. 关闭selinux, 执行 setenforce 0 命令。 ### 应用沙盒创建失败 diff --git a/zh-cn/device-dev/subsystems/Readme-CN.md b/zh-cn/device-dev/subsystems/Readme-CN.md index 3aca6a69afabb10c047aed0b228025b0f4c283b4..901db72406063e38d4675440075e1b915d050bc3 100644 --- a/zh-cn/device-dev/subsystems/Readme-CN.md +++ b/zh-cn/device-dev/subsystems/Readme-CN.md @@ -82,6 +82,8 @@ - [系统参数](subsys-boot-init-sysparam.md) - [沙盒管理](subsys-boot-init-sandbox.md) - [插件](subsys-boot-init-plugin.md) + - [组件化启动](subsys-boot-init-sub-unit.md) + - [init运行日志规范化](subsys-boot-init-log.md) - [appspawn应用孵化组件](subsys-boot-appspawn.md) - [bootstrap服务启动组件](subsys-boot-bootstrap.md) - [常见问题](subsys-boot-faqs.md) diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-log.md b/zh-cn/device-dev/subsystems/subsys-boot-init-log.md new file mode 100644 index 0000000000000000000000000000000000000000..f7e67b7d31bee1e67f7957ca9182d6748528e7dc --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-log.md @@ -0,0 +1,74 @@ +# init运行时日志规范化 +## 概述 +### 功能简介 +日志的基本功能就是记录init启动中的关键节点,以及定位故障问题。 +- 基于日志可以定位故障问题,可以查看各子系统启动时长,命令执行时长等。 +- 可以查看不同模块的日志tag,如param、uevent、module等。 +- 输出关键阶段日志,如第一阶段启动日志、required partition设备节点、uevent创建日志、服务启动日志等。 +- 日志等级可控,根据需要输出不同级别日志,目前日志级别分为INIT_DEBUG, +INIT_INFO,INIT_WARN,INIT_ERROR,INIT_FATAL。 + +### 基本概念 + +init日志根据OpenHarmony版本不同实现方式不同。 +- 对于OpenHarmony标准版本,init日志采用内核的dmesg log实现。 +- 对于OpenHarmony liteos L1版本init日志采用hilog接口实现。 +- 对于OpenHarmony liteos L0版本init日志采用printf接口实现。 + +### 约束与限制 +无 + +## 开发指导 +### 场景介绍 +init log主要应用在init的启动过程中,启动相关模块(param、ueventd、module等)中,以及对外提供的begetutils接口中。 + +### 接口说明 + +**表1** log接口说明 + | 接口 | 接口格式和示例 | 说明 | + | -------- | -------- | -------- | + | INIT_LOGV | INIT_LOGV("Add %s to job %s", service->name, jobName); | 输出debug log。 | + | INIT_LOGI | INIT_LOGI("Start init first stage."); | 输出info log。 | + | INIT_LOGW | INIT_LOGW("initialize signal handler failed"); | 输出warning log。 | + | INIT_LOGE | INIT_LOGE("Failed to format other opt"); | 输出err log。 | + | INIT_LOGF | INIT_LOGF("Failed to init system"); | 输出fatal log。 | + | INIT_ERROR_CHECK | INIT_ERROR_CHECK(ctx != NULL, return NULL, "Failed to get cmd args "); | 判断 ctx != NULL 不成立的情况下输出log,同时执行 return NULL。 | + | INIT_INFO_CHECK | INIT_INFO_CHECK(sockopt != NULL, return SERVICE_FAILURE, "Failed to malloc for service %s", service->name); | 判断 sockopt != NULL 不成立的情况下输出log,同时执行 return SERVICE_FAILURE。 | + | INIT_WARNING_CHECK | INIT_WARNING_CHECK(argsCount <= SPACES_CNT_IN_CMD_MAX, argsCount = SPACES_CNT_IN_CMD_MAX, "Too much arguments for command, max number is %d", SPACES_CNT_IN_CMD_MAX); | 判断 argsCount <= SPACES_CNT_IN_CMD_MAX 不成立的情况下输出log,同时执行 argsCount = SPACES_CNT_IN_CMD_MAX。 | + | INIT_CHECK | INIT_CHECK(arg != NULL, return NULL); | 判断arg != NULL 不成立的情况下执行 return NULL。 | + | INIT_CHECK_RETURN_VALUE | INIT_CHECK_RETURN_VALUE(errno == 0, -1); | 判断errno == 0 不成立的情况下执行 return -1。 | + | INIT_CHECK_ONLY_RETURN | INIT_CHECK_ONLY_RETURN(cmd != NULL); | 判断cmd != NULL 不成立的情况下执行 return。 | + | INIT_CHECK_ONLY_ELOG | INIT_CHECK_ONLY_ELOG(execv(argv[0], argv) == 0, "execv %s failed! err %d.", argv[0], errno); | 判断execv(argv[0], argv) == 0 不成立的情况下只打印log "execv %s failed! err %d."。 | + +### 开发实例 + + 1. 调用接口打印日志 + + 例如在 //base/startup/init/services/init/standard/init.c中调用接口INIT_LOGI("Start init first stage.")打印日志。 + ```c + void SystemPrepare(void) + { + MountBasicFs(); + CreateDeviceNode(); + LogInit(); + // Make sure init log always output to /dev/kmsg. + EnableDevKmsg(); + INIT_LOGI("Start init first stage."); + // Only ohos normal system support + // two stages of init. + // If we are in updater mode, only one stage of init. + if (InUpdaterMode() == 0) { + StartInitSecondStage(); + } + } + ``` + 通过dmesg可以查看打印的log,"Start init first stage."。 + + 2. 通过命令设置日志等级 + + 通过命令begetctl setloglevel level,其中level对应log的等级0~4,即INIT_DEBUG,INIT_INFO,INIT_WARN,INIT_ERROR,INIT_FATAL。 + + 设置完成之后init的g_logLevel等级立即生效,上述log接口中log等级大于等于g_logLevel才会打印日志。例如:begetctl setloglevel 3,即设置log等级为INIT_ERROR,则上述的log接口中只有INIT_LOGE、INIT_LOGF才会打印log。 + + 系统重启之后在init.cfg中"load_persist_params "命令之后生效设置的log等级。 + diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md b/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md index 69e3b2dc032c90905ea40f8475c3bb6acf56f545..0612e4eb70e19f00940c20f890f60b87f9c3b10b 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-plugin.md @@ -59,6 +59,8 @@ bootchart和bootevent只支持标准系统, begetctl 支持小型系统和标 | modulectl uninstall moduleName | 卸载动态插件,例如:
modulectl uninstall bootchart | 无 | | modulectl install moduleName | 安装动态插件,例如:
modulectl install bootchart | 无 | | modulectl list | 动态插件列表,例如:
begetctl modulectl list | 无 | +| setloglevel level | 设置log等级为info,例如:
begetctl setloglevel 1 | log等级设置范围0~4 | +| getloglevel | 获取当前init的log等级,例如:
begetctl getloglevel | 无 | | bootevent disable | 关闭bootevent插件功能,例如:
bootevent disable | 无 | | bootevent enable | 开启bootevent插件功能,例如:
begetctl 关闭bootevent插件功能 | 无 | | dump_service parameter_service trigger | 命令行展示所有trigger信息,例如:
begetctl dump_service parameter_service trigger | 无 | @@ -67,16 +69,6 @@ bootchart和bootevent只支持标准系统, begetctl 支持小型系统和标 | dump api | 命令行展示init接口信息,例如:
begetctl dump api | 无 | -### 接口说明 - - **表1** 接口介绍 -| 函数 | 函数解释 | -| ---------- | ---------- | -| void PluginExecCmdByName(const char *name, const char *cmdContent) | 通过名称启动插件。 | -| void PluginExecCmdByCmdIndex(int index, const char *cmdContent) | 通过标志启动插件。 | -| int PluginExecCmd(const char *name, int argc, const char **argv) | 命令启动插件。 | -| int AddCmdExecutor(const char *cmdName, CmdExecutor execCmd) | 添加安装插件命令。 | - ### 开发步骤 新增一个插件, 以bootchart为例: 1. 安装so文件, 定义单独文件,实现下面函数。 diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md b/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md index 0fd7c44f7e6fbe995fe8d26dd0cf13da5e1942a2..bfb9ad418ce7b7268ad2aabee9a8fc790f195e50 100644 --- a/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-sandbox.md @@ -23,6 +23,7 @@ | src-path | 需要mount的目录/文件路径 | | sandbox-path | 沙盒里面需要挂载至的目录/文件 | | sandbox-flags | mount的挂载标志位, 缺省"bind rec"标志位 | + | ignore | 是否忽略mount失败,设置为1 则忽略失败,继续往下执行 | | target-name | 需要link的目录 | | link-name | 沙盒内link后的目录 | @@ -43,13 +44,13 @@ bool InitSandboxWithName(const char *name); // 解析JSON至结构体 typedef struct { - mountlist_t *mounts; // 待 mount 的目录 - mountlist_t *fileMounts; // 待 mount 的文件 - linklist_t *links; // 待 link 的目录 - char *rootPath; // 沙盒的根路径 -> /mnt/sandbox/system|vendor|xxx - char name[MAX_BUFFER_LEN]; // 沙盒名称,system沙盒、chipset沙盒等 - bool isCreated; // 沙盒创建标志 - int ns; // namespace + ListNode pathMountsHead; // sandbox mount_path list head + ListNode fileMountsHead; // sandbox mount_file list head + ListNode linksHead; // sandbox symbolic link list head + char *rootPath; // /mnt/sandbox/system|vendor|xxx + char name[MAX_BUFFER_LEN]; // name of sandbox. i.e system, chipset etc. + bool isCreated; // sandbox already created or not + int ns; // namespace } sandbox_t; ``` ### 开发步骤 diff --git a/zh-cn/device-dev/subsystems/subsys-boot-init-sub-unit.md b/zh-cn/device-dev/subsystems/subsys-boot-init-sub-unit.md new file mode 100644 index 0000000000000000000000000000000000000000..06e7419723eae6063f99cda96bfa6101c0e241d9 --- /dev/null +++ b/zh-cn/device-dev/subsystems/subsys-boot-init-sub-unit.md @@ -0,0 +1,120 @@ +# 组件化启动 +## 概述 +### 功能简介 +构建四个基础组件镜像,提供相应的组件化目录,包括: +- 系统组件:system +- 产品通用配置组件:sys_prod +- 芯片组件:chipset +- 产品硬件配置组件:chip_prod; + +确保系统参数以及启动脚本都可以按照组件的优先级进行扫描初始化; +完成系统组件和芯片组件的独立编译构建。 +### 基本概念 +- 基础组件 + + system:系统组件文件系统挂载点,与芯片及硬件无关的平台业务; + sys_prod:对系统组件的能力扩展以及能力定制,承载产品级差异能力,存放产品相关的配置文件; + chipset:芯片组件文件系统挂载点,为系统组件提供统一的硬件抽象服务,相同的芯片平台可统一一份芯片组件; + chip_prod:单板外设特有硬件能力以及产品级硬件差异配置, 存放芯片相关的配置文件。 + +- 组件化编译构建 + + 通过"target_cpu" 指定系统组件的指令集;通过"inherit" 继承base、headless或者rich等通用组件集合;最后通过"subsystems" 定义该形态更多的部件。 + +- 系统参数以及启动脚本按照组件的优先级进行扫描初始化 + + 系统参数以及启动脚本包括:服务的cfg配置文件、param文件、沙盒json配置文件以及module插件化库文件等。相关文件优先级顺序是 /system < /chipset < /sys_prod < /chip_prod,即优先级高的配置文件将取代、更新低优先级配置。 + + +### 约束与限制 +对于标准版本和小型系统都支持组件化编译构建,以及系统参数以及启动脚本按照组件的优先级进行扫描初始化。 + +## 开发指导 +### 场景介绍 +组件化启动主要是满足厂家、硬件平台通过模块化的组合快速实现产品开发。以下以rk3568产品为例介绍组件化启动。 + +### rk3568产品的组件化构建编译 +//vendor/hihope/rk3568/config.json 配置文件实现构建此产品需要的组件,如下所示: + + { + "product_name": "rk3568", + "device_company": "rockchip", + ... + "target_cpu": "arm", + ... + "inherit": [ "productdefine/common/inherit/rich.json", "productdefine/common/inherit/chipset_common.json" ], + "subsystems": [ + { + "subsystem": "security", + "components": [ + { + "component": "selinux", + "features": [] + } + ] + } + ... + } + +从中可以看出产品名称、芯片厂家、支持的指令集等;inherit指出依赖的通用组件;subsystems指出通用组件以外的部件。 +//productdefine/common/inherit/rich.json 如下所示配置系统组件完整的部件;系统组件还可以包括base.json(所有产品都要包含的最小部件集合列表)、headless.json(没有ui界面的产品支持应用安装管理的最小部件集合)。 + + { + "version": "3.0", + "subsystems": [ + { + "subsystem": "arkui", + "components": [ + { + "component": "ace_engine", + "features": [] + }, + { + "component": "napi", + "features": [] + } + ] + }, + { + "subsystem": "account", + "components": [ + { + "component": "os_account", + "features": [] + } + ] + }, + ... + } + +### 系统参数根据优先级扫描初始化 +对于服务的cfg配置文件优先级是/system/etc < /system/etc/init < /chipset/etc,即优先级高的配置文件将取代、更新低优先级配置。例如/system/etc/init/camera_service.cfg, + + { + "services" : [{ + "name" : "camera_service", + "path" : ["/system/bin/sa_main", "/system/profile/camera_service.xml"], + "uid" : "cameraserver", + "gid" : ["system", "shell"], + "secon" : "u:r:camera_service:s0", + "permission" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"], + "permission_acls" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"] + }] + } + +同时存在/chipset/etc/camera_B_service.cfg + + { + "services" : [{ + "name" : "camera_service", + "path" : ["/system/bin/sa_main", "/system/profile/camera_B_service.xml"], + "uid" : "cameraserver", + "gid" : ["system", "shell"], + "secon" : "u:r:camera_service:s0", + "permission" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"], + "permission_acls" : ["ohos.permission.GET_SENSITIVE_PERMISSIONS"], + "disabled" : 1 + }] + } + +那么根据优先级的要求,camera_service服务"path"属性将会被优先级高的["/system/bin/sa_main", "/system/profile/camera_B_service.xml"]取代,同时增加"disabled"属性。 diff --git a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md index 43eb7d21472cf8206f517711046af4786a327516..c4ac1bf5503818d94237cf12de8f3ce7fe91ce63 100644 --- a/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md +++ b/zh-cn/device-dev/subsystems/subsys-dfx-hitracemeter.md @@ -144,44 +144,20 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 #include "hitrace_meter.h"//接口函数定义头文件 ``` -3. 接口调用示例。 +3. 接口调用,将需要跟踪的Trace value传入参数,在shell中执行hitrace命令后会自动抓取Trace数据,抓到的Trace数据中包括了函数调用过程以及调用过程消耗的内存和时间,可用于分析代码调用流程,代码性能问题。 ```cpp - #include "hitrace_meter.h" // 包含hitrace_meter.h - using namespace std; - - int main() - { - uint64_t label = BYTRACE_TAG_OHOS; - sleep(1); - CountTrace(label, "count number", 2000); // 整数跟踪 - - StartTrace(label, "func1Trace", -1); // func1Start的跟踪起始点 - sleep(1); - StartTrace(label, "func2Trace", -1); // func2Start的跟踪起始点 - sleep(2); - FinishTrace(label); // func2Trace的结束点 - sleep(1); - FinishTrace(label); // func1Trace的结束点 - - sleep(1); - CountTrace(label, "count number", 3000); // 整数跟踪 - - StartAsyncTrace(label, "asyncTrace1", 1234); // 异步asyncTrace1的开始点 - sleep(1); - StartAsyncTrace(label, "asyncTrace2", 3456); // 异步asyncTrace2的开始点 - StartAsyncTrace(label, "asyncTrace3", 5678); // 异步asyncTrace3的开始点 - sleep(1); - FinishAsyncTrace(label, "asyncTrace3", 5678); // 异步asyncTrace3的结束点 - sleep(1); - FinishAsyncTrace(label, "asyncTrace1", 1234); // 异步asyncTrace1的结束点 - sleep(1); - FinishAsyncTrace(label, "asyncTrace2", 3456); // 异步asyncTrace2的结束点 - - return 0; - } + CountTrace(label, "count number", 2000); // 整数跟踪 + + StartTrace(label, "func1Trace", -1); // func1Start的跟踪起始点 + + FinishTrace(label); // func1Trace的结束点 + + StartAsyncTrace(label, "asyncTrace1", 1234); // 异步asyncTrace1的开始点 + + FinishAsyncTrace(label, "asyncTrace2", 3456); // 异步asyncTrace2的结束点 ``` 4. 使用方法,打点编译部署完成后,运行下面命令行来抓取Trace。然后在端侧shell里运行应用,可以抓取到Trace数据。 @@ -192,6 +168,34 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 抓取之后的数据可以在smartperf中"Open trace file"或者直接拖入图形区打开,关于smartperf的详细介绍可查看 [smartperf](https://toscode.gitee.com/openharmony-sig/smartperf) 。 +## 开发示例 + +目前HiTraceMeter支持的Trace Tag在基本概念hitrace_meter.h中都已列出,我们以OHOS这个Tag为例,假设我们需要获取func1,func2函数的Trace数据,则一个使用示例如下: + +```cpp +#include "hitrace_meter.h" // 包含hitrace_meter.h +using namespace std; + +int main() +{ + uint64_t label = BYTRACE_TAG_OHOS; + sleep(1); + CountTrace(label, "count number", 2000); // 整数跟踪 + + StartTrace(label, "func1Trace", -1); // func1Start的跟踪起始点 + sleep(1); + StartTrace(label, "func2Trace", -1); // func2Start的跟踪起始点 + sleep(2); + FinishTrace(label); // func2Trace的结束点 + sleep(1); + FinishTrace(label); // func1Trace的结束点 + + return 0; + } +``` + + + ## 调测验证 以下为一个demo调试过程,该demo使用了同步接口中的StartTrace和FinishTrace。 @@ -233,13 +237,13 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 ``` ohos_executable("hitrace_example") { sources = [ "example/hitrace_example.cpp" ] - + external_deps = [ "hitrace_native:hitrace_meter" ] - + subsystem_name = "hiviewdfx" part_name = "hitrace_native" } - + group("hitrace_target") { deps = [ ":hitrace", @@ -248,7 +252,15 @@ C++接口仅系统开发者使用,JS(目前暂未开放js接口)应用开 } ``` -3. 将编译出来的hitrace_example可执行文件放到设备中的/system/bin目录下,在shell中执行hitrace_example。 +3. 将编译出来的hitrace_example可执行文件放到设备中的/system/bin目录下,在shell中执行依次执行如下命令: + + ```shell + hitrace --trace_begin ohos + hitrace_exampe + hitrace --trace_dump + ``` + + 当我们看到Trace数据中有我们需要的Trace value时,说明成功抓取Trace,成功的数据如下所示: ``` <...>-1651 (-------) [002] .... 327.194136: tracing_mark_write: S|1650|H:testAsync 111 diff --git a/zh-cn/readme/figures/build_framework_ZN.png b/zh-cn/readme/figures/build_framework_ZN.png index c969b8364b42e032465e94a0d10ad602c77c715e..03f4d6f6cffc9d3552f86f197230d01a50e2860e 100644 Binary files a/zh-cn/readme/figures/build_framework_ZN.png and b/zh-cn/readme/figures/build_framework_ZN.png differ diff --git a/zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md b/zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md new file mode 100644 index 0000000000000000000000000000000000000000..a2fa9bf54bb06e639c06b8b6ba31b1d5a64b1da9 --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.0.6-LTS.md @@ -0,0 +1,109 @@ +# OpenHarmony 3.0.6 LTS + + +## 版本概述 + +此版本为OpenHarmony-3.0-LTS分支上的维护版本,基于OpenHarmony-v3.0.5-LTS版本修复一些安全问题。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.0.6 LTS | NA | +| HUAWEI DevEco Studio(可选) | 3.0 Beta1 | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 2.2 Beta2 | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee账号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)**:通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.6-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**方式二**:通过repo + https 下载。 + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.0.6-LTS --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + + **表2** 获取源码路径 + +| **LTS版本源码** | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.0.6 | [站点](https://repo.huaweicloud.com/openharmony/os/3.0.6/code-v3.0.6-LTS.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/3.0.6/code-v3.0.6-LTS.tar.gz.sha256) | +| 标准系统Hi3516解决方案(二进制) | 3.0.6 | [站点](https://repo.huaweicloud.com/openharmony/os/3.0.6/standard.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/3.0.6/standard.tar.gz.sha256) | +| 轻量系统Hi3861解决方案(二进制) | 3.0.6 | [站点](https://repo.huaweicloud.com/openharmony/os/3.0.6/hispark_pegasus.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/3.0.6/hispark_pegasus.tar.gz.sha256) | +| 小型系统Hi3516解决方案-LiteOS(二进制) | 3.0.6 | [站点](https://repo.huaweicloud.com/openharmony/os/3.0.6/hispark_taurus.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/3.0.6/hispark_taurus.tar.gz.sha256) | +| 小型系统Hi3516解决方案-Linux(二进制) | 3.0.6 | [站点](https://repo.huaweicloud.com/openharmony/os/3.0.6/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://repo.huaweicloud.com/openharmony/os/3.0.6/hispark_taurus_linux.tar.gz.sha256) | + + +## 更新说明 + + +### 特性变更 + +此版本不涉及特性变更。 + + +### API变更 + +此版本不涉及API变更。 + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +## 修复安全漏洞列表 + + **表3** 修复的安全漏洞列表 + +| issue编号 | 描述 | 合入链接 | +| -------- | -------- | -------- | +| I5MTWL | 修复kernel_linux_5.10组件的CVE-2022-36123、CVE-2022-20369、CVE-2022-2588、CVE-2022-2586、CVE-2022-2585、CVE-2022-20368安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/402) | +| 5FYFI | 修复kernel_linux_5.10组件的CVE-2022-34918、CVE-2022-2318、CVE-2022-2380安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/331) | +| 5FYFI | 修复kernel_linux_5.10组件的CVE-2022-26365、CVE-2022-33742、CVE-2022-33743、CVE-2022-33740、CVE-2022-33741安全漏洞 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/352) | +| I5LUE0 | 修复third_party_zlib组件的CVE-2022-37434安全漏洞 | [PR](https://gitee.com/openharmony/third_party_zlib/pulls/44) | +| I5NCH4 | 小型系统Hi3516串口运行/bin/wms_server时会打印内存地址和布局信息 | [PR](https://gitee.com/openharmony/distributedschedule_samgr_lite/pulls/1) | + + diff --git a/zh-cn/release-notes/OpenHarmony-v3.1.3-release.md b/zh-cn/release-notes/OpenHarmony-v3.1.3-release.md new file mode 100644 index 0000000000000000000000000000000000000000..493b77b534ac0e867c7cd417067022a983b1df0c --- /dev/null +++ b/zh-cn/release-notes/OpenHarmony-v3.1.3-release.md @@ -0,0 +1,147 @@ +# OpenHarmony 3.1.3 Release + + +## 版本概述 + +当前版本在OpenHarmony 3.1.2 Release的基础上,修复了linux kernel、Python等开源组件的已知漏洞,增强了系统安全性。 + + +## 配套关系 + + **表1** 版本软件和工具配套关系 + +| 软件 | 版本 | 备注 | +| -------- | -------- | -------- | +| OpenHarmony | 3.1.3 Release | NA | +| Full SDK | Ohos_sdk_full 3.1.7.7 (API Version 8 Relese) | 面向OEM厂商提供,包含了需要使用系统权限的系统接口。
使用Full SDK时需要手动从镜像站点获取,并在DevEco Studio中替换,具体操作可参考[替换指南](https://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/quick-start/full-sdk-switch-guide.md)。 | +| Public SDK | Ohos_sdk_public 3.1.7.7 (API Version 8 Release) | 面向应用开发者提供,不包含需要使用系统权限的系统接口。
DevEco Studio 3.0 Beta4版本起,通过DevEco Studio获取的SDK默认为Public SDK。 | +| HUAWEI DevEco Studio(可选) | 3.0 Release for OpenHarmony | OpenHarmony应用开发推荐使用。 | +| HUAWEI DevEco Device Tool(可选) | 3.0 Release | OpenHarmony智能设备集成开发环境推荐使用。 | + + +## 源码获取 + + +### 前提条件 + +1. 注册码云gitee账号。 + +2. 注册码云SSH公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191)。 + +3. 安装[git客户端](https://gitee.com/link?target=https%3A%2F%2Fgit-scm.com%2Fbook%2Fzh%2Fv2%2F%25E8%25B5%25B7%25E6%25AD%25A5-%25E5%25AE%2589%25E8%25A3%2585-Git)和[git-lfs](https://gitee.com/vcs-all-in-one/git-lfs?_from=gitee_search#downloading)并配置用户信息。 + + ``` + git config --global user.name "yourname" + git config --global user.email "your-email-address" + git config --global credential.helper store + ``` + +4. 安装码云repo工具,可以执行如下命令。 + + ``` + curl -s https://gitee.com/oschina/repo/raw/fork_flow/repo-py3 > /usr/local/bin/repo #如果没有权限,可下载至其他目录,并将其配置到环境变量中chmod a+x /usr/local/bin/repo + pip3 install -i https://repo.huaweicloud.com/repository/pypi/simple requests + ``` + + +### 通过repo获取 + +**方式一(推荐)** + +通过repo + ssh 下载(需注册公钥,请参考[码云帮助中心](https://gitee.com/help/articles/4191))。 + + +``` +repo init -u git@gitee.com:openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.3-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + +**方式二** + +通过repo + https 下载。 + + +``` +repo init -u https://gitee.com/openharmony/manifest.git -b refs/tags/OpenHarmony-v3.1.3-Release --no-repo-verify +repo sync -c +repo forall -c 'git lfs pull' +``` + + +### 从镜像站点获取 + +**表2** 获取源码路径 + + | 版本源码 | **版本信息** | **下载站点** | **SHA256校验码** | +| -------- | -------- | -------- | -------- | +| 全量代码(标准、轻量和小型系统) | 3.1.3 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/code-v3.1.3-Release.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/code-v3.1.3-Release.tar.gz.sha256) | +| Hi3516标准系统解决方案(二进制) | 3.1.3 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/standard_hi3516.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/standard_hi3516.tar.gz.sha256) | +| RK3568标准系统解决方案(二进制) | 3.1.3 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/code-v3.1.3-Release.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/standard_rk3568.tar.gz.sha256) | +| Hi3861轻量系统解决方案(二进制) | 3.1.3 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/hispark_pegasus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/hispark_pegasus.tar.gz.sha256) | +| Hi3516小型系统解决方案-LiteOS(二进制) | 3.1.3 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/hispark_taurus.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/hispark_taurus.tar.gz.sha256) | +| Hi3516小型系统解决方案-Linux(二进制) | 3.1.3 Release | [站点](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/hispark_taurus_linux.tar.gz) | [SHA256校验码](https://mirrors.huaweicloud.com/openharmony/os/3.1.3/hispark_taurus_linux.tar.gz.sha256) | +| 标准系统Full SDK包(Mac) | 3.1.7.7 | [站点](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-mac-full.tar.gz) | [SHA256校验码](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-mac-full.tar.gz.sha256) | +| 标准系统Full SDK包(Windows\Linux) | 3.1.7.7 | [站点](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-full.tar.gz) | [SHA256校验码](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-full.tar.gz.sha256) | +| 标准系统Public SDK包(Mac) | 3.1.7.7 | [站点](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-mac-public.tar.gz) | [SHA256校验码](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-mac-public.tar.gz.sha256) | +| 标准系统Public SDK包(Windows\Linux) | 3.1.7.7 | [站点](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-public.tar.gz) | [SHA256校验码](https://gitee.com/link?target=https%3A%2F%2Fmirrors.huaweicloud.com%2Fopenharmony%2Fos%2F3.1.2%2Fsdk-patch%2Fohos-sdk-public.tar.gz.sha256) | + + +## 更新说明 + +本版本在OpenHarmony 3.1.2 Release的基础上有如下变更。 + + +### 特性变更 + +本次版本无新增特性及变更。 + +API变更 + + +3.1.3 Release对比3.1.2 Release API接口无变更。 + + + +### 芯片及开发板适配 + +芯片及开发板适配状态请参考[SIG-Devboard](https://gitee.com/openharmony/community/blob/master/sig/sig-devboard/sig_devboard_cn.md)信息。 + + +## 修复缺陷列表 + +**表3** 修复缺陷ISSUE列表 + + | 子系统 | 问题描述 | +| -------- | -------- | +| 媒体子系统 | 标准系统Hi3516在图库中播放视频,单板有概率异常重启([I5N70Z](https://gitee.com/openharmony/kernel_linux_config/issues/I5N70Z)) | + + +## 修复安全漏洞列表 + +**表4** 修复安全问题列表 + + | ISSUE | 问题描述 | 修复链接 | +| -------- | -------- | -------- | +| I5QAEX | 手机开启热点,测试机设置应用WLAN界面执行连接wifi操作,日志中打印ip地址。 | [PR](https://gitee.com/openharmony/communication_netmanager_base/pulls/527) | +| I5QBQD | dsoftbus_standard:启动日志中存在明文mac地址打印。 | [PR](https://gitee.com/openharmony/communication_dsoftbus/pulls/2328) | +| I5R13H | dhd启动日志中存在明文mac地址信息打印。 | [PR](https://gitee.com/openharmony/kernel_linux_patches/pulls/304) | +| I5MVEM | 修复组件css-what 上的CVE-2021-33587漏洞。 | [PR](https://gitee.com/openharmony/third_party_css-what/pulls/8) | +| I5QBNS | 修复组件curl上的CVE-2022-35252漏洞。 | [PR](https://gitee.com/openharmony/third_party_curl/pulls/83) | +| I5MR1V | 修复组件linux_kernel上的CVE-2022-2588、CVE-2022-2585、CVE-2022-20369、CVE-2022-20368安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/426) | +| I5MQS0 | 修复组件linux_kernel上的CVE-2022-2586安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/427) | +| I5P0W4 | 修复组件linux_kernel上的CVE-2022-2959、CVE-2022-2991安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/428) | +| I5P0TX | 修复组件linux_kernel上的CVE-2022-2938安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/430) | +| I5QBWI | 修复组件linux_kernel上的CVE-2022-3028、CVE-2022-2977、CVE-2022-2964安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/440) | +| I5QC1O | 修复组件linux_kernel上的CVE-2022-39188、CVE-2022-3078、CVE-2022-2905、CVE-2022-39842安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/450) | +| I5P0WN | 修复组件linux_kernel上的CVE-2022-26373安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/461) | +| I5NZKV | 修复组件linux_kernel上的CVE-2022-2503安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/431) | +| I5R2L0 | 修复组件linux_kernel上的CVE-2022-3061安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/443) | +| I5R2JQ | 修复组件linux_kernel上的CVE-2022-2663、CVE-2022-39190、CVE-2022-39189安全漏洞。 | [PR](https://gitee.com/openharmony/kernel_linux_5.10/pulls/445) | +| I5R8X1 | 修复组件Python上的CVE-2021-29921安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/19) | +| I5R8X1 | 修复组件Python上的CVE-2022-0391安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/23) | +| I5R8X1 | 修复组件Python上的CVE-2021-3737安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/20) | +| I5R8X1 | 修复组件Python上的CVE-2021-4189安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/21) | +| I5R8X1 | 修复组件Python上的CVE-2021-3733安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/22) | +| I5R8X1 | 修复组件Python上的CVE-2021-28861安全漏洞。 | [PR](https://gitee.com/openharmony/third_party_python/pulls/24) | + diff --git a/zh-cn/release-notes/Readme.md b/zh-cn/release-notes/Readme.md index 090ebf20f802b3c21388c2555e4adf46800025da..36430bb2fd1f920166bfe0f29e88ac42d02c5035 100644 --- a/zh-cn/release-notes/Readme.md +++ b/zh-cn/release-notes/Readme.md @@ -1,30 +1,33 @@ # OpenHarmony Release Notes ## OpenHarmony 3.x Releases -- [OpenHarmony v3.2 Beta3 (2022-09-30)](OpenHarmony-v3.2-beta3.md) -- [OpenHarmony v3.1.2 Release (2022-08-24)](OpenHarmony-v3.1.2-release.md) -- [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md) -- [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md) -- [OpenHarmony v3.1.1 Release (2022-05-31)](OpenHarmony-v3.1.1-release.md) -- [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md) -- [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) -- [OpenHarmony v3.0.5 LTS (2022-07-01)](OpenHarmony-v3.0.5-LTS.md) -- [OpenHarmony v3.0.3 LTS (2022-04-08)](OpenHarmony-v3.0.3-LTS.md) -- [OpenHarmony v3.0.2 LTS (2022-03-18)](OpenHarmony-v3.0.2-LTS.md) -- [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md) -- [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md) +- [OpenHarmony v3.2 Beta3 (2022-09-30)](OpenHarmony-v3.2-beta3.md) +- [OpenHarmony v3.2 Beta2 (2022-07-30)](OpenHarmony-v3.2-beta2.md) +- [OpenHarmony v3.2 Beta1 (2022-05-31)](OpenHarmony-v3.2-beta1.md) +- [OpenHarmony v3.1 Release (2022-03-30)](OpenHarmony-v3.1-release.md) + - [OpenHarmony v3.1.3 Release (2022-09-30)](OpenHarmony-v3.1.3-release.md) + - [OpenHarmony v3.1.2 Release (2022-08-24)](OpenHarmony-v3.1.2-release.md) + - [OpenHarmony v3.1.1 Release (2022-05-31)](OpenHarmony-v3.1.1-release.md) +- [OpenHarmony v3.1 Beta (2021-12-31)](OpenHarmony-v3.1-beta.md) +- [OpenHarmony v3.0 LTS (2021-09-30)](OpenHarmony-v3.0-LTS.md) + - [OpenHarmony v3.0.6 LTS (2022-09-15)](OpenHarmony-v3.0.6-LTS.md) + - [OpenHarmony v3.0.5 LTS (2022-07-01)](OpenHarmony-v3.0.5-LTS.md) + - [OpenHarmony v3.0.3 LTS (2022-04-08)](OpenHarmony-v3.0.3-LTS.md) + - [OpenHarmony v3.0.2 LTS (2022-03-18)](OpenHarmony-v3.0.2-LTS.md) + - [OpenHarmony v3.0.1 LTS (2022-01-12)](OpenHarmony-v3.0.1-LTS.md) ## OpenHarmony 2.x Releases -- [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md) -- [OpenHarmony 2.0 Canary (2021-06-01)](OpenHarmony-2-0-Canary.md) +- [OpenHarmony v2.2 beta2 (2021-08-04)](OpenHarmony-v2.2-beta2.md) +- [OpenHarmony 2.0 Canary (2021-06-01)](OpenHarmony-2-0-Canary.md) ## OpenHarmony 1.x Releases -- [OpenHarmony v1.1.5 LTS (2022-08-24)](OpenHarmony-v1.1.5-LTS.md) -- [OpenHarmony v1.1.4 LTS (2022-02-11)](OpenHarmony-v1-1-4-LTS.md) -- [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md) -- [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md) -- [OpenHarmony 1.1.1 LTS (2021-06-22)](OpenHarmony-1-1-1-LTS.md) -- [OpenHarmony 1.1.0 LTS (2021-04-01)](OpenHarmony-1-1-0-LTS.md) -- [OpenHarmony 1.0 (2020-09-10)](OpenHarmony-1-0.md) + +- [OpenHarmony v1.0 (2020-09-10)](OpenHarmony-1-0.md) + - [OpenHarmony v1.1.5 LTS (2022-08-24)](OpenHarmony-v1.1.5-LTS.md) + - [OpenHarmony v1.1.4 LTS (2022-02-11)](OpenHarmony-v1-1-4-LTS.md) + - [OpenHarmony v1.1.3 LTS (2021-09-30)](OpenHarmony-v1-1-3-LTS.md) + - [OpenHarmony v1.1.2 LTS (2021-08-04)](OpenHarmony-v1.1.2-LTS.md) + - [OpenHarmony v1.1.1 LTS (2021-06-22)](OpenHarmony-1-1-1-LTS.md) + - [OpenHarmony v1.1.0 LTS (2021-04-01)](OpenHarmony-1-1-0-LTS.md) diff --git a/zh-cn/website.md b/zh-cn/website.md index 50ce7f0dfc23de70e0de59450db04c3bdfdf2fd7..6296502c6013f3ec22f4ecf3ebdc6a45d2b10c79 100644 --- a/zh-cn/website.md +++ b/zh-cn/website.md @@ -7,14 +7,17 @@ - [OpenHarmony v3.2 Beta3 (2022-09-30)](release-notes/OpenHarmony-v3.2-beta3.md) - [OpenHarmony v3.2 Beta2 (2022-07-30)](release-notes/OpenHarmony-v3.2-beta2.md) - [OpenHarmony v3.2 Beta1 (2022-05-31)](release-notes/OpenHarmony-v3.2-beta1.md) - - [OpenHarmony v3.1.1 Release (2022-05-31)](release-notes/OpenHarmony-v3.1.1-release.md) - [OpenHarmony v3.1 Release (2022-03-30)](release-notes/OpenHarmony-v3.1-release.md) + - [OpenHarmony v3.1.3 Release (2022-09-30)](release-notes/OpenHarmony-v3.1.3-release.md) + - [OpenHarmony v3.1.2 Release (2022-08-24)](release-notes/OpenHarmony-v3.1.2-release.md) + - [OpenHarmony v3.1.1 Release (2022-05-31)](release-notes/OpenHarmony-v3.1.1-release.md) - [OpenHarmony v3.1 Beta (2021-12-31)](release-notes/OpenHarmony-v3.1-beta.md) - - [OpenHarmony v3.0.5 LTS (2022-07-01)](release-notes/OpenHarmony-v3.0.5-LTS.md) - - [OpenHarmony v3.0.3 LTS (2022-04-08)](release-notes/OpenHarmony-v3.0.3-LTS.md) - - [OpenHarmony v3.0.2 LTS (2022-03-18)](release-notes/OpenHarmony-v3.0.2-LTS.md) - - [OpenHarmony v3.0.1 LTS (2022-01-12)](release-notes/OpenHarmony-v3.0.1-LTS.md) - [OpenHarmony v3.0 LTS (2021-09-30)](release-notes/OpenHarmony-v3.0-LTS.md) + - [OpenHarmony v3.0.6 LTS (2022-09-15)](release-notes/OpenHarmony-v3.0.6-LTS.md) + - [OpenHarmony v3.0.5 LTS (2022-07-01)](release-notes/OpenHarmony-v3.0.5-LTS.md) + - [OpenHarmony v3.0.3 LTS (2022-04-08)](release-notes/OpenHarmony-v3.0.3-LTS.md) + - [OpenHarmony v3.0.2 LTS (2022-03-18)](release-notes/OpenHarmony-v3.0.2-LTS.md) + - [OpenHarmony v3.0.1 LTS (2022-01-12)](release-notes/OpenHarmony-v3.0.1-LTS.md) - OpenHarmony 2.x Releases - [OpenHarmony v2.2 beta2 (2021-08-04)](release-notes/OpenHarmony-v2.2-beta2.md) @@ -22,12 +25,13 @@ - OpenHarmony 1.x Releases - - [OpenHarmony v1.1.4 LTS (2022-02-11)](release-notes/OpenHarmony-v1-1-4-LTS.md) - - [OpenHarmony v1.1.3 LTS (2021-09-30)](release-notes/OpenHarmony-v1-1-3-LTS.md) - - [OpenHarmony v1.1.2 LTS (2021-08-04)](release-notes/OpenHarmony-v1.1.2-LTS.md) - - [OpenHarmony 1.1.1 LTS (2021-06-22)](release-notes/OpenHarmony-1-1-1-LTS.md) - - [OpenHarmony 1.1.0 LTS (2021-04-01)](release-notes/OpenHarmony-1-1-0-LTS.md) - [OpenHarmony 1.0 (2020-09-10)](release-notes/OpenHarmony-1-0.md) + - [OpenHarmony v1.1.5 LTS (2022-08-24)](release-notes/OpenHarmony-v1.1.5-LTS.md) + - [OpenHarmony v1.1.4 LTS (2022-02-11)](release-notes/OpenHarmony-v1-1-4-LTS.md) + - [OpenHarmony v1.1.3 LTS (2021-09-30)](release-notes/OpenHarmony-v1-1-3-LTS.md) + - [OpenHarmony v1.1.2 LTS (2021-08-04)](release-notes/OpenHarmony-v1.1.2-LTS.md) + - [OpenHarmony v1.1.1 LTS (2021-06-22)](release-notes/OpenHarmony-1-1-1-LTS.md) + - [OpenHarmony v1.1.0 LTS (2021-04-01)](release-notes/OpenHarmony-1-1-0-LTS.md) - API差异报告 - OpenHarmony 3.2 Beta3